
/*!
 * jQuery JavaScript Library v1.4.2
 * http://jquery.com/
 *
 * Copyright 2010, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 * 
 * Includes Sizzle.js
 * http://sizzlejs.com/
 * Copyright 2010, The Dojo Foundation
 * Released under the MIT, BSD, and GPL Licenses.
 *
 * Date: Sat Feb 13 22:33:48 2010 -0500
 */
(function(A,w){function ma(){if(!c.isReady){try{s.documentElement.doScroll("left")}catch(a){setTimeout(ma,1);return}c.ready()}}function Qa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function X(a,b,d,f,e,j){var i=a.length;if(typeof b==="object"){for(var o in b)X(a,o,b[o],f,e,d);return a}if(d!==w){f=!j&&f&&c.isFunction(d);for(o=0;o<i;o++)e(a[o],b,f?d.call(a[o],o,e(a[o],b)):d,j);return a}return i?
e(a[0],b):w}function J(){return(new Date).getTime()}function Y(){return false}function Z(){return true}function na(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function oa(a){var b,d=[],f=[],e=arguments,j,i,o,k,n,r;i=c.data(this,"events");if(!(a.liveFired===this||!i||!i.live||a.button&&a.type==="click")){a.liveFired=this;var u=i.live.slice(0);for(k=0;k<u.length;k++){i=u[k];i.origType.replace(O,"")===a.type?f.push(i.selector):u.splice(k--,1)}j=c(a.target).closest(f,a.currentTarget);n=0;for(r=
j.length;n<r;n++)for(k=0;k<u.length;k++){i=u[k];if(j[n].selector===i.selector){o=j[n].elem;f=null;if(i.preType==="mouseenter"||i.preType==="mouseleave")f=c(a.relatedTarget).closest(i.selector)[0];if(!f||f!==o)d.push({elem:o,handleObj:i})}}n=0;for(r=d.length;n<r;n++){j=d[n];a.currentTarget=j.elem;a.data=j.handleObj.data;a.handleObj=j.handleObj;if(j.handleObj.origHandler.apply(j.elem,e)===false){b=false;break}}return b}}function pa(a,b){return"live."+(a&&a!=="*"?a+".":"")+b.replace(/\./g,"`").replace(/ /g,
"&")}function qa(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function ra(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var j in f)for(var i in f[j])c.event.add(this,j,f[j][i],f[j][i].data)}}})}function sa(a,b,d){var f,e,j;b=b&&b[0]?b[0].ownerDocument||b[0]:s;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===s&&!ta.test(a[0])&&(c.support.checkClone||!ua.test(a[0]))){e=
true;if(j=c.fragments[a[0]])if(j!==1)f=j}if(!f){f=b.createDocumentFragment();c.clean(a,b,f,d)}if(e)c.fragments[a[0]]=j?f:1;return{fragment:f,cacheable:e}}function K(a,b){var d={};c.each(va.concat.apply([],va.slice(0,b)),function(){d[this]=a});return d}function wa(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Ra=A.jQuery,Sa=A.$,s=A.document,T,Ta=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Ua=/^.[^:#\[\.,]*$/,Va=/\S/,
Wa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Xa=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,P=navigator.userAgent,xa=false,Q=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,R=Array.prototype.slice,ya=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(a==="body"&&!b){this.context=s;this[0]=s.body;this.selector="body";this.length=1;return this}if(typeof a==="string")if((d=Ta.exec(a))&&
(d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:s;if(a=Xa.exec(a))if(c.isPlainObject(b)){a=[s.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=sa([d[1]],[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}return c.merge(this,a)}else{if(b=s.getElementById(d[2])){if(b.id!==d[2])return T.find(a);this.length=1;this[0]=b}this.context=s;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=s;a=s.getElementsByTagName(a);return c.merge(this,
a)}else return!b||b.jquery?(b||T).find(a):c(b).find(a);else if(c.isFunction(a))return T.ready(a);if(a.selector!==w){this.selector=a.selector;this.context=a.context}return c.makeArray(a,this)},selector:"",jquery:"1.4.2",length:0,size:function(){return this.length},toArray:function(){return R.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){var f=c();c.isArray(a)?ba.apply(f,a):c.merge(f,a);f.prevObject=this;f.context=this.context;if(b===
"find")f.selector=this.selector+(this.selector?" ":"")+d;else if(b)f.selector=this.selector+"."+b+"("+d+")";return f},each:function(a,b){return c.each(this,a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(s,c);else Q&&Q.push(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(R.apply(this,arguments),"slice",R.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this,
function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject||c(null)},push:ba,sort:[].sort,splice:[].splice};c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,j,i,o;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(j in e){i=a[j];o=e[j];if(a!==o)if(f&&o&&(c.isPlainObject(o)||c.isArray(o))){i=i&&(c.isPlainObject(i)||
c.isArray(i))?i:c.isArray(o)?[]:{};a[j]=c.extend(f,i,o)}else if(o!==w)a[j]=o}return a};c.extend({noConflict:function(a){A.$=Sa;if(a)A.jQuery=Ra;return c},isReady:false,ready:function(){if(!c.isReady){if(!s.body)return setTimeout(c.ready,13);c.isReady=true;if(Q){for(var a,b=0;a=Q[b++];)a.call(s,c);Q=null}c.fn.triggerHandler&&c(s).triggerHandler("ready")}},bindReady:function(){if(!xa){xa=true;if(s.readyState==="complete")return c.ready();if(s.addEventListener){s.addEventListener("DOMContentLoaded",
L,false);A.addEventListener("load",c.ready,false)}else if(s.attachEvent){s.attachEvent("onreadystatechange",L);A.attachEvent("onload",c.ready);var a=false;try{a=A.frameElement==null}catch(b){}s.documentElement.doScroll&&a&&ma()}}},isFunction:function(a){return $.call(a)==="[object Function]"},isArray:function(a){return $.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||$.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!aa.call(a,"constructor")&&!aa.call(a.constructor.prototype,
"isPrototypeOf"))return false;var b;for(b in a);return b===w||aa.call(a,b)},isEmptyObject:function(a){for(var b in a)return false;return true},error:function(a){throw a;},parseJSON:function(a){if(typeof a!=="string"||!a)return null;a=c.trim(a);if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return A.JSON&&A.JSON.parse?A.JSON.parse(a):(new Function("return "+
a))();else c.error("Invalid JSON: "+a)},noop:function(){},globalEval:function(a){if(a&&Va.test(a)){var b=s.getElementsByTagName("head")[0]||s.documentElement,d=s.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(s.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,j=a.length,i=j===w||c.isFunction(a);if(d)if(i)for(f in a){if(b.apply(a[f],
d)===false)break}else for(;e<j;){if(b.apply(a[e++],d)===false)break}else if(i)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=a[0];e<j&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Wa,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ba.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d=0,f=b.length;d<f;d++)if(b[d]===
a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!==w;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,j=a.length;e<j;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,j=0,i=a.length;j<i;j++){e=b(a[j],j,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b==="string"){d=a;a=d[b];b=w}else if(b&&
!c.isFunction(b)){d=b;b=w}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b},uaMatch:function(a){a=a.toLowerCase();a=/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||!/compatible/.test(a)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(a)||[];return{browser:a[1]||"",version:a[2]||"0"}},browser:{}});P=c.uaMatch(P);if(P.browser){c.browser[P.browser]=true;c.browser.version=P.version}if(c.browser.webkit)c.browser.safari=
true;if(ya)c.inArray=function(a,b){return ya.call(b,a)};T=c(s);if(s.addEventListener)L=function(){s.removeEventListener("DOMContentLoaded",L,false);c.ready()};else if(s.attachEvent)L=function(){if(s.readyState==="complete"){s.detachEvent("onreadystatechange",L);c.ready()}};(function(){c.support={};var a=s.documentElement,b=s.createElement("script"),d=s.createElement("div"),f="script"+J();d.style.display="none";d.innerHTML="   <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
var e=d.getElementsByTagName("*"),j=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!j)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(j.getAttribute("style")),hrefNormalized:j.getAttribute("href")==="/a",opacity:/^0.55$/.test(j.style.opacity),cssFloat:!!j.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:s.createElement("select").appendChild(s.createElement("option")).selected,
parentNode:d.removeChild(d.appendChild(s.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(i){}a.insertBefore(b,a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}try{delete b.test}catch(o){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function k(){c.support.noCloneEvent=
false;d.detachEvent("onclick",k)});d.cloneNode(true).fireEvent("onclick")}d=s.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=s.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var k=s.createElement("div");k.style.width=k.style.paddingLeft="1px";s.body.appendChild(k);c.boxModel=c.support.boxModel=k.offsetWidth===2;s.body.removeChild(k).style.display="none"});a=function(k){var n=
s.createElement("div");k="on"+k;var r=k in n;if(!r){n.setAttribute(k,"return;");r=typeof n[k]==="function"}return r};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=j=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ya=0,za={};c.extend({cache:{},expando:G,noData:{embed:true,object:true,
applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var f=a[G],e=c.cache;if(!f&&typeof b==="string"&&d===w)return null;f||(f=++Ya);if(typeof b==="object"){a[G]=f;e[f]=c.extend(true,{},b)}else if(!e[f]){a[G]=f;e[f]={}}a=e[f];if(d!==w)a[b]=d;return typeof b==="string"?a[b]:a}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{if(c.support.deleteExpando)delete a[c.expando];
else a.removeAttribute&&a.removeAttribute(c.expando);delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===w){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===w&&this.length)f=c.data(this[0],a);return f===w&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this,
a,b)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===
w)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var Aa=/[\n\t]/g,ca=/\s+/,Za=/\r/g,$a=/href|src|style/,ab=/(button|input)/i,bb=/(button|input|object|select|textarea)/i,
cb=/^(a|area)$/i,Ba=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(n){var r=c(this);r.addClass(a.call(this,n,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className){for(var j=" "+e.className+" ",
i=e.className,o=0,k=b.length;o<k;o++)if(j.indexOf(" "+b[o]+" ")<0)i+=" "+b[o];e.className=c.trim(i)}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(k){var n=c(this);n.removeClass(a.call(this,k,n.attr("class")))});if(a&&typeof a==="string"||a===w)for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var j=(" "+e.className+" ").replace(Aa," "),i=0,o=b.length;i<o;i++)j=j.replace(" "+b[i]+" ",
" ");e.className=c.trim(j)}else e.className=""}return this},toggleClass:function(a,b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var j=c(this);j.toggleClass(a.call(this,e,j.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,j=0,i=c(this),o=b,k=a.split(ca);e=k[j++];){o=f?o:!i.hasClass(e);i[o?"addClass":"removeClass"](e)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className=
this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(Aa," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===w){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var j=b?d:0;for(d=b?d+1:e.length;j<d;j++){var i=
e[j];if(i.selected){a=c(i).val();if(b)return a;f.push(a)}}return f}if(Ba.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Za,"")}return w}var o=c.isFunction(a);return this.each(function(k){var n=c(this),r=a;if(this.nodeType===1){if(o)r=a.call(this,k,n.val());if(typeof r==="number")r+="";if(c.isArray(r)&&Ba.test(this.type))this.checked=c.inArray(n.val(),r)>=0;else if(c.nodeName(this,"select")){var u=c.makeArray(r);c("option",this).each(function(){this.selected=
c.inArray(c(this).val(),u)>=0});if(!u.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return w;if(f&&b in c.attrFn)return c(a)[b](d);f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==w;b=f&&c.props[b]||b;if(a.nodeType===1){var j=$a.test(b);if(b in a&&f&&!j){if(e){b==="type"&&ab.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");
a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:bb.test(a.nodeName)||cb.test(a.nodeName)&&a.href?0:w;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&j?a.getAttribute(b,2):a.getAttribute(b);return a===null?w:a}return c.style(a,b,d)}});var O=/\.(.*)$/,db=function(a){return a.replace(/[^\w\s\.\|`]/g,
function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==A&&!a.frameElement)a=A;var e,j;if(d.handler){e=d;d=e.handler}if(!d.guid)d.guid=c.guid++;if(j=c.data(a)){var i=j.events=j.events||{},o=j.handle;if(!o)j.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,arguments):w};o.elem=a;b=b.split(" ");for(var k,n=0,r;k=b[n++];){j=e?c.extend({},e):{handler:d,data:f};if(k.indexOf(".")>-1){r=k.split(".");
k=r.shift();j.namespace=r.slice(0).sort().join(".")}else{r=[];j.namespace=""}j.type=k;j.guid=d.guid;var u=i[k],z=c.event.special[k]||{};if(!u){u=i[k]=[];if(!z.setup||z.setup.call(a,f,r,o)===false)if(a.addEventListener)a.addEventListener(k,o,false);else a.attachEvent&&a.attachEvent("on"+k,o)}if(z.add){z.add.call(a,j);if(!j.handler.guid)j.handler.guid=d.guid}u.push(j);c.event.global[k]=true}a=null}}},global:{},remove:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){var e,j=0,i,o,k,n,r,u,z=c.data(a),
C=z&&z.events;if(z&&C){if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(e in C)c.event.remove(a,e+b)}else{for(b=b.split(" ");e=b[j++];){n=e;i=e.indexOf(".")<0;o=[];if(!i){o=e.split(".");e=o.shift();k=new RegExp("(^|\\.)"+c.map(o.slice(0).sort(),db).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(r=C[e])if(d){n=c.event.special[e]||{};for(B=f||0;B<r.length;B++){u=r[B];if(d.guid===u.guid){if(i||k.test(u.namespace)){f==null&&r.splice(B--,1);n.remove&&n.remove.call(a,u)}if(f!=
null)break}}if(r.length===0||f!=null&&r.length===1){if(!n.teardown||n.teardown.call(a,o)===false)Ca(a,e,z.handle);delete C[e]}}else for(var B=0;B<r.length;B++){u=r[B];if(i||k.test(u.namespace)){c.event.remove(a,n,u.handler,B);r.splice(B--,1)}}}if(c.isEmptyObject(C)){if(b=z.handle)b.elem=null;delete z.events;delete z.handle;c.isEmptyObject(z)&&c.removeData(a)}}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[G]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf("!")>=0){a.type=
e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return w;a.result=w;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d,b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(j){}if(!a.isPropagationStopped()&&
f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){f=a.target;var i,o=c.nodeName(f,"a")&&e==="click",k=c.event.special[e]||{};if((!k._default||k._default.call(d,a)===false)&&!o&&!(f&&f.nodeName&&c.noData[f.nodeName.toLowerCase()])){try{if(f[e]){if(i=f["on"+e])f["on"+e]=null;c.event.triggered=true;f[e]()}}catch(n){}if(i)f["on"+e]=i;c.event.triggered=false}}},handle:function(a){var b,d,f,e;a=arguments[0]=c.event.fix(a||A.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive;
if(!b){d=a.type.split(".");a.type=d.shift();f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)")}e=c.data(this,"events");d=e[a.type];if(e&&d){d=d.slice(0);e=0;for(var j=d.length;e<j;e++){var i=d[e];if(b||f.test(i.namespace)){a.handler=i.handler;a.data=i.data;a.handleObj=i;i=i.handler.apply(this,arguments);if(i!==w){a.result=i;if(i===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix:function(a){if(a[G])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement||s;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=s.documentElement;d=s.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop||
d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(!a.which&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==w)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,a.origType,c.extend({},a,{handler:oa}))},remove:function(a){var b=true,d=a.origType.replace(O,"");c.each(c.data(this,
"events").live||[],function(){if(d===this.origType.replace(O,""))return b=false});b&&c.event.remove(this,a.origType,oa)}},beforeunload:{setup:function(a,b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};var Ca=s.removeEventListener?function(a,b,d){a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=
a;this.type=a.type}else this.type=a;this.timeStamp=J();this[G]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=Z;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=Z;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z;this.stopPropagation()},isDefaultPrevented:Y,isPropagationStopped:Y,
isImmediatePropagationStopped:Y};var Da=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},Ea=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?Ea:Da,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ea:Da)}}});if(!c.support.submitBubbles)c.event.special.submit=
{setup:function(){if(this.nodeName.toLowerCase()!=="form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length)return na("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13)return na("submit",this,arguments)})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}};
if(!c.support.changeBubbles){var da=/textarea|input|select/i,ea,Fa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},fa=function(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Fa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",
e);if(!(f===w||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:fa,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return fa.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return fa.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a,
"_change_data",Fa(a))}},setup:function(){if(this.type==="file")return false;for(var a in ea)c.event.add(this,a+".specialChange",ea[a]);return da.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return da.test(this.nodeName)}};ea=c.event.special.change.filters}s.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,f)}c.event.special[b]={setup:function(){this.addEventListener(a,
d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var j in d)this[b](j,f,d[j],e);return this}if(c.isFunction(f)){e=f;f=w}var i=b==="one"?c.proxy(e,function(k){c(this).unbind(k,i);return e.apply(this,arguments)}):e;if(d==="unload"&&b!=="one")this.one(d,f,e);else{j=0;for(var o=this.length;j<o;j++)c.event.add(this[j],d,i,f)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&&
!a.preventDefault)for(var d in a)this.unbind(d,a[d]);else{d=0;for(var f=this.length;d<f;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,f){return this.live(b,d,f,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return a.result}},
toggle:function(a){for(var b=arguments,d=1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(f){var e=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Ga={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,f,e,j){var i,o=0,k,n,r=j||this.selector,
u=j?this:c(this.context);if(c.isFunction(f)){e=f;f=w}for(d=(d||"").split(" ");(i=d[o++])!=null;){j=O.exec(i);k="";if(j){k=j[0];i=i.replace(O,"")}if(i==="hover")d.push("mouseenter"+k,"mouseleave"+k);else{n=i;if(i==="focus"||i==="blur"){d.push(Ga[i]+k);i+=k}else i=(Ga[i]||i)+k;b==="live"?u.each(function(){c.event.add(this,pa(i,r),{data:f,selector:r,handler:e,origType:i,origHandler:e,preType:n})}):u.unbind(pa(i,r),e)}}return this}});c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),
function(a,b){c.fn[b]=function(d){return d?this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});A.attachEvent&&!A.addEventListener&&A.attachEvent("onunload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});(function(){function a(g){for(var h="",l,m=0;g[m];m++){l=g[m];if(l.nodeType===3||l.nodeType===4)h+=l.nodeValue;else if(l.nodeType!==8)h+=a(l.childNodes)}return h}function b(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];
if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1&&!p){t.sizcache=l;t.sizset=q}if(t.nodeName.toLowerCase()===h){y=t;break}t=t[g]}m[q]=y}}}function d(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1){if(!p){t.sizcache=l;t.sizset=q}if(typeof h!=="string"){if(t===h){y=true;break}}else if(k.filter(h,[t]).length>0){y=t;break}}t=t[g]}m[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
e=0,j=Object.prototype.toString,i=false,o=true;[0,0].sort(function(){o=false;return 0});var k=function(g,h,l,m){l=l||[];var q=h=h||s;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||typeof g!=="string")return l;for(var p=[],v,t,y,S,H=true,M=x(h),I=g;(f.exec(""),v=f.exec(I))!==null;){I=v[3];p.push(v[1]);if(v[2]){S=v[3];break}}if(p.length>1&&r.exec(g))if(p.length===2&&n.relative[p[0]])t=ga(p[0]+p[1],h);else for(t=n.relative[p[0]]?[h]:k(p.shift(),h);p.length;){g=p.shift();if(n.relative[g])g+=p.shift();
t=ga(g,t)}else{if(!m&&p.length>1&&h.nodeType===9&&!M&&n.match.ID.test(p[0])&&!n.match.ID.test(p[p.length-1])){v=k.find(p.shift(),h,M);h=v.expr?k.filter(v.expr,v.set)[0]:v.set[0]}if(h){v=m?{expr:p.pop(),set:z(m)}:k.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=v.expr?k.filter(v.expr,v.set):v.set;if(p.length>0)y=z(t);else H=false;for(;p.length;){var D=p.pop();v=D;if(n.relative[D])v=p.pop();else D="";if(v==null)v=h;n.relative[D](y,v,M)}}else y=[]}y||(y=t);y||k.error(D||
g);if(j.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))l.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&l.push(t[g]);else l.push.apply(l,y);else z(y,l);if(S){k(S,q,l,m);k.uniqueSort(l)}return l};k.uniqueSort=function(g){if(B){i=o;g.sort(B);if(i)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};k.matches=function(g,h){return k(g,null,null,h)};k.find=function(g,h,l){var m,q;if(!g)return[];
for(var p=0,v=n.order.length;p<v;p++){var t=n.order[p];if(q=n.leftMatch[t].exec(g)){var y=q[1];q.splice(1,1);if(y.substr(y.length-1)!=="\\"){q[1]=(q[1]||"").replace(/\\/g,"");m=n.find[t](q,h,l);if(m!=null){g=g.replace(n.match[t],"");break}}}}m||(m=h.getElementsByTagName("*"));return{set:m,expr:g}};k.filter=function(g,h,l,m){for(var q=g,p=[],v=h,t,y,S=h&&h[0]&&x(h[0]);g&&h.length;){for(var H in n.filter)if((t=n.leftMatch[H].exec(g))!=null&&t[2]){var M=n.filter[H],I,D;D=t[1];y=false;t.splice(1,1);if(D.substr(D.length-
1)!=="\\"){if(v===p)p=[];if(n.preFilter[H])if(t=n.preFilter[H](t,v,l,p,m,S)){if(t===true)continue}else y=I=true;if(t)for(var U=0;(D=v[U])!=null;U++)if(D){I=M(D,t,U,v);var Ha=m^!!I;if(l&&I!=null)if(Ha)y=true;else v[U]=false;else if(Ha){p.push(D);y=true}}if(I!==w){l||(v=p);g=g.replace(n.match[H],"");if(!y)return[];break}}}if(g===q)if(y==null)k.error(g);else break;q=g}return v};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var n=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,
CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},
relative:{"+":function(g,h){var l=typeof h==="string",m=l&&!/\W/.test(h);l=l&&!m;if(m)h=h.toLowerCase();m=0;for(var q=g.length,p;m<q;m++)if(p=g[m]){for(;(p=p.previousSibling)&&p.nodeType!==1;);g[m]=l||p&&p.nodeName.toLowerCase()===h?p||false:p===h}l&&k.filter(h,g,true)},">":function(g,h){var l=typeof h==="string";if(l&&!/\W/.test(h)){h=h.toLowerCase();for(var m=0,q=g.length;m<q;m++){var p=g[m];if(p){l=p.parentNode;g[m]=l.nodeName.toLowerCase()===h?l:false}}}else{m=0;for(q=g.length;m<q;m++)if(p=g[m])g[m]=
l?p.parentNode:p.parentNode===h;l&&k.filter(h,g,true)}},"":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("parentNode",h,m,g,p,l)},"~":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("previousSibling",h,m,g,p,l)}},find:{ID:function(g,h,l){if(typeof h.getElementById!=="undefined"&&!l)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var l=[];
h=h.getElementsByName(g[1]);for(var m=0,q=h.length;m<q;m++)h[m].getAttribute("name")===g[1]&&l.push(h[m]);return l.length===0?null:l}},TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,l,m,q,p){g=" "+g[1].replace(/\\/g,"")+" ";if(p)return g;p=0;for(var v;(v=h[p])!=null;p++)if(v)if(q^(v.className&&(" "+v.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))l||m.push(v);else if(l)h[p]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},
CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,l,m,q,p){h=g[1].replace(/\\/g,"");if(!p&&n.attrMap[h])g[1]=n.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,l,m,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,h);else{g=k.filter(g[3],h,l,true^q);l||m.push.apply(m,
g);return false}else if(n.match.POS.test(g[0])||n.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,l){return!!k(l[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},
text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},
setFilters:{first:function(g,h){return h===0},last:function(g,h,l,m){return h===m.length-1},even:function(g,h){return h%2===0},odd:function(g,h){return h%2===1},lt:function(g,h,l){return h<l[3]-0},gt:function(g,h,l){return h>l[3]-0},nth:function(g,h,l){return l[3]-0===h},eq:function(g,h,l){return l[3]-0===h}},filter:{PSEUDO:function(g,h,l,m){var q=h[1],p=n.filters[q];if(p)return p(g,l,h,m);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h=
h[3];l=0;for(m=h.length;l<m;l++)if(h[l]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+q)},CHILD:function(g,h){var l=h[1],m=g;switch(l){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(l==="first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":l=h[2];var q=h[3];if(l===1&&q===0)return true;h=h[0];var p=g.parentNode;if(p&&(p.sizcache!==h||!g.nodeIndex)){var v=0;for(m=p.firstChild;m;m=
m.nextSibling)if(m.nodeType===1)m.nodeIndex=++v;p.sizcache=h}g=g.nodeIndex-q;return l===0?g===0:g%l===0&&g/l>=0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var l=h[1];g=n.attrHandle[l]?n.attrHandle[l](g):g[l]!=null?g[l]:g.getAttribute(l);l=g+"";var m=h[2];h=h[4];return g==null?m==="!=":m===
"="?l===h:m==="*="?l.indexOf(h)>=0:m==="~="?(" "+l+" ").indexOf(h)>=0:!h?l&&g!==false:m==="!="?l!==h:m==="^="?l.indexOf(h)===0:m==="$="?l.substr(l.length-h.length)===h:m==="|="?l===h||l.substr(0,h.length+1)===h+"-":false},POS:function(g,h,l,m){var q=n.setFilters[h[2]];if(q)return q(g,l,h,m)}}},r=n.match.POS;for(var u in n.match){n.match[u]=new RegExp(n.match[u].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[u]=new RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[u].source.replace(/\\(\d+)/g,function(g,
h){return"\\"+(h-0+1)}))}var z=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};try{Array.prototype.slice.call(s.documentElement.childNodes,0)}catch(C){z=function(g,h){h=h||[];if(j.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var l=0,m=g.length;l<m;l++)h.push(g[l]);else for(l=0;g[l];l++)h.push(g[l]);return h}}var B;if(s.documentElement.compareDocumentPosition)B=function(g,h){if(!g.compareDocumentPosition||
!h.compareDocumentPosition){if(g==h)i=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===h?0:1;if(g===0)i=true;return g};else if("sourceIndex"in s.documentElement)B=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)i=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)i=true;return g};else if(s.createRange)B=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)i=true;return g.ownerDocument?-1:1}var l=g.ownerDocument.createRange(),m=
h.ownerDocument.createRange();l.setStart(g,0);l.setEnd(g,0);m.setStart(h,0);m.setEnd(h,0);g=l.compareBoundaryPoints(Range.START_TO_END,m);if(g===0)i=true;return g};(function(){var g=s.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var l=s.documentElement;l.insertBefore(g,l.firstChild);if(s.getElementById(h)){n.find.ID=function(m,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(m[1]))?q.id===m[1]||typeof q.getAttributeNode!=="undefined"&&
q.getAttributeNode("id").nodeValue===m[1]?[q]:w:[]};n.filter.ID=function(m,q){var p=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&p&&p.nodeValue===q}}l.removeChild(g);l=g=null})();(function(){var g=s.createElement("div");g.appendChild(s.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(h,l){l=l.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var m=0;l[m];m++)l[m].nodeType===1&&h.push(l[m]);l=h}return l};g.innerHTML="<a href='#'></a>";
if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(h){return h.getAttribute("href",2)};g=null})();s.querySelectorAll&&function(){var g=k,h=s.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){k=function(m,q,p,v){q=q||s;if(!v&&q.nodeType===9&&!x(q))try{return z(q.querySelectorAll(m),p)}catch(t){}return g(m,q,p,v)};for(var l in g)k[l]=g[l];h=null}}();
(function(){var g=s.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){n.order.splice(1,0,"CLASS");n.find.CLASS=function(h,l,m){if(typeof l.getElementsByClassName!=="undefined"&&!m)return l.getElementsByClassName(h[1])};g=null}}})();var E=s.compareDocumentPosition?function(g,h){return!!(g.compareDocumentPosition(h)&16)}:
function(g,h){return g!==h&&(g.contains?g.contains(h):true)},x=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},ga=function(g,h){var l=[],m="",q;for(h=h.nodeType?[h]:h;q=n.match.PSEUDO.exec(g);){m+=q[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;q=0;for(var p=h.length;q<p;q++)k(g,h[q],l);return k.filter(m,l)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=a;c.isXMLDoc=x;c.contains=E})();var eb=/Until$/,fb=/^(?:parents|prevUntil|prevAll)/,
gb=/,/;R=Array.prototype.slice;var Ia=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,j){return!!b.call(e,j,e)===d});else if(b.nodeType)return c.grep(a,function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Ua.test(b))return c.filter(b,f,!d);else b=c.filter(b,f)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f++){d=b.length;
c.find(a,this[f],b);if(f>0)for(var j=d;j<b.length;j++)for(var i=0;i<d;i++)if(b[i]===b[j]){b.splice(j--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Ia(this,a,false),"not",a)},filter:function(a){return this.pushStack(Ia(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,j=
{},i;if(f&&a.length){e=0;for(var o=a.length;e<o;e++){i=a[e];j[i]||(j[i]=c.expr.match.POS.test(i)?c(i,b||this.context):i)}for(;f&&f.ownerDocument&&f!==b;){for(i in j){e=j[i];if(e.jquery?e.index(f)>-1:c(f).is(e)){d.push({selector:i,elem:f});delete j[i]}}f=f.parentNode}}return d}var k=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(n,r){for(;r&&r.ownerDocument&&r!==b;){if(k?k.index(r)>-1:c(r).is(a))return r;r=r.parentNode}return null})},index:function(a){if(!a||typeof a===
"string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),a);return this.pushStack(qa(a[0])||qa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",
d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?
a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);eb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||gb.test(f))&&fb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===w||a.nodeType!==1||!c(a).is(d));){a.nodeType===
1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var Ja=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ka=/(<([\w:]+)[^>]*?)\/>/g,hb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,La=/<([\w:]+)/,ib=/<tbody/i,jb=/<|&#?\w+;/,ta=/<script|<object|<embed|<option|<style/i,ua=/checked\s*(?:[^=]|=\s*.checked.)/i,Ma=function(a,b,d){return hb.test(d)?
a:b+"></"+d+">"},F={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d=
c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this},
wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})},
prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,
this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,f;(f=this[d])!=null;d++)if(!a||c.filter(a,[f]).length){if(!b&&f.nodeType===1){c.cleanData(f.getElementsByTagName("*"));c.cleanData([f])}f.parentNode&&f.parentNode.removeChild(f)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild);
return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Ja,"").replace(/=([^="'>\s]+\/)>/g,'="$1">').replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){ra(this,b);ra(this.find("*"),b.find("*"))}return b},html:function(a){if(a===w)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Ja,
""):null;else if(typeof a==="string"&&!ta.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(La.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Ka,Ma);try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(f){this.empty().append(a)}}else c.isFunction(a)?this.each(function(e){var j=c(this),i=j.html();j.empty().append(function(){return a.call(this,e,i)})}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&
this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=c(this),f=d.html();d.replaceWith(a.call(this,b,f))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){function f(u){return c.nodeName(u,"table")?u.getElementsByTagName("tbody")[0]||
u.appendChild(u.ownerDocument.createElement("tbody")):u}var e,j,i=a[0],o=[],k;if(!c.support.checkClone&&arguments.length===3&&typeof i==="string"&&ua.test(i))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(i))return this.each(function(u){var z=c(this);a[0]=i.call(this,u,b?z.html():w);z.domManip(a,b,d)});if(this[0]){e=i&&i.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:sa(a,this,o);k=e.fragment;if(j=k.childNodes.length===
1?(k=k.firstChild):k.firstChild){b=b&&c.nodeName(j,"tr");for(var n=0,r=this.length;n<r;n++)d.call(b?f(this[n],j):this[n],n>0||e.cacheable||this.length>1?k.cloneNode(true):k)}o.length&&c.each(o,Qa)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);var e=this.length===1&&this[0].parentNode;if(e&&e.nodeType===11&&e.childNodes.length===1&&d.length===1){d[b](this[0]);
return this}else{e=0;for(var j=d.length;e<j;e++){var i=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),i);f=f.concat(i)}return this.pushStack(f,a,d.selector)}}});c.extend({clean:function(a,b,d,f){b=b||s;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||s;for(var e=[],j=0,i;(i=a[j])!=null;j++){if(typeof i==="number")i+="";if(i){if(typeof i==="string"&&!jb.test(i))i=b.createTextNode(i);else if(typeof i==="string"){i=i.replace(Ka,Ma);var o=(La.exec(i)||["",
""])[1].toLowerCase(),k=F[o]||F._default,n=k[0],r=b.createElement("div");for(r.innerHTML=k[1]+i+k[2];n--;)r=r.lastChild;if(!c.support.tbody){n=ib.test(i);o=o==="table"&&!n?r.firstChild&&r.firstChild.childNodes:k[1]==="<table>"&&!n?r.childNodes:[];for(k=o.length-1;k>=0;--k)c.nodeName(o[k],"tbody")&&!o[k].childNodes.length&&o[k].parentNode.removeChild(o[k])}!c.support.leadingWhitespace&&V.test(i)&&r.insertBefore(b.createTextNode(V.exec(i)[0]),r.firstChild);i=r.childNodes}if(i.nodeType)e.push(i);else e=
c.merge(e,i)}}if(d)for(j=0;e[j];j++)if(f&&c.nodeName(e[j],"script")&&(!e[j].type||e[j].type.toLowerCase()==="text/javascript"))f.push(e[j].parentNode?e[j].parentNode.removeChild(e[j]):e[j]);else{e[j].nodeType===1&&e.splice.apply(e,[j+1,0].concat(c.makeArray(e[j].getElementsByTagName("script"))));d.appendChild(e[j])}return e},cleanData:function(a){for(var b,d,f=c.cache,e=c.event.special,j=c.support.deleteExpando,i=0,o;(o=a[i])!=null;i++)if(d=o[c.expando]){b=f[d];if(b.events)for(var k in b.events)e[k]?
c.event.remove(o,k):Ca(o,k,b.handle);if(j)delete o[c.expando];else o.removeAttribute&&o.removeAttribute(c.expando);delete f[d]}}});var kb=/z-?index|font-?weight|opacity|zoom|line-?height/i,Na=/alpha\([^)]*\)/,Oa=/opacity=([^)]*)/,ha=/float/i,ia=/-([a-z])/ig,lb=/([A-Z])/g,mb=/^-?\d+(?:px)?$/i,nb=/^-?\d/,ob={position:"absolute",visibility:"hidden",display:"block"},pb=["Left","Right"],qb=["Top","Bottom"],rb=s.defaultView&&s.defaultView.getComputedStyle,Pa=c.support.cssFloat?"cssFloat":"styleFloat",ja=
function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===w)return c.curCSS(d,f);if(typeof e==="number"&&!kb.test(f))e+="px";c.style(d,f,e)})};c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return w;if((b==="width"||b==="height")&&parseFloat(d)<0)d=w;var f=a.style||a,e=d!==w;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter=
Na.test(a)?a.replace(Na,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Oa.exec(f.filter)[1])/100+"":""}if(ha.test(b))b=Pa;b=b.replace(ia,ja);if(e)f[b]=d;return f[b]},css:function(a,b,d,f){if(b==="width"||b==="height"){var e,j=b==="width"?pb:qb;function i(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(j,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a,
"border"+this+"Width",true))||0})}a.offsetWidth!==0?i():c.swap(a,ob,i);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&a.currentStyle){f=Oa.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ha.test(b))b=Pa;if(!d&&e&&e[b])f=e[b];else if(rb){if(ha.test(b))b="float";b=b.replace(lb,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f=
a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ia,ja);f=a.currentStyle[b]||a.currentStyle[d];if(!mb.test(f)&&nb.test(f)){b=e.left;var j=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=j}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=
a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var sb=J(),tb=/<script(.|\s)*?\/script>/gi,ub=/select|textarea/i,vb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ka=/\?/,wb=/(\?|&)_=.*?(&|$)/,xb=/^(\w+:)?\/\/([^\/?#]+)/,yb=/%20/g,zb=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!==
"string")return zb.call(this,a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);f="POST"}var j=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(i,o){if(o==="success"||o==="notmodified")j.html(e?c("<div />").append(i.responseText.replace(tb,"")).find(e):i.responseText);d&&j.each(d,[i.responseText,o,i])}});return this},
serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ub.test(this.nodeName)||vb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),
function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,
global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:A.XMLHttpRequest&&(A.location.protocol!=="file:"||!A.ActiveXObject)?function(){return new A.XMLHttpRequest}:function(){try{return new A.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&&
e.success.call(k,o,i,x);e.global&&f("ajaxSuccess",[x,e])}function d(){e.complete&&e.complete.call(k,x,i);e.global&&f("ajaxComplete",[x,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),j,i,o,k=a&&a.context||e,n=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(n==="GET")N.test(e.url)||(e.url+=(ka.test(e.url)?
"&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)||N.test(e.url))){j=e.jsonpCallback||"jsonp"+sb++;if(e.data)e.data=(e.data+"").replace(N,"="+j+"$1");e.url=e.url.replace(N,"="+j+"$1");e.dataType="script";A[j]=A[j]||function(q){o=q;b();d();A[j]=w;try{delete A[j]}catch(p){}z&&z.removeChild(C)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache===
false&&n==="GET"){var r=J(),u=e.url.replace(wb,"$1_="+r+"$2");e.url=u+(u===e.url?(ka.test(e.url)?"&":"?")+"_="+r:"")}if(e.data&&n==="GET")e.url+=(ka.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&c.event.trigger("ajaxStart");r=(r=xb.exec(e.url))&&(r[1]&&r[1]!==location.protocol||r[2]!==location.host);if(e.dataType==="script"&&n==="GET"&&r){var z=s.getElementsByTagName("head")[0]||s.documentElement,C=s.createElement("script");C.src=e.url;if(e.scriptCharset)C.charset=e.scriptCharset;if(!j){var B=
false;C.onload=C.onreadystatechange=function(){if(!B&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){B=true;b();d();C.onload=C.onreadystatechange=null;z&&C.parentNode&&z.removeChild(C)}}}z.insertBefore(C,z.firstChild);return w}var E=false,x=e.xhr();if(x){e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);try{if(e.data||a&&a.contentType)x.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&x.setRequestHeader("If-Modified-Since",
c.lastModified[e.url]);c.etag[e.url]&&x.setRequestHeader("If-None-Match",c.etag[e.url])}r||x.setRequestHeader("X-Requested-With","XMLHttpRequest");x.setRequestHeader("Accept",e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(ga){}if(e.beforeSend&&e.beforeSend.call(k,x,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");x.abort();return false}e.global&&f("ajaxSend",[x,e]);var g=x.onreadystatechange=function(q){if(!x||x.readyState===0||q==="abort"){E||
d();E=true;if(x)x.onreadystatechange=c.noop}else if(!E&&x&&(x.readyState===4||q==="timeout")){E=true;x.onreadystatechange=c.noop;i=q==="timeout"?"timeout":!c.httpSuccess(x)?"error":e.ifModified&&c.httpNotModified(x,e.url)?"notmodified":"success";var p;if(i==="success")try{o=c.httpData(x,e.dataType,e)}catch(v){i="parsererror";p=v}if(i==="success"||i==="notmodified")j||b();else c.handleError(e,x,i,p);d();q==="timeout"&&x.abort();if(e.async)x=null}};try{var h=x.abort;x.abort=function(){x&&h.call(x);
g("abort")}}catch(l){}e.async&&e.timeout>0&&setTimeout(function(){x&&!E&&g("timeout")},e.timeout);try{x.send(n==="POST"||n==="PUT"||n==="DELETE"?e.data:null)}catch(m){c.handleError(e,x,null,m);d()}e.async||g();return x}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===
1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b===
"json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(i,o){if(c.isArray(o))c.each(o,function(k,n){b||/\[\]$/.test(i)?f(i,n):d(i+"["+(typeof n==="object"||c.isArray(n)?k:"")+"]",n)});else!b&&o!=null&&typeof o==="object"?c.each(o,function(k,n){d(i+"["+k+"]",n)}):f(i,o)}function f(i,o){o=c.isFunction(o)?o():o;e[e.length]=encodeURIComponent(i)+"="+encodeURIComponent(o)}var e=[];if(b===w)b=c.ajaxSettings.traditional;
if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var j in a)d(j,a[j]);return e.join("&").replace(yb,"+")}});var la={},Ab=/toggle|show|hide/,Bb=/^([+-]=)?([\d+-.]+)(.*)$/,W,va=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");
this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(la[d])f=la[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();la[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a||a===0)return this.animate(K("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!=="none"&&c.data(this[a],
"olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(K("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d)},
animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var j=c.extend({},e),i,o=this.nodeType===1&&c(this).is(":hidden"),k=this;for(i in a){var n=i.replace(ia,ja);if(i!==n){a[n]=a[i];delete a[i];i=n}if(a[i]==="hide"&&o||a[i]==="show"&&!o)return j.complete.call(this);if((i==="height"||i==="width")&&this.style){j.display=c.css(this,"display");j.overflow=this.style.overflow}if(c.isArray(a[i])){(j.specialEasing=
j.specialEasing||{})[i]=a[i][1];a[i]=a[i][0]}}if(j.overflow!=null)this.style.overflow="hidden";j.curAnim=c.extend({},a);c.each(a,function(r,u){var z=new c.fx(k,j,r);if(Ab.test(u))z[u==="toggle"?o?"show":"hide":u](a);else{var C=Bb.exec(u),B=z.cur(true)||0;if(C){u=parseFloat(C[2]);var E=C[3]||"px";if(E!=="px"){k.style[r]=(u||1)+E;B=(u||1)/z.cur(true)*B;k.style[r]=B+E}if(C[1])u=(C[1]==="-="?-1:1)*u+B;z.custom(B,u,E)}else z.custom(B,u,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);
this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration===
"number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a,b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||
c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(j){return e.step(j)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;
this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=J(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=
this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem,
e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||
c.fx.stop()},stop:function(){clearInterval(W);W=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length};c.fn.offset="getBoundingClientRect"in s.documentElement?
function(a){var b=this[0];if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(),f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:function(a){var b=
this[0];if(a)return this.each(function(r){c.offset.setOffset(this,a,r)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f=b,e=b.ownerDocument,j,i=e.documentElement,o=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var k=b.offsetTop,n=b.offsetLeft;(b=b.parentNode)&&b!==o&&b!==i;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;j=e?e.getComputedStyle(b,null):b.currentStyle;
k-=b.scrollTop;n-=b.scrollLeft;if(b===d){k+=b.offsetTop;n+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&j.overflow!=="visible"){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=j}if(f.position==="relative"||f.position==="static"){k+=o.offsetTop;n+=o.offsetLeft}if(c.offset.supportsFixedPosition&&
f.position==="fixed"){k+=Math.max(i.scrollTop,o.scrollTop);n+=Math.max(i.scrollLeft,o.scrollLeft)}return{top:k,left:n}};c.offset={initialize:function(){var a=s.body,b=s.createElement("div"),d,f,e,j=parseFloat(c.curCSS(a,"marginTop",true))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";
a.insertBefore(b,a.firstChild);d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==j;a.removeChild(b);
c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),j=parseInt(c.curCSS(a,"top",true),10)||0,i=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a,
d,e);d={top:b.top-e.top+j,left:b.left-e.left+i};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top-
f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||s.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],j;if(!e)return null;if(f!==w)return this.each(function(){if(j=wa(this))j.scrollTo(!a?f:c(j).scrollLeft(),a?f:c(j).scrollTop());else this[d]=f});else return(j=wa(e))?"pageXOffset"in j?j[a?"pageYOffset":
"pageXOffset"]:c.support.boxModel&&j.document.documentElement[d]||j.document.body[d]:e[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(j){var i=c(this);i[d](f.call(this,j,i[d]()))});return"scrollTo"in
e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window);

/* =========================================================

// jquery.innerfade.js

// Datum: 2008-02-14
// Firma: Medienfreunde Hofmann & Baldes GbR
// Author: Torsten Baldes
// Mail: t.baldes@medienfreunde.com
// Web: http://medienfreunde.com

// based on the work of Matt Oakes http://portfolio.gizone.co.uk/applications/slideshow/
// and Ralf S. Engelschall http://trainofthoughts.org/

 *
 *  <ul id="news"> 
 *      <li>content 1</li>
 *      <li>content 2</li>
 *      <li>content 3</li>
 *  </ul>
 *  
 *  $('#news').innerfade({ 
 *	  animationtype: Type of animation 'fade' or 'slide' (Default: 'fade'), 
 *	  speed: Fading-/Sliding-Speed in milliseconds or keywords (slow, normal or fast) (Default: 'normal'), 
 *	  timeout: Time between the fades in milliseconds (Default: '2000'), 
 *	  type: Type of slideshow: 'sequence', 'random' or 'random_start' (Default: 'sequence'), 
 * 		containerheight: Height of the containing element in any css-height-value (Default: 'auto'),
 *	  runningclass: CSS-Class which the container get’s applied (Default: 'innerfade'),
 *	  children: optional children selector (Default: null)
 *  }); 
 *

// ========================================================= */


(function($) {

    $.fn.innerfade = function(options) {
        return this.each(function() {   
            $.innerfade(this, options);
        });
    };

    $.innerfade = function(container, options) {
        var settings = {
        		'animationtype':    'fade',
            'speed':            'normal',
            'type':             'sequence',
            'timeout':          2000,
            'containerheight':  'auto',
            'runningclass':     'innerfade',
            'children':         null
        };
        if (options)
            $.extend(settings, options);
        if (settings.children === null)
            var elements = $(container).children();
        else
            var elements = $(container).children(settings.children);
        if (elements.length > 1) {
            $(container).css('position', 'relative').css('height', settings.containerheight).addClass(settings.runningclass);
            for (var i = 0; i < elements.length; i++) {
                $(elements[i]).css('z-index', String(elements.length-i)).css('position', 'absolute').hide();
            };
            if (settings.type == "sequence") {
                setTimeout(function() {
                    $.innerfade.next(elements, settings, 1, 0);
                }, settings.timeout);
                $(elements[0]).show();
            } else if (settings.type == "random") {
            		var last = Math.floor ( Math.random () * ( elements.length ) );
                setTimeout(function() {
                    do { 
												current = Math.floor ( Math.random ( ) * ( elements.length ) );
										} while (last == current );             
										$.innerfade.next(elements, settings, current, last);
                }, settings.timeout);
                $(elements[last]).show();
						} else if ( settings.type == 'random_start' ) {
								settings.type = 'sequence';
								var current = Math.floor ( Math.random () * ( elements.length ) );
								setTimeout(function(){
									$.innerfade.next(elements, settings, (current + 1) %  elements.length, current);
								}, settings.timeout);
								$(elements[current]).show();
						}	else {
							alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');
						}
				}
    };

    $.innerfade.next = function(elements, settings, current, last) {
        if (settings.animationtype == 'slide') {
            $(elements[last]).slideUp(settings.speed);
            $(elements[current]).slideDown(settings.speed);
        } else if (settings.animationtype == 'fade') {
            $(elements[last]).fadeOut(settings.speed);
            $(elements[current]).fadeIn(settings.speed, function() {
							removeFilter($(this)[0]);
						});
        } else
            alert('Innerfade-animationtype must either be \'slide\' or \'fade\'');
        if (settings.type == "sequence") {
            if ((current + 1) < elements.length) {
                current = current + 1;
                last = current - 1;
            } else {
                current = 0;
                last = elements.length - 1;
            }
        } else if (settings.type == "random") {
            last = current;
            while (current == last)
                current = Math.floor(Math.random() * elements.length);
        } else
            alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');
        setTimeout((function() {
            $.innerfade.next(elements, settings, current, last);
        }), settings.timeout);
    };

})(jQuery);

// **** remove Opacity-Filter in ie ****
function removeFilter(element) {
	if(element.style.removeAttribute){
		element.style.removeAttribute('filter');
	}
}

/*!
 * jQuery Form Plugin
 * version: 2.82 (15-JUN-2011)
 * @requires jQuery v1.3.2 or later
 *
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
;(function($) {

/*
	Usage Note:
	-----------
	Do not use both ajaxSubmit and ajaxForm on the same form.  These
	functions are intended to be exclusive.  Use ajaxSubmit if you want
	to bind your own submit handler to the form.  For example,

	$(document).ready(function() {
		$('#myForm').bind('submit', function(e) {
			e.preventDefault(); // <-- important
			$(this).ajaxSubmit({
				target: '#output'
			});
		});
	});

	Use ajaxForm when you want the plugin to manage all the event binding
	for you.  For example,

	$(document).ready(function() {
		$('#myForm').ajaxForm({
			target: '#output'
		});
	});

	When using ajaxForm, the ajaxSubmit function will be invoked for you
	at the appropriate time.
*/

/**
 * ajaxSubmit() provides a mechanism for immediately submitting
 * an HTML form using AJAX.
 */
$.fn.ajaxSubmit = function(options) {
	// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
	if (!this.length) {
		log('ajaxSubmit: skipping submit process - no element selected');
		return this;
	}
	
	var method, action, url, $form = this;

	if (typeof options == 'function') {
		options = { success: options };
	}

	method = this.attr('method');
	action = this.attr('action');
	url = (typeof action === 'string') ? $.trim(action) : '';
	url = url || window.location.href || '';
	if (url) {
		// clean url (don't include hash vaue)
		url = (url.match(/^([^#]+)/)||[])[1];
	}

	options = $.extend(true, {
		url:  url,
		success: $.ajaxSettings.success,
		type: method || 'GET',
		iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
	}, options);

	// hook for manipulating the form data before it is extracted;
	// convenient for use with rich editors like tinyMCE or FCKEditor
	var veto = {};
	this.trigger('form-pre-serialize', [this, options, veto]);
	if (veto.veto) {
		log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
		return this;
	}

	// provide opportunity to alter form data before it is serialized
	if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
		log('ajaxSubmit: submit aborted via beforeSerialize callback');
		return this;
	}

	var n,v,a = this.formToArray(options.semantic);
	if (options.data) {
		options.extraData = options.data;
		for (n in options.data) {
			if(options.data[n] instanceof Array) {
				for (var k in options.data[n]) {
					a.push( { name: n, value: options.data[n][k] } );
				}
			}
			else {
				v = options.data[n];
				v = $.isFunction(v) ? v() : v; // if value is fn, invoke it
				a.push( { name: n, value: v } );
			}
		}
	}

	// give pre-submit callback an opportunity to abort the submit
	if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
		log('ajaxSubmit: submit aborted via beforeSubmit callback');
		return this;
	}

	// fire vetoable 'validate' event
	this.trigger('form-submit-validate', [a, this, options, veto]);
	if (veto.veto) {
		log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
		return this;
	}

	var q = $.param(a);

	if (options.type.toUpperCase() == 'GET') {
		options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
		options.data = null;  // data is null for 'get'
	}
	else {
		options.data = q; // data is the query string for 'post'
	}

	var callbacks = [];
	if (options.resetForm) {
		callbacks.push(function() { $form.resetForm(); });
	}
	if (options.clearForm) {
		callbacks.push(function() { $form.clearForm(); });
	}

	// perform a load on the target only if dataType is not provided
	if (!options.dataType && options.target) {
		var oldSuccess = options.success || function(){};
		callbacks.push(function(data) {
			var fn = options.replaceTarget ? 'replaceWith' : 'html';
			$(options.target)[fn](data).each(oldSuccess, arguments);
		});
	}
	else if (options.success) {
		callbacks.push(options.success);
	}

	options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
		var context = options.context || options;   // jQuery 1.4+ supports scope context 
		for (var i=0, max=callbacks.length; i < max; i++) {
			callbacks[i].apply(context, [data, status, xhr || $form, $form]);
		}
	};

	// are there files to upload?
	var fileInputs = $('input:file', this).length > 0;
	var mp = 'multipart/form-data';
	var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);

	// options.iframe allows user to force iframe mode
	// 06-NOV-09: now defaulting to iframe mode if file input is detected
   if (options.iframe !== false && (fileInputs || options.iframe || multipart)) {
	   // hack to fix Safari hang (thanks to Tim Molendijk for this)
	   // see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
	   if (options.closeKeepAlive) {
		   $.get(options.closeKeepAlive, function() { fileUpload(a); });
		}
	   else {
		   fileUpload(a);
		}
   }
   else {
		// IE7 massage (see issue 57)
		if ($.browser.msie && method == 'get') { 
			var ieMeth = $form[0].getAttribute('method');
			if (typeof ieMeth === 'string')
				options.type = ieMeth;
		}
		$.ajax(options);
   }

	// fire 'notify' event
	this.trigger('form-submit-notify', [this, options]);
	return this;


	// private function for handling file uploads (hat tip to YAHOO!)
	function fileUpload(a) {
		var form = $form[0], i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle;

        if (a) {
        	// ensure that every serialized input is still enabled
          	for (i=0; i < a.length; i++) {
            	$(form[a[i].name]).attr('disabled', false);
          	}
        }

		if ($(':input[name=submit],:input[id=submit]', form).length) {
			// if there is an input with a name or id of 'submit' then we won't be
			// able to invoke the submit fn on the form (at least not x-browser)
			alert('Error: Form elements must not have name or id of "submit".');
			return;
		}
		
		s = $.extend(true, {}, $.ajaxSettings, options);
		s.context = s.context || s;
		id = 'jqFormIO' + (new Date().getTime());
		if (s.iframeTarget) {
			$io = $(s.iframeTarget);
			n = $io.attr('name');
			if (n == null)
			 	$io.attr('name', id);
			else
				id = n;
		}
		else {
			$io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />');
			$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
		}
		io = $io[0];


		xhr = { // mock object
			aborted: 0,
			responseText: null,
			responseXML: null,
			status: 0,
			statusText: 'n/a',
			getAllResponseHeaders: function() {},
			getResponseHeader: function() {},
			setRequestHeader: function() {},
			abort: function(status) {
				var e = (status === 'timeout' ? 'timeout' : 'aborted');
				log('aborting upload... ' + e);
				this.aborted = 1;
				$io.attr('src', s.iframeSrc); // abort op in progress
				xhr.error = e;
				s.error && s.error.call(s.context, xhr, e, status);
				g && $.event.trigger("ajaxError", [xhr, s, e]);
				s.complete && s.complete.call(s.context, xhr, e);
			}
		};

		g = s.global;
		// trigger ajax global events so that activity/block indicators work like normal
		if (g && ! $.active++) {
			$.event.trigger("ajaxStart");
		}
		if (g) {
			$.event.trigger("ajaxSend", [xhr, s]);
		}

		if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
			if (s.global) {
				$.active--;
			}
			return;
		}
		if (xhr.aborted) {
			return;
		}

		// add submitting element to data if we know it
		sub = form.clk;
		if (sub) {
			n = sub.name;
			if (n && !sub.disabled) {
				s.extraData = s.extraData || {};
				s.extraData[n] = sub.value;
				if (sub.type == "image") {
					s.extraData[n+'.x'] = form.clk_x;
					s.extraData[n+'.y'] = form.clk_y;
				}
			}
		}
		
		var CLIENT_TIMEOUT_ABORT = 1;
		var SERVER_ABORT = 2;

		function getDoc(frame) {
			var doc = frame.contentWindow ? frame.contentWindow.document : frame.contentDocument ? frame.contentDocument : frame.document;
			return doc;
		}
		
		// take a breath so that pending repaints get some cpu time before the upload starts
		function doSubmit() {
			// make sure form attrs are set
			var t = $form.attr('target'), a = $form.attr('action');

			// update form attrs in IE friendly way
			form.setAttribute('target',id);
			if (!method) {
				form.setAttribute('method', 'POST');
			}
			if (a != s.url) {
				form.setAttribute('action', s.url);
			}

			// ie borks in some cases when setting encoding
			if (! s.skipEncodingOverride && (!method || /post/i.test(method))) {
				$form.attr({
					encoding: 'multipart/form-data',
					enctype:  'multipart/form-data'
				});
			}

			// support timout
			if (s.timeout) {
				timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout);
			}
			
			// look for server aborts
			function checkState() {
				try {
					var state = getDoc(io).readyState;
					log('state = ' + state);
					if (state.toLowerCase() == 'uninitialized')
						setTimeout(checkState,50);
				}
				catch(e) {
					log('Server abort: ' , e, ' (', e.name, ')');
					cb(SERVER_ABORT);
					timeoutHandle && clearTimeout(timeoutHandle);
					timeoutHandle = undefined;
				}
			}

			// add "extra" data to form if provided in options
			var extraInputs = [];
			try {
				if (s.extraData) {
					for (var n in s.extraData) {
						extraInputs.push(
							$('<input type="hidden" name="'+n+'" />').attr('value',s.extraData[n])
								.appendTo(form)[0]);
					}
				}

				if (!s.iframeTarget) {
					// add iframe to doc and submit the form
					$io.appendTo('body');
	                io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
				}
				setTimeout(checkState,15);
				form.submit();
			}
			finally {
				// reset attrs and remove "extra" input elements
				form.setAttribute('action',a);
				if(t) {
					form.setAttribute('target', t);
				} else {
					$form.removeAttr('target');
				}
				$(extraInputs).remove();
			}
		}

		if (s.forceSync) {
			doSubmit();
		}
		else {
			setTimeout(doSubmit, 10); // this lets dom updates render
		}

		var data, doc, domCheckCount = 50, callbackProcessed;

		function cb(e) {
			if (xhr.aborted || callbackProcessed) {
				return;
			}
			try {
				doc = getDoc(io);
			}
			catch(ex) {
				log('cannot access response document: ', ex);
				e = SERVER_ABORT;
			}
			if (e === CLIENT_TIMEOUT_ABORT && xhr) {
				xhr.abort('timeout');
				return;
			}
			else if (e == SERVER_ABORT && xhr) {
				xhr.abort('server abort');
				return;
			}

			if (!doc || doc.location.href == s.iframeSrc) {
				// response not received yet
				if (!timedOut)
					return;
			}
            io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);

			var status = 'success', errMsg;
			try {
				if (timedOut) {
					throw 'timeout';
				}

				var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
				log('isXml='+isXml);
				if (!isXml && window.opera && (doc.body == null || doc.body.innerHTML == '')) {
					if (--domCheckCount) {
						// in some browsers (Opera) the iframe DOM is not always traversable when
						// the onload callback fires, so we loop a bit to accommodate
						log('requeing onLoad callback, DOM not available');
						setTimeout(cb, 250);
						return;
					}
					// let this fall through because server response could be an empty document
					//log('Could not access iframe DOM after mutiple tries.');
					//throw 'DOMException: not available';
				}

				//log('response detected');
                var docRoot = doc.body ? doc.body : doc.documentElement;
                xhr.responseText = docRoot ? docRoot.innerHTML : null;
				xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
				if (isXml)
					s.dataType = 'xml';
				xhr.getResponseHeader = function(header){
					var headers = {'content-type': s.dataType};
					return headers[header];
				};
                // support for XHR 'status' & 'statusText' emulation :
                if (docRoot) {
                    xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status;
                    xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText;
                }

				var dt = s.dataType || '';
				var scr = /(json|script|text)/.test(dt.toLowerCase());
				if (scr || s.textarea) {
					// see if user embedded response in textarea
					var ta = doc.getElementsByTagName('textarea')[0];
					if (ta) {
						xhr.responseText = ta.value;
                        // support for XHR 'status' & 'statusText' emulation :
                        xhr.status = Number( ta.getAttribute('status') ) || xhr.status;
                        xhr.statusText = ta.getAttribute('statusText') || xhr.statusText;
					}
					else if (scr) {
						// account for browsers injecting pre around json response
						var pre = doc.getElementsByTagName('pre')[0];
						var b = doc.getElementsByTagName('body')[0];
						if (pre) {
							xhr.responseText = pre.textContent ? pre.textContent : pre.innerHTML;
						}
						else if (b) {
							xhr.responseText = b.innerHTML;
						}
					}
				}
				else if (s.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
					xhr.responseXML = toXml(xhr.responseText);
				}

                try {
                    data = httpData(xhr, s.dataType, s);
                }
                catch (e) {
                    status = 'parsererror';
                    xhr.error = errMsg = (e || status);
                }
			}
			catch (e) {
				log('error caught: ',e);
				status = 'error';
                xhr.error = errMsg = (e || status);
			}

			if (xhr.aborted) {
				log('upload aborted');
				status = null;
			}

            if (xhr.status) { // we've set xhr.status
                status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error';
            }

			// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
			if (status === 'success') {
				s.success && s.success.call(s.context, data, 'success', xhr);
				g && $.event.trigger("ajaxSuccess", [xhr, s]);
			}
            else if (status) {
				if (errMsg == undefined)
					errMsg = xhr.statusText;
				s.error && s.error.call(s.context, xhr, status, errMsg);
				g && $.event.trigger("ajaxError", [xhr, s, errMsg]);
            }

			g && $.event.trigger("ajaxComplete", [xhr, s]);

			if (g && ! --$.active) {
				$.event.trigger("ajaxStop");
			}

			s.complete && s.complete.call(s.context, xhr, status);

			callbackProcessed = true;
			if (s.timeout)
				clearTimeout(timeoutHandle);

			// clean up
			setTimeout(function() {
				if (!s.iframeTarget)
					$io.remove();
				xhr.responseXML = null;
			}, 100);
		}

		var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+)
			if (window.ActiveXObject) {
				doc = new ActiveXObject('Microsoft.XMLDOM');
				doc.async = 'false';
				doc.loadXML(s);
			}
			else {
				doc = (new DOMParser()).parseFromString(s, 'text/xml');
			}
			return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null;
		};
		var parseJSON = $.parseJSON || function(s) {
			return window['eval']('(' + s + ')');
		};

		var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4

			var ct = xhr.getResponseHeader('content-type') || '',
				xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
				data = xml ? xhr.responseXML : xhr.responseText;

			if (xml && data.documentElement.nodeName === 'parsererror') {
				$.error && $.error('parsererror');
			}
			if (s && s.dataFilter) {
				data = s.dataFilter(data, type);
			}
			if (typeof data === 'string') {
				if (type === 'json' || !type && ct.indexOf('json') >= 0) {
					data = parseJSON(data);
				} else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
					$.globalEval(data);
				}
			}
			return data;
		};
	}
};

/**
 * ajaxForm() provides a mechanism for fully automating form submission.
 *
 * The advantages of using this method instead of ajaxSubmit() are:
 *
 * 1: This method will include coordinates for <input type="image" /> elements (if the element
 *	is used to submit the form).
 * 2. This method will include the submit element's name/value data (for the element that was
 *	used to submit the form).
 * 3. This method binds the submit() method to the form for you.
 *
 * The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
 * passes the options argument along after properly binding events for submit elements and
 * the form itself.
 */
$.fn.ajaxForm = function(options) {
	// in jQuery 1.3+ we can fix mistakes with the ready state
	if (this.length === 0) {
		var o = { s: this.selector, c: this.context };
		if (!$.isReady && o.s) {
			log('DOM not ready, queuing ajaxForm');
			$(function() {
				$(o.s,o.c).ajaxForm(options);
			});
			return this;
		}
		// is your DOM ready?  http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
		log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
		return this;
	}

	return this.ajaxFormUnbind().bind('submit.form-plugin', function(e) {
		if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
			e.preventDefault();
			$(this).ajaxSubmit(options);
		}
	}).bind('click.form-plugin', function(e) {
		var target = e.target;
		var $el = $(target);
		if (!($el.is(":submit,input:image"))) {
			// is this a child element of the submit el?  (ex: a span within a button)
			var t = $el.closest(':submit');
			if (t.length == 0) {
				return;
			}
			target = t[0];
		}
		var form = this;
		form.clk = target;
		if (target.type == 'image') {
			if (e.offsetX != undefined) {
				form.clk_x = e.offsetX;
				form.clk_y = e.offsetY;
			} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
				var offset = $el.offset();
				form.clk_x = e.pageX - offset.left;
				form.clk_y = e.pageY - offset.top;
			} else {
				form.clk_x = e.pageX - target.offsetLeft;
				form.clk_y = e.pageY - target.offsetTop;
			}
		}
		// clear form vars
		setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
	});
};

// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
	return this.unbind('submit.form-plugin click.form-plugin');
};

/**
 * formToArray() gathers form element data into an array of objects that can
 * be passed to any of the following ajax functions: $.get, $.post, or load.
 * Each object in the array has both a 'name' and 'value' property.  An example of
 * an array for a simple login form might be:
 *
 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
 *
 * It is this array that is passed to pre-submit callback functions provided to the
 * ajaxSubmit() and ajaxForm() methods.
 */
$.fn.formToArray = function(semantic) {
	var a = [];
	if (this.length === 0) {
		return a;
	}

	var form = this[0];
	var els = semantic ? form.getElementsByTagName('*') : form.elements;
	if (!els) {
		return a;
	}

	var i,j,n,v,el,max,jmax;
	for(i=0, max=els.length; i < max; i++) {
		el = els[i];
		n = el.name;
		if (!n) {
			continue;
		}

		if (semantic && form.clk && el.type == "image") {
			// handle image inputs on the fly when semantic == true
			if(!el.disabled && form.clk == el) {
				a.push({name: n, value: $(el).val()});
				a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
			}
			continue;
		}

		v = $.fieldValue(el, true);
		if (v && v.constructor == Array) {
			for(j=0, jmax=v.length; j < jmax; j++) {
				a.push({name: n, value: v[j]});
			}
		}
		else if (v !== null && typeof v != 'undefined') {
			a.push({name: n, value: v});
		}
	}

	if (!semantic && form.clk) {
		// input type=='image' are not found in elements array! handle it here
		var $input = $(form.clk), input = $input[0];
		n = input.name;
		if (n && !input.disabled && input.type == 'image') {
			a.push({name: n, value: $input.val()});
			a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
		}
	}
	return a;
};

/**
 * Serializes form data into a 'submittable' string. This method will return a string
 * in the format: name1=value1&amp;name2=value2
 */
$.fn.formSerialize = function(semantic) {
	//hand off to jQuery.param for proper encoding
	return $.param(this.formToArray(semantic));
};

/**
 * Serializes all field elements in the jQuery object into a query string.
 * This method will return a string in the format: name1=value1&amp;name2=value2
 */
$.fn.fieldSerialize = function(successful) {
	var a = [];
	this.each(function() {
		var n = this.name;
		if (!n) {
			return;
		}
		var v = $.fieldValue(this, successful);
		if (v && v.constructor == Array) {
			for (var i=0,max=v.length; i < max; i++) {
				a.push({name: n, value: v[i]});
			}
		}
		else if (v !== null && typeof v != 'undefined') {
			a.push({name: this.name, value: v});
		}
	});
	//hand off to jQuery.param for proper encoding
	return $.param(a);
};

/**
 * Returns the value(s) of the element in the matched set.  For example, consider the following form:
 *
 *  <form><fieldset>
 *	  <input name="A" type="text" />
 *	  <input name="A" type="text" />
 *	  <input name="B" type="checkbox" value="B1" />
 *	  <input name="B" type="checkbox" value="B2"/>
 *	  <input name="C" type="radio" value="C1" />
 *	  <input name="C" type="radio" value="C2" />
 *  </fieldset></form>
 *
 *  var v = $(':text').fieldValue();
 *  // if no values are entered into the text inputs
 *  v == ['','']
 *  // if values entered into the text inputs are 'foo' and 'bar'
 *  v == ['foo','bar']
 *
 *  var v = $(':checkbox').fieldValue();
 *  // if neither checkbox is checked
 *  v === undefined
 *  // if both checkboxes are checked
 *  v == ['B1', 'B2']
 *
 *  var v = $(':radio').fieldValue();
 *  // if neither radio is checked
 *  v === undefined
 *  // if first radio is checked
 *  v == ['C1']
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If this value is false the value(s)
 * for each element is returned.
 *
 * Note: This method *always* returns an array.  If no valid value can be determined the
 *	   array will be empty, otherwise it will contain one or more values.
 */
$.fn.fieldValue = function(successful) {
	for (var val=[], i=0, max=this.length; i < max; i++) {
		var el = this[i];
		var v = $.fieldValue(el, successful);
		if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
			continue;
		}
		v.constructor == Array ? $.merge(val, v) : val.push(v);
	}
	return val;
};

/**
 * Returns the value of the field element.
 */
$.fieldValue = function(el, successful) {
	var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
	if (successful === undefined) {
		successful = true;
	}

	if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
		(t == 'checkbox' || t == 'radio') && !el.checked ||
		(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
		tag == 'select' && el.selectedIndex == -1)) {
			return null;
	}

	if (tag == 'select') {
		var index = el.selectedIndex;
		if (index < 0) {
			return null;
		}
		var a = [], ops = el.options;
		var one = (t == 'select-one');
		var max = (one ? index+1 : ops.length);
		for(var i=(one ? index : 0); i < max; i++) {
			var op = ops[i];
			if (op.selected) {
				var v = op.value;
				if (!v) { // extra pain for IE...
					v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
				}
				if (one) {
					return v;
				}
				a.push(v);
			}
		}
		return a;
	}
	return $(el).val();
};

/**
 * Clears the form data.  Takes the following actions on the form's input fields:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 */
$.fn.clearForm = function() {
	return this.each(function() {
		$('input,select,textarea', this).clearFields();
	});
};

/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function() {
	var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
	return this.each(function() {
		var t = this.type, tag = this.tagName.toLowerCase();
		if (re.test(t) || tag == 'textarea') {
			this.value = '';
		}
		else if (t == 'checkbox' || t == 'radio') {
			this.checked = false;
		}
		else if (tag == 'select') {
			this.selectedIndex = -1;
		}
	});
};

/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 */
$.fn.resetForm = function() {
	return this.each(function() {
		// guard against an input with the name of 'reset'
		// note that IE reports the reset function as an 'object'
		if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
			this.reset();
		}
	});
};

/**
 * Enables or disables any matching elements.
 */
$.fn.enable = function(b) {
	if (b === undefined) {
		b = true;
	}
	return this.each(function() {
		this.disabled = !b;
	});
};

/**
 * Checks/unchecks any matching checkboxes or radio buttons and
 * selects/deselects and matching option elements.
 */
$.fn.selected = function(select) {
	if (select === undefined) {
		select = true;
	}
	return this.each(function() {
		var t = this.type;
		if (t == 'checkbox' || t == 'radio') {
			this.checked = select;
		}
		else if (this.tagName.toLowerCase() == 'option') {
			var $sel = $(this).parent('select');
			if (select && $sel[0] && $sel[0].type == 'select-one') {
				// deselect all other options
				$sel.find('option').selected(false);
			}
			this.selected = select;
		}
	});
};

// helper fn for console logging
function log() {
	var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'');
	if (window.console && window.console.log) {
		//window.console.log(msg);
	}
	else if (window.opera && window.opera.postError) {
		//window.opera.postError(msg);
	}
};

})(jQuery);
/*!
 * jQuery Taconite plugin - A port of the Taconite framework by Ryan Asleson and
 *     Nathaniel T. Schutta: http://taconite.sourceforge.net/
 *
 * Examples and documentation at: http://malsup.com/jquery/taconite/
 * Copyright (c) 2007-2011 M. Alsup
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Thanks to Kenton Simpson for contributing many good ideas!
 *
 * @version: 3.64  16-JUN-2011
 * @requires jQuery v1.3.2 or later
 */

(function($) {
var version = '3.64';

$.taconite = function(xml) {
    processDoc(xml);
};

$.taconite.debug = 0;  // set to true to enable debug logging to window.console.log
$.taconite.autodetect = true;
$.taconite.defaults = {
    cdataWrap: 'div'
};

// add 'replace' and 'replaceContent' plugins (conditionally)
$.fn.replace = $.fn.replace || function(a) {
    this.after(a);
    this.remove();
};
$.fn.replaceContent = $.fn.replaceContent || function(a) {
    return this.empty().append(a);
};

$.expr[':'].taconiteTag = function(a) {
    return a.taconiteTag === 1;
};

// allow auto-detection to be enabled/disabled on-demand
$.taconite.enableAutoDetection = function(b) {
    $.taconite.autodetect = b;
    if (origHttpData)
        $.httpData = b ? origHttpData : detect;
};

var logCount = 0;
function log() {
    if (!$.taconite.debug || !window.console || !window.console.log) return;
    !logCount++ && log('Plugin Version: ' + version);
    window.console.log('[taconite] ' + [].join.call(arguments,''));
}

var parseJSON = $.parseJSON || function(s) {
    return window['eval']('(' + s + ')');
};

function httpData( xhr, type, s ) {
    var ct = xhr.getResponseHeader('content-type') || '',
        xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
        data = xml ? xhr.responseXML : xhr.responseText;

    if (xml && data.documentElement.nodeName === 'parsererror') {
        $.error && $.error('parsererror');
    }
    if (s && s.dataFilter) {
        data = s.dataFilter(data, type);
    }
    if (typeof data === 'string') {
        if (type === 'json' || !type && ct.indexOf('json') >= 0) {
            data = parseJSON(data);
        } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
            $.globalEval(data);
        }
    }
    return data;
}

function getResponse(xhr, type, s) {
    if (origHttpData)
        return origHttpData(xhr, type, s);
    return xhr.responseXML || xhr.responseText;
}

function detect(xhr, type, s) {
    var ct = xhr.getResponseHeader('content-type');
    if ($.taconite.debug) {
        log('[AJAX response] content-type: ', ct, ';  status: ', xhr.status, ' ', xhr.statusText, ';  has responseXML: ', xhr.responseXML != null);
        log('type arg: ' + type);
//        log('responseXML: ' + xhr.responseXML);  // IE9 doesn't like xhr.toString()
    }
    var data = getResponse(xhr, type, s);
    if (data && data.documentElement && data.documentElement.nodeName != 'parsererror') {
        $.taconite(data);
    }
    else if (typeof data == 'string') {
        // issue #4 (don't try to parse plain text or html responses
        if ( /taconite/.test(data) )
            $.taconite(data);
    }
    else {
        log('jQuery core httpData returned: ' + data);
        log('httpData: response is not XML (or not "valid" XML)');
    }
    return data;
}

// 1.5+ hook
$.ajaxPrefilter && $.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
    jqXHR.success(function( data, status, jqXHR ) {
        if ($.taconite.autodetect)
            detect(jqXHR, options.dataType, options);
    });
});

// < 1.5 hook
var origHttpData = $.httpData;
if ($.httpData)
    $.httpData = detect;  // replace jQuery's httpData method

// custom data parsers
var parsers = { 'json': jsonParser }, rawData, rawDataIndic;

$.taconite.registerParser = function(type, fn) {
    parsers[type] = fn;
};

function parseRawData(type, data) {
    var d = data, parser = parsers[type];
    if ($.isFunction(parser))
        return parser(data);
    else
        throw 'No parser registered for rawData of type "' + type + '"';
}

function jsonParser(json) {
    return parseJSON(json);
}


function processDoc(xml) {
    var status = true, ex;
    try {
        if (typeof xml == 'string')
            xml = convert(xml);
        if (! ( xml && xml.documentElement) ) {
            log('$.taconite invoked without valid document; nothing to process');
            return false;
        }

        var root = xml.documentElement.tagName;
        log('XML document root: ', root);

        var taconiteDoc = $('taconite', xml)[0];

        if (!taconiteDoc) {
            log('document does not contain <taconite> element; nothing to process');
            return false;
        }

        $.event.trigger('taconite-begin-notify', [taconiteDoc]);
        status = go(taconiteDoc);
    } catch(e) {
        status = ex = e;
    }
    rawDataIndic && $.event.trigger('taconite-rawdata-notify', [rawData]);
    $.event.trigger('taconite-complete-notify', [xml, !!status, status === true ? null : status]);
    if (ex)
        throw ex;
}

// convert string to xml document
function convert(s) {
    var doc;
    log('attempting string to document conversion');
    try {
        if (window.DOMParser) {
            var parser = new DOMParser();
            doc = parser.parseFromString(s, 'text/xml');
        }
        else {
            doc = $("<xml>")[0];
            doc.async = 'false';
            doc.loadXML(s);
        }
    }
    catch(e) {
        if (window.console && window.console.error)
            window.console.error('[taconite] ERROR parsing XML string for conversion: ' + e);
        throw e;
    }
    var ok = doc && doc.documentElement && doc.documentElement.tagName != 'parsererror';
    log('conversion ', ok ? 'successful!' : 'FAILED');
    return doc;
}

function go(xml) {
    try {
        var t = new Date().getTime();
        // process the document
        process(xml.childNodes);
        $.taconite.lastTime = (new Date().getTime()) - t;
        log('time to process response: ' + $.taconite.lastTime + 'ms');
    } catch(e) {
        if (window.console && window.console.error)
            window.console.error('[taconite] ERROR processing document: ' + e);
        throw e;
    }
    return true;
}

// process the taconite commands
function process(commands) {
    rawData = {};
    rawDataIndic = false;
    var trimHash = { wrap: 1 };
    var doPostProcess = 0;
    var a, n, v, i, j, js, els, raw, type, q, jq, cdataWrap;

    for(i=0; i < commands.length; i++) {
        if (commands[i].nodeType != 1)
            continue; // commands are elements
        var cmdNode = commands[i], cmd = cmdNode.tagName;
        if (cmd == 'eval') {
            js = (cmdNode.firstChild ? cmdNode.firstChild.nodeValue : null);
            log('invoking "eval" command: ', js);
            if (js)
                $.globalEval(js);
            continue;
        }
        if (cmd == 'rawData') {
            raw = (cmdNode.firstChild ? cmdNode.firstChild.nodeValue : null);
            type = cmdNode.getAttribute('type');
            log('rawData ('+type+'): ', raw);

            var namespace = cmdNode.getAttribute('namespace') || 'none';

            !rawData[namespace] && (rawData[namespace] = []);

            rawData[namespace].push({
                data: parseRawData(type, raw),
                type: type,
                name: cmdNode.getAttribute('name') || null,
                raw: raw
            });
            !rawDataIndic && (rawDataIndic = true);
            continue;
        }
        q = cmdNode.getAttribute('select');
        jq = $(q);
        if (!jq[0]) {
            log('No matching targets for selector: ', q);
            continue;
        }
        cdataWrap = cmdNode.getAttribute('cdataWrap') || $.taconite.defaults.cdataWrap;

        a = [];
        if (cmdNode.childNodes.length > 0) {
            doPostProcess = 1;
            for (j=0,els=[]; j < cmdNode.childNodes.length; j++)
                els[j] = createNode(cmdNode.childNodes[j], cdataWrap);
            a.push(trimHash[cmd] ? cleanse(els) : els);
        }

        // remain backward compat with pre 2.0.9 versions
        n = cmdNode.getAttribute('name');
        v = cmdNode.getAttribute('value');
        if (n !== null) a.push(n);
        if (v !== null) a.push(v);

        // @since: 2.0.9: support arg1, arg2, arg3...
        for (var j=1; true; j++) {
            v = cmdNode.getAttribute('arg'+j);
            if (v === null)
                break;
            // support numeric primitives
            if (v.length) {
                var n = Number(v);
                if (v == n)
                    v = n;
            }
            a.push(v);
        }

        $.taconite.debug && logCommand(q, cmd, a, els);
        jq[cmd].apply(jq,a);
    }

    // apply dynamic fixes
    doPostProcess && postProcess();
}

function logCommand(q, cmd, a, els) {
    var args = '...';
    if (!els) {
        args = '';
        for (var k=0, val=a[0]; k < a.length, val=a[k]; k++) {
            k > 0 && (args += ',');
            typeof val == 'string' ? (args += ("'" + val + "'")) : (args += val);
        }
    }
    log("invoking command: $('", q, "').", cmd, '('+ args +')');
}

function postProcess() {
    if ($.browser.mozilla) return;
    // post processing fixes go here; currently there is only one:
    // fix1: opera, IE6, Safari/Win don't maintain selected options in all cases (thanks to Karel Fučík for this!)
    $('select:taconiteTag').each(function() {
        var sel = this;
        $('option:taconiteTag', this).each(function() {
            this.setAttribute('selected','selected');
            this.taconiteTag = null;
            if (sel.type == 'select-one') {
                var idx = $('option',sel).index(this);
                sel.selectedIndex = idx;
            }
        });
        this.taconiteTag = null;
    });
}

function cleanse(els) {
    for (var i=0, a=[]; i < els.length; i++)
        if (els[i].nodeType == 1) a.push(els[i]);
    return a;
}

function createNode(node, cdataWrap) {
    var type = node.nodeType;
    if (type == 1) return createElement(node, cdataWrap);
    if (type == 3) return fixTextNode(node.nodeValue);
    if (type == 4) return handleCDATA(node.nodeValue, cdataWrap);
    return null;
}

function handleCDATA(s, cdataWrap) {
    var el = document.createElement(cdataWrap);
    var $el = $(el)[cdataWrap == 'script' ? 'text' : 'html'](s);
    var $ch = $el.children();

    // remove wrapper node if possible
    if ($ch.size() == 1)
        return $ch[0];
    return el;
}

function fixTextNode(s) {
    if ($.browser.msie) s = s.replace(/\n/g, '\r').replace(/\s+/g, ' ');
    return document.createTextNode(s);
}

function createElement(node, cdataWrap) {
    var e, tag = node.tagName.toLowerCase();
    // some elements in IE need to be created with attrs inline
    if ($.browser.msie && $.browser.version < 9) {
        var type = node.getAttribute('type');
        if (tag == 'table' || type == 'radio' || type == 'checkbox' || tag == 'button' ||
            (tag == 'select' && node.getAttribute('multiple'))) {
            e = document.createElement('<' + tag + ' ' + copyAttrs(null, node, true) + '>');
        }
    }
    if (!e) {
        e = document.createElement(tag);
        // copyAttrs(e, node, tag == 'option' && $.browser.safari);
        copyAttrs(e, node);
    }

    // IE fix; colspan must be explicitly set
    if ($.browser.msie && tag == 'td') {
        var colspan = node.getAttribute('colspan');
        if (colspan) e.colSpan = parseInt(colspan);
    }

    // IE fix; script tag not allowed to have children
    if($.browser.msie && !e.canHaveChildren) {
        if(node.childNodes.length > 0)
            e.text = node.text;
    }
    else {
        for(var i=0, max=node.childNodes.length; i < max; i++) {
            var child = createNode (node.childNodes[i], cdataWrap);
            if(child) e.appendChild(child);
        }
    }
    if (! $.browser.mozilla) {
        if (tag == 'select' || (tag == 'option' && node.getAttribute('selected')))
            e.taconiteTag = 1;
    }
    return e;
}

function copyAttrs(dest, src, inline) {
    for (var i=0, attr=''; i < src.attributes.length; i++) {
        var a = src.attributes[i], n = $.trim(a.name), v = $.trim(a.value);
        if (inline) attr += (n + '="' + v + '" ');
        else if (n == 'style') { // IE workaround
            dest.style.cssText = v;
            dest.setAttribute(n, v);
        }
        else $.attr(dest, n, v);
    }
    return attr;
}

})(jQuery);

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/**
 * jQuery lightBox plugin
 * This jQuery plugin was inspired and based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
 * and adapted to me for use like a plugin from jQuery.
 * @name jquery-lightbox-0.5.js
 * @author Leandro Vieira Pinho - http://leandrovieira.com
 * @version 0.5
 * @date April 11, 2008
 * @category jQuery plugin
 * @copyright (c) 2008 Leandro Vieira Pinho (leandrovieira.com)
 * @license CC Attribution-No Derivative Works 2.5 Brazil - http://creativecommons.org/licenses/by-nd/2.5/br/deed.en_US
 * @example Visit http://leandrovieira.com/projects/jquery/lightbox/ for more informations about this jQuery plugin
 */

// Offering a Custom Alias suport - More info: http://docs.jquery.com/Plugins/Authoring#Custom_Alias
(function($) {
	/**
	 * $ is an alias to jQuery object
	 *
	 */
	$.fn.lightBox = function(settings) {
		// Settings to configure the jQuery lightBox plugin how you like
		settings = jQuery.extend({
			// Configuration related to overlay
			overlayBgColor: 		'#000',		// (string) Background color to overlay; inform a hexadecimal value like: #RRGGBB. Where RR, GG, and BB are the hexadecimal values for the red, green, and blue values of the color.
			overlayOpacity:			0.8,		// (integer) Opacity value to overlay; inform: 0.X. Where X are number from 0 to 9
			// Configuration related to navigation
			fixedNavigation:		false,		// (boolean) Boolean that informs if the navigation (next and prev button) will be fixed or not in the interface.
			// Configuration related to images
			imageLoading:			'/Orion/shared/lightbox/cargando.gif',		// (string) Path and the name of the loading icon
			imageBtnPrev:			'/Orion/shared/lightbox/anterior.gif',			// (string) Path and the name of the prev button image
			imageBtnNext:			'/Orion/shared/lightbox/siguiente.gif',			// (string) Path and the name of the next button image
			imageBtnClose:			'/Orion/shared/lightbox/cerrar.gif',		// (string) Path and the name of the close btn
			imageBlank:				'/Orion/shared/lightbox/lightbox-blank.gif',			// (string) Path and the name of a blank image (one pixel)
			// Configuration related to container image box
			containerBorderSize:	10,			// (integer) If you adjust the padding in the CSS for the container, #lightbox-container-image-box, you will need to update this value
			containerResizeSpeed:	400,		// (integer) Specify the resize duration of container image. These number are miliseconds. 400 is default.
			// Configuration related to texts in caption. For example: Image 2 of 8. You can alter either "Image" and "of" texts.
			txtImage:				'Imagen',	// (string) Specify text "Image"
			txtOf:					'de',		// (string) Specify text "of"
			// Configuration related to keyboard navigation
			keyToClose:				'c',		// (string) (c = close) Letter to close the jQuery lightBox interface. Beyond this letter, the letter X and the SCAPE key is used to.
			keyToPrev:				'a',		// (string) (p = previous) Letter to show the previous image
			keyToNext:				's',		// (string) (n = next) Letter to show the next image.
			// Don�t alter these variables in any way
			imageArray:				[],
			activeImage:			0
		},settings);
		// Caching the jQuery object with all elements matched
		var jQueryMatchedObj = this; // This, in this context, refer to jQuery object
		/**
		 * Initializing the plugin calling the start function
		 *
		 * @return boolean false
		 */
		function _initialize() {
			_start(this,jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked
			return false; // Avoid the browser following the link
		}
		/**
		 * Start the jQuery lightBox plugin
		 *
		 * @param object objClicked The object (link) whick the user have clicked
		 * @param object jQueryMatchedObj The jQuery object with all elements matched
		 */
		function _start(objClicked,jQueryMatchedObj) {
			// Hime some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
			$('embed, object, select').css({ 'visibility' : 'hidden' });
			// Call the function to create the markup structure; style some elements; assign events in some elements.
			_set_interface();
			// Unset total images in imageArray
			settings.imageArray.length = 0;
			// Unset image active information
			settings.activeImage = 0;
			// We have an image set? Or just an image? Let�s see it.
			if ( jQueryMatchedObj.length == 1 ) {
				settings.imageArray.push(new Array(objClicked.getAttribute('href'),objClicked.getAttribute('title')));
			} else {
				// Add an Array (as many as we have), with href and title atributes, inside the Array that storage the images references		
				for ( var i = 0; i < jQueryMatchedObj.length; i++ ) {
					settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'),jQueryMatchedObj[i].getAttribute('title')));
				}
			}
			while ( settings.imageArray[settings.activeImage][0] != objClicked.getAttribute('href') ) {
				settings.activeImage++;
			}
			// Call the function that prepares image exibition
			_set_image_to_view();
		}
		/**
		 * Create the jQuery lightBox plugin interface
		 *
		 * The HTML markup will be like that:
			<div id="jquery-overlay"></div>
			<div id="jquery-lightbox">
				<div id="lightbox-container-image-box">
					<div id="lightbox-container-image">
						<img src="../fotos/XX.jpg" id="lightbox-image">
						<div id="lightbox-nav">
							<a href="#" id="lightbox-nav-btnPrev"></a>
							<a href="#" id="lightbox-nav-btnNext"></a>
						</div>
						<div id="lightbox-loading">
							<a href="#" id="lightbox-loading-link">
								<img src="../images/lightbox-ico-loading.gif">
							</a>
						</div>
					</div>
				</div>
				<div id="lightbox-container-image-data-box">
					<div id="lightbox-container-image-data">
						<div id="lightbox-image-details">
							<span id="lightbox-image-details-caption"></span>
							<span id="lightbox-image-details-currentNumber"></span>
						</div>
						<div id="lightbox-secNav">
							<a href="#" id="lightbox-secNav-btnClose">
								<img src="../images/lightbox-btn-close.gif">
							</a>
						</div>
					</div>
				</div>
			</div>
		 *
		 */
		function _set_interface() {
			// Apply the HTML markup into body tag
			$('body').append('<div id="jquery-overlay"></div><div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image"><img id="lightbox-image"><div style="" id="lightbox-nav"><a href="#" id="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext"></a></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="' + settings.imageLoading + '"></a></div></div></div><div id="lightbox-container-image-data-box"><div id="lightbox-container-image-data"><div id="lightbox-image-details"><span id="lightbox-image-details-caption"></span><span id="lightbox-image-details-currentNumber"></span></div><div id="lightbox-secNav"><a href="#" id="lightbox-secNav-btnClose"><img src="' + settings.imageBtnClose + '"></a></div></div></div></div>');	
			// Get page sizes
			var arrPageSizes = ___getPageSize();
			// Style overlay and show it
			$('#jquery-overlay').css({
				backgroundColor:	settings.overlayBgColor,
				opacity:			settings.overlayOpacity,
				width:				arrPageSizes[0],
				height:				arrPageSizes[1]
			}).fadeIn();
			// Get page scroll
			var arrPageScroll = ___getPageScroll();
			// Calculate top and left offset for the jquery-lightbox div object and show it
			$('#jquery-lightbox').css({
				top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
				left:	arrPageScroll[0]
			}).show();
			// Assigning click events in elements to close overlay
			$('#jquery-overlay,#jquery-lightbox').click(function() {
				_finish();									
			});
			// Assign the _finish function to lightbox-loading-link and lightbox-secNav-btnClose objects
			$('#lightbox-loading-link,#lightbox-secNav-btnClose').click(function() {
				_finish();
				return false;
			});
			// If window was resized, calculate the new overlay dimensions
			$(window).resize(function() {
				// Get page sizes
				var arrPageSizes = ___getPageSize();
				// Style overlay and show it
				$('#jquery-overlay').css({
					width:		arrPageSizes[0],
					height:		arrPageSizes[1]
				});
				// Get page scroll
				var arrPageScroll = ___getPageScroll();
				// Calculate top and left offset for the jquery-lightbox div object and show it
				$('#jquery-lightbox').css({
					top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
					left:	arrPageScroll[0]
				});
			});
		}
		/**
		 * Prepares image exibition; doing a image�s preloader to calculate it�s size
		 *
		 */
		function _set_image_to_view() { // show the loading
			// Show the loading
			$('#lightbox-loading').show();
			if ( settings.fixedNavigation ) {
				$('#lightbox-image,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();
			} else {
				// Hide some elements
				$('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();
			}
			// Image preload process
			var objImagePreloader = new Image();
			objImagePreloader.onload = function() {
				$('#lightbox-image').attr('src',settings.imageArray[settings.activeImage][0]);
				// Perfomance an effect in the image container resizing it
				_resize_container_image_box(objImagePreloader.width,objImagePreloader.height);
				//	clear onLoad, IE behaves irratically with animated gifs otherwise
				objImagePreloader.onload=function(){};
			};
			objImagePreloader.src = settings.imageArray[settings.activeImage][0];
		};
		/**
		 * Perfomance an effect in the image container resizing it
		 *
		 * @param integer intImageWidth The image�s width that will be showed
		 * @param integer intImageHeight The image�s height that will be showed
		 */
		function _resize_container_image_box(intImageWidth,intImageHeight) {
			// Get current width and height
			var intCurrentWidth = $('#lightbox-container-image-box').width();
			var intCurrentHeight = $('#lightbox-container-image-box').height();
			// Get the width and height of the selected image plus the padding
			var intWidth = (intImageWidth + (settings.containerBorderSize * 2)); // Plus the image�s width and the left and right padding value
			var intHeight = (intImageHeight + (settings.containerBorderSize * 2)); // Plus the image�s height and the left and right padding value
			// Diferences
			var intDiffW = intCurrentWidth - intWidth;
			var intDiffH = intCurrentHeight - intHeight;
			// Perfomance the effect
			$('#lightbox-container-image-box').animate({ width: intWidth, height: intHeight },settings.containerResizeSpeed,function() { _show_image(); });
			if ( ( intDiffW == 0 ) && ( intDiffH == 0 ) ) {
				if ( $.browser.msie ) {
					___pause(250);
				} else {
					___pause(100);	
				}
			} 
			$('#lightbox-container-image-data-box').css({ width: intImageWidth });
			$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ height: intImageHeight + (settings.containerBorderSize * 2) });
		};
		/**
		 * Show the prepared image
		 *
		 */
		function _show_image() {
			$('#lightbox-loading').hide();
			$('#lightbox-image').fadeIn(function() {
				_show_image_data();
				_set_navigation();
			});
			_preload_neighbor_images();
		};
		/**
		 * Show the image information
		 *
		 */
		function _show_image_data() {
			$('#lightbox-container-image-data-box').slideDown('fast');
			$('#lightbox-image-details-caption').hide();
			if ( settings.imageArray[settings.activeImage][1] ) {
				$('#lightbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show();
			}
			// If we have a image set, display 'Image X of X'
			//if ( settings.imageArray.length > 1 ) {
                                var downloadpicture = settings.imageArray[settings.activeImage][0];
                                var fileSrc = downloadpicture.replace('/big/', '/source/');
                                fileSrc = fileSrc.replace(/^\//,'');
                                fileSrc = urlencode(fileSrc);
                                var enlace = ' <a href="/Resources/files/download?file='+fileSrc+'" target="_blank">(descargar)</a>';


				$('#lightbox-image-details-currentNumber').html(settings.txtImage + ' ' + ( settings.activeImage + 1 ) + ' ' + settings.txtOf + ' ' + settings.imageArray.length + enlace).show();
			//}
		}
		/**
		 * Display the button navigations
		 *
		 */
		function _set_navigation() {
			$('#lightbox-nav').show();

			// Instead to define this configuration in CSS file, we define here. And it�s need to IE. Just.
			$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
			
			// Show the prev button, if not the first image in set
			if ( settings.activeImage != 0 ) {
				if ( settings.fixedNavigation ) {
					$('#lightbox-nav-btnPrev').css({ 'background' : 'url(' + settings.imageBtnPrev + ') left 15% no-repeat' })
						.unbind()
						.bind('click',function() {
							settings.activeImage = settings.activeImage - 1;
							_set_image_to_view();
							return false;
						});
				} else {
					// Show the images button for Next buttons
					$('#lightbox-nav-btnPrev').unbind().hover(function() {
						$(this).css({ 'background' : 'url(' + settings.imageBtnPrev + ') left 15% no-repeat' });
					},function() {
						$(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
					}).show().bind('click',function() {
						settings.activeImage = settings.activeImage - 1;
						_set_image_to_view();
						return false;
					});
				}
			}
			
			// Show the next button, if not the last image in set
			if ( settings.activeImage != ( settings.imageArray.length -1 ) ) {
				if ( settings.fixedNavigation ) {
					$('#lightbox-nav-btnNext').css({ 'background' : 'url(' + settings.imageBtnNext + ') right 15% no-repeat' })
						.unbind()
						.bind('click',function() {
							settings.activeImage = settings.activeImage + 1;
							_set_image_to_view();
							return false;
						});
				} else {
					// Show the images button for Next buttons
					$('#lightbox-nav-btnNext').unbind().hover(function() {
						$(this).css({ 'background' : 'url(' + settings.imageBtnNext + ') right 15% no-repeat' });
					},function() {
						$(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
					}).show().bind('click',function() {
						settings.activeImage = settings.activeImage + 1;
						_set_image_to_view();
						return false;
					});
				}
			}
			// Enable keyboard navigation
			_enable_keyboard_navigation();
		}
		/**
		 * Enable a support to keyboard navigation
		 *
		 */
		function _enable_keyboard_navigation() {
			$(document).keydown(function(objEvent) {
				_keyboard_action(objEvent);
			});
		}
		/**
		 * Disable the support to keyboard navigation
		 *
		 */
		function _disable_keyboard_navigation() {
			$(document).unbind();
		}
		/**
		 * Perform the keyboard actions
		 *
		 */
		function _keyboard_action(objEvent) {
			// To ie
			if ( objEvent == null ) {
				keycode = event.keyCode;
				escapeKey = 27;
			// To Mozilla
			} else {
				keycode = objEvent.keyCode;
				escapeKey = objEvent.DOM_VK_ESCAPE;
			}
			// Get the key in lower case form
			key = String.fromCharCode(keycode).toLowerCase();
			// Verify the keys to close the ligthBox
			if ( ( key == settings.keyToClose ) || ( key == 'x' ) || ( keycode == escapeKey ) ) {
				_finish();
			}
			// Verify the key to show the previous image
			if ( ( key == settings.keyToPrev ) || ( keycode == 37 ) ) {
				// If we�re not showing the first image, call the previous
				if ( settings.activeImage != 0 ) {
					settings.activeImage = settings.activeImage - 1;
					_set_image_to_view();
					_disable_keyboard_navigation();
				}
			}
			// Verify the key to show the next image
			if ( ( key == settings.keyToNext ) || ( keycode == 39 ) ) {
				// If we�re not showing the last image, call the next
				if ( settings.activeImage != ( settings.imageArray.length - 1 ) ) {
					settings.activeImage = settings.activeImage + 1;
					_set_image_to_view();
					_disable_keyboard_navigation();
				}
			}
		}
		/**
		 * Preload prev and next images being showed
		 *
		 */
		function _preload_neighbor_images() {
			if ( (settings.imageArray.length -1) > settings.activeImage ) {
				objNext = new Image();
				objNext.src = settings.imageArray[settings.activeImage + 1][0];
			}
			if ( settings.activeImage > 0 ) {
				objPrev = new Image();
				objPrev.src = settings.imageArray[settings.activeImage -1][0];
			}
		}
		/**
		 * Remove jQuery lightBox plugin HTML markup
		 *
		 */
		function _finish() {
			$('#jquery-lightbox').remove();
			$('#jquery-overlay').fadeOut(function() { $('#jquery-overlay').remove(); });
			// Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
			$('embed, object, select').css({ 'visibility' : 'visible' });
		}
		/**
		 / THIRD FUNCTION
		 * getPageSize() by quirksmode.com
		 *
		 * @return Array Return an array with page width, height and window width, height
		 */
		function ___getPageSize() {
			var xScroll, yScroll;
			if (window.innerHeight && window.scrollMaxY) {	
				xScroll = window.innerWidth + window.scrollMaxX;
				yScroll = window.innerHeight + window.scrollMaxY;
			} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
				xScroll = document.body.scrollWidth;
				yScroll = document.body.scrollHeight;
			} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
				xScroll = document.body.offsetWidth;
				yScroll = document.body.offsetHeight;
			}
			var windowWidth, windowHeight;
			if (self.innerHeight) {	// all except Explorer
				if(document.documentElement.clientWidth){
					windowWidth = document.documentElement.clientWidth; 
				} else {
					windowWidth = self.innerWidth;
				}
				windowHeight = self.innerHeight;
			} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
				windowWidth = document.documentElement.clientWidth;
				windowHeight = document.documentElement.clientHeight;
			} else if (document.body) { // other Explorers
				windowWidth = document.body.clientWidth;
				windowHeight = document.body.clientHeight;
			}	
			// for small pages with total height less then height of the viewport
			if(yScroll < windowHeight){
				pageHeight = windowHeight;
			} else { 
				pageHeight = yScroll;
			}
			// for small pages with total width less then width of the viewport
			if(xScroll < windowWidth){	
				pageWidth = xScroll;		
			} else {
				pageWidth = windowWidth;
			}
			arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
			return arrayPageSize;
		};
		/**
		 / THIRD FUNCTION
		 * getPageScroll() by quirksmode.com
		 *
		 * @return Array Return an array with x,y page scroll values.
		 */
		function ___getPageScroll() {
			var xScroll, yScroll;
			if (self.pageYOffset) {
				yScroll = self.pageYOffset;
				xScroll = self.pageXOffset;
			} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
				yScroll = document.documentElement.scrollTop;
				xScroll = document.documentElement.scrollLeft;
			} else if (document.body) {// all other Explorers
				yScroll = document.body.scrollTop;
				xScroll = document.body.scrollLeft;	
			}
			arrayPageScroll = new Array(xScroll,yScroll);
			return arrayPageScroll;
		};
		 /**
		  * Stop the code execution from a escified time in milisecond
		  *
		  */
		 function ___pause(ms) {
			var date = new Date(); 
			curDate = null;
			do { var curDate = new Date(); }
			while ( curDate - date < ms);
		 };
		// Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once
		return this.unbind('click').click(_initialize);
	};
})(jQuery); // Call and execute the function immediately passing the jQuery object


/*!
 * jQuery hashchange event - v1.3 - 7/21/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */

// Script: jQuery hashchange event
//
// *Version: 1.3, Last updated: 7/21/2010*
// 
// Project Home - http://benalman.com/projects/jquery-hashchange-plugin/
// GitHub       - http://github.com/cowboy/jquery-hashchange/
// Source       - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js
// (Minified)   - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (0.8kb gzipped)
// 
// About: License
// 
// Copyright (c) 2010 "Cowboy" Ben Alman,
// Dual licensed under the MIT and GPL licenses.
// http://benalman.com/about/license/
// 
// About: Examples
// 
// These working examples, complete with fully commented code, illustrate a few
// ways in which this plugin can be used.
// 
// hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/
// document.domain - http://benalman.com/code/projects/jquery-hashchange/examples/document_domain/
// 
// About: Support and Testing
// 
// Information about what version or versions of jQuery this plugin has been
// tested with, what browsers it has been tested in, and where the unit tests
// reside (so you can test it yourself).
// 
// jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2
// Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5,
//                   Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5.
// Unit Tests      - http://benalman.com/code/projects/jquery-hashchange/unit/
// 
// About: Known issues
// 
// While this jQuery hashchange event implementation is quite stable and
// robust, there are a few unfortunate browser bugs surrounding expected
// hashchange event-based behaviors, independent of any JavaScript
// window.onhashchange abstraction. See the following examples for more
// information:
// 
// Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/
// Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/
// WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/
// Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/
// 
// Also note that should a browser natively support the window.onhashchange 
// event, but not report that it does, the fallback polling loop will be used.
// 
// About: Release History
// 
// 1.3   - (7/21/2010) Reorganized IE6/7 Iframe code to make it more
//         "removable" for mobile-only development. Added IE6/7 document.title
//         support. Attempted to make Iframe as hidden as possible by using
//         techniques from http://www.paciellogroup.com/blog/?p=604. Added 
//         support for the "shortcut" format $(window).hashchange( fn ) and
//         $(window).hashchange() like jQuery provides for built-in events.
//         Renamed jQuery.hashchangeDelay to <jQuery.fn.hashchange.delay> and
//         lowered its default value to 50. Added <jQuery.fn.hashchange.domain>
//         and <jQuery.fn.hashchange.src> properties plus document-domain.html
//         file to address access denied issues when setting document.domain in
//         IE6/7.
// 1.2   - (2/11/2010) Fixed a bug where coming back to a page using this plugin
//         from a page on another domain would cause an error in Safari 4. Also,
//         IE6/7 Iframe is now inserted after the body (this actually works),
//         which prevents the page from scrolling when the event is first bound.
//         Event can also now be bound before DOM ready, but it won't be usable
//         before then in IE6/7.
// 1.1   - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug
//         where browser version is incorrectly reported as 8.0, despite
//         inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag.
// 1.0   - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special
//         window.onhashchange functionality into a separate plugin for users
//         who want just the basic event & back button support, without all the
//         extra awesomeness that BBQ provides. This plugin will be included as
//         part of jQuery BBQ, but also be available separately.

(function($,window,undefined){
  '$:nomunge'; // Used by YUI compressor.
  
  // Reused string.
  var str_hashchange = 'hashchange',
    
    // Method / object references.
    doc = document,
    fake_onhashchange,
    special = $.event.special,
    
    // Does the browser support window.onhashchange? Note that IE8 running in
    // IE7 compatibility mode reports true for 'onhashchange' in window, even
    // though the event isn't supported, so also test document.documentMode.
    doc_mode = doc.documentMode,
    supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 );
  
  // Get location.hash (or what you'd expect location.hash to be) sans any
  // leading #. Thanks for making this necessary, Firefox!
  function get_fragment( url ) {
    url = url || location.href;
    return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' );
  };
  
  // Method: jQuery.fn.hashchange
  // 
  // Bind a handler to the window.onhashchange event or trigger all bound
  // window.onhashchange event handlers. This behavior is consistent with
  // jQuery's built-in event handlers.
  // 
  // Usage:
  // 
  // > jQuery(window).hashchange( [ handler ] );
  // 
  // Arguments:
  // 
  //  handler - (Function) Optional handler to be bound to the hashchange
  //    event. This is a "shortcut" for the more verbose form:
  //    jQuery(window).bind( 'hashchange', handler ). If handler is omitted,
  //    all bound window.onhashchange event handlers will be triggered. This
  //    is a shortcut for the more verbose
  //    jQuery(window).trigger( 'hashchange' ). These forms are described in
  //    the <hashchange event> section.
  // 
  // Returns:
  // 
  //  (jQuery) The initial jQuery collection of elements.
  
  // Allow the "shortcut" format $(elem).hashchange( fn ) for binding and
  // $(elem).hashchange() for triggering, like jQuery does for built-in events.
  $.fn[ str_hashchange ] = function( fn ) {
    return fn ? this.bind( str_hashchange, fn ) : this.trigger( str_hashchange );
  };
  
  // Property: jQuery.fn.hashchange.delay
  // 
  // The numeric interval (in milliseconds) at which the <hashchange event>
  // polling loop executes. Defaults to 50.
  
  // Property: jQuery.fn.hashchange.domain
  // 
  // If you're setting document.domain in your JavaScript, and you want hash
  // history to work in IE6/7, not only must this property be set, but you must
  // also set document.domain BEFORE jQuery is loaded into the page. This
  // property is only applicable if you are supporting IE6/7 (or IE8 operating
  // in "IE7 compatibility" mode).
  // 
  // In addition, the <jQuery.fn.hashchange.src> property must be set to the
  // path of the included "document-domain.html" file, which can be renamed or
  // modified if necessary (note that the document.domain specified must be the
  // same in both your main JavaScript as well as in this file).
  // 
  // Usage:
  // 
  // jQuery.fn.hashchange.domain = document.domain;
  
  // Property: jQuery.fn.hashchange.src
  // 
  // If, for some reason, you need to specify an Iframe src file (for example,
  // when setting document.domain as in <jQuery.fn.hashchange.domain>), you can
  // do so using this property. Note that when using this property, history
  // won't be recorded in IE6/7 until the Iframe src file loads. This property
  // is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7
  // compatibility" mode).
  // 
  // Usage:
  // 
  // jQuery.fn.hashchange.src = 'path/to/file.html';
  
  $.fn[ str_hashchange ].delay = 50;
  /*
  $.fn[ str_hashchange ].domain = null;
  $.fn[ str_hashchange ].src = null;
  */
  
  // Event: hashchange event
  // 
  // Fired when location.hash changes. In browsers that support it, the native
  // HTML5 window.onhashchange event is used, otherwise a polling loop is
  // initialized, running every <jQuery.fn.hashchange.delay> milliseconds to
  // see if the hash has changed. In IE6/7 (and IE8 operating in "IE7
  // compatibility" mode), a hidden Iframe is created to allow the back button
  // and hash-based history to work.
  // 
  // Usage as described in <jQuery.fn.hashchange>:
  // 
  // > // Bind an event handler.
  // > jQuery(window).hashchange( function(e) {
  // >   var hash = location.hash;
  // >   ...
  // > });
  // > 
  // > // Manually trigger the event handler.
  // > jQuery(window).hashchange();
  // 
  // A more verbose usage that allows for event namespacing:
  // 
  // > // Bind an event handler.
  // > jQuery(window).bind( 'hashchange', function(e) {
  // >   var hash = location.hash;
  // >   ...
  // > });
  // > 
  // > // Manually trigger the event handler.
  // > jQuery(window).trigger( 'hashchange' );
  // 
  // Additional Notes:
  // 
  // * The polling loop and Iframe are not created until at least one handler
  //   is actually bound to the 'hashchange' event.
  // * If you need the bound handler(s) to execute immediately, in cases where
  //   a location.hash exists on page load, via bookmark or page refresh for
  //   example, use jQuery(window).hashchange() or the more verbose 
  //   jQuery(window).trigger( 'hashchange' ).
  // * The event can be bound before DOM ready, but since it won't be usable
  //   before then in IE6/7 (due to the necessary Iframe), recommended usage is
  //   to bind it inside a DOM ready handler.
  
  // Override existing $.event.special.hashchange methods (allowing this plugin
  // to be defined after jQuery BBQ in BBQ's source code).
  special[ str_hashchange ] = $.extend( special[ str_hashchange ], {
    
    // Called only when the first 'hashchange' event is bound to window.
    setup: function() {
      // If window.onhashchange is supported natively, there's nothing to do..
      if ( supports_onhashchange ) { return false; }
      
      // Otherwise, we need to create our own. And we don't want to call this
      // until the user binds to the event, just in case they never do, since it
      // will create a polling loop and possibly even a hidden Iframe.
      $( fake_onhashchange.start );
    },
    
    // Called only when the last 'hashchange' event is unbound from window.
    teardown: function() {
      // If window.onhashchange is supported natively, there's nothing to do..
      if ( supports_onhashchange ) { return false; }
      
      // Otherwise, we need to stop ours (if possible).
      $( fake_onhashchange.stop );
    }
    
  });
  
  // fake_onhashchange does all the work of triggering the window.onhashchange
  // event for browsers that don't natively support it, including creating a
  // polling loop to watch for hash changes and in IE 6/7 creating a hidden
  // Iframe to enable back and forward.
  fake_onhashchange = (function(){
    var self = {},
      timeout_id,
      
      // Remember the initial hash so it doesn't get triggered immediately.
      last_hash = get_fragment(),
      
      fn_retval = function(val){ return val; },
      history_set = fn_retval,
      history_get = fn_retval;
    
    // Start the polling loop.
    self.start = function() {
      timeout_id || poll();
    };
    
    // Stop the polling loop.
    self.stop = function() {
      timeout_id && clearTimeout( timeout_id );
      timeout_id = undefined;
    };
    
    // This polling loop checks every $.fn.hashchange.delay milliseconds to see
    // if location.hash has changed, and triggers the 'hashchange' event on
    // window when necessary.
    function poll() {
      var hash = get_fragment(),
        history_hash = history_get( last_hash );
      
      if ( hash !== last_hash ) {
        history_set( last_hash = hash, history_hash );
        
        $(window).trigger( str_hashchange );
        
      } else if ( history_hash !== last_hash ) {
        location.href = location.href.replace( /#.*/, '' ) + history_hash;
      }
      
      timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay );
    };
    
    // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    // vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv
    // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    $.browser.msie && !supports_onhashchange && (function(){
      // Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8
      // when running in "IE7 compatibility" mode.
      
      var iframe,
        iframe_src;
      
      // When the event is bound and polling starts in IE 6/7, create a hidden
      // Iframe for history handling.
      self.start = function(){
        if ( !iframe ) {
          iframe_src = $.fn[ str_hashchange ].src;
          iframe_src = iframe_src && iframe_src + get_fragment();
          
          // Create hidden Iframe. Attempt to make Iframe as hidden as possible
          // by using techniques from http://www.paciellogroup.com/blog/?p=604.
          iframe = $('<iframe tabindex="-1" title="empty"/>').hide()
            
            // When Iframe has completely loaded, initialize the history and
            // start polling.
            .one( 'load', function(){
              iframe_src || history_set( get_fragment() );
              poll();
            })
            
            // Load Iframe src if specified, otherwise nothing.
            .attr( 'src', iframe_src || 'javascript:0' )
            
            // Append Iframe after the end of the body to prevent unnecessary
            // initial page scrolling (yes, this works).
            .insertAfter( 'body' )[0].contentWindow;
          
          // Whenever `document.title` changes, update the Iframe's title to
          // prettify the back/next history menu entries. Since IE sometimes
          // errors with "Unspecified error" the very first time this is set
          // (yes, very useful) wrap this with a try/catch block.
          doc.onpropertychange = function(){
            try {
              if ( event.propertyName === 'title' ) {
                iframe.document.title = doc.title;
              }
            } catch(e) {}
          };
          
        }
      };
      
      // Override the "stop" method since an IE6/7 Iframe was created. Even
      // if there are no longer any bound event handlers, the polling loop
      // is still necessary for back/next to work at all!
      self.stop = fn_retval;
      
      // Get history by looking at the hidden Iframe's location.hash.
      history_get = function() {
        return get_fragment( iframe.location.href );
      };
      
      // Set a new history item by opening and then closing the Iframe
      // document, *then* setting its location.hash. If document.domain has
      // been set, update that as well.
      history_set = function( hash, history_hash ) {
        var iframe_doc = iframe.document,
          domain = $.fn[ str_hashchange ].domain;
        
        if ( hash !== history_hash ) {
          // Update Iframe with any initial `document.title` that might be set.
          iframe_doc.title = doc.title;
          
          // Opening the Iframe's document after it has been closed is what
          // actually adds a history entry.
          iframe_doc.open();
          
          // Set document.domain for the Iframe document as well, if necessary.
          domain && iframe_doc.write( '<script>document.domain="' + domain + '"</script>' );
          
          iframe_doc.close();
          
          // Update the Iframe's hash, for great justice.
          iframe.location.hash = hash;
        }
      };
      
    })();
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    // ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    
    return self;
  })();
  
})(jQuery,this);


	/**
	 * jQuery MD5 hash algorithm function
	 *
	 * 	<code>
	 * 		Calculate the md5 hash of a String
	 * 		String $.md5 ( String str )
	 * 	</code>
	 *
	 * Calculates the MD5 hash of str using the » RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash.
	 * MD5 (Message-Digest algorithm 5) is a widely-used cryptographic hash function with a 128-bit hash value. MD5 has been employed in a wide variety of security applications, and is also commonly used to check the integrity of data. The generated hash is also non-reversable. Data cannot be retrieved from the message digest, the digest uniquely identifies the data.
	 * MD5 was developed by Professor Ronald L. Rivest in 1994. Its 128 bit (16 byte) message digest makes it a faster implementation than SHA-1.
	 * This script is used to process a variable length message into a fixed-length output of 128 bits using the MD5 algorithm. It is fully compatible with UTF-8 encoding. It is very useful when u want to transfer encrypted passwords over the internet. If you plan using UTF-8 encoding in your project don't forget to set the page encoding to UTF-8 (Content-Type meta tag).
	 * This function orginally get from the WebToolkit and rewrite for using as the jQuery plugin.
	 *
	 * Example
	 * 	Code
	 * 		<code>
	 * 			$.md5("I'm Persian.");
	 * 		</code>
	 * 	Result
	 * 		<code>
	 * 			"b8c901d0f02223f9761016cfff9d68df"
	 * 		</code>
	 *
	 * @alias Muhammad Hussein Fattahizadeh < muhammad [AT] semnanweb [DOT] com >
	 * @link http://www.semnanweb.com/jquery-plugin/md5.html
	 * @see http://www.webtoolkit.info/
	 * @license http://www.gnu.org/licenses/gpl.html [GNU General Public License]
	 * @param {jQuery} {md5:function(string))
	 * @return string
	 */

	(function(jQuery){

		var rotateLeft = function(lValue, iShiftBits) {
			return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
		}

		var addUnsigned = function(lX, lY) {
			var lX4, lY4, lX8, lY8, lResult;
			lX8 = (lX & 0x80000000);
			lY8 = (lY & 0x80000000);
			lX4 = (lX & 0x40000000);
			lY4 = (lY & 0x40000000);
			lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
			if (lX4 & lY4) return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
			if (lX4 | lY4) {
				if (lResult & 0x40000000) return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
				else return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
			} else {
				return (lResult ^ lX8 ^ lY8);
			}
		}

		var F = function(x, y, z) {
			return (x & y) | ((~ x) & z);
		}

		var G = function(x, y, z) {
			return (x & z) | (y & (~ z));
		}

		var H = function(x, y, z) {
			return (x ^ y ^ z);
		}

		var I = function(x, y, z) {
			return (y ^ (x | (~ z)));
		}

		var FF = function(a, b, c, d, x, s, ac) {
			a = addUnsigned(a, addUnsigned(addUnsigned(F(b, c, d), x), ac));
			return addUnsigned(rotateLeft(a, s), b);
		};

		var GG = function(a, b, c, d, x, s, ac) {
			a = addUnsigned(a, addUnsigned(addUnsigned(G(b, c, d), x), ac));
			return addUnsigned(rotateLeft(a, s), b);
		};

		var HH = function(a, b, c, d, x, s, ac) {
			a = addUnsigned(a, addUnsigned(addUnsigned(H(b, c, d), x), ac));
			return addUnsigned(rotateLeft(a, s), b);
		};

		var II = function(a, b, c, d, x, s, ac) {
			a = addUnsigned(a, addUnsigned(addUnsigned(I(b, c, d), x), ac));
			return addUnsigned(rotateLeft(a, s), b);
		};

		var convertToWordArray = function(string) {
			var lWordCount;
			var lMessageLength = string.length;
			var lNumberOfWordsTempOne = lMessageLength + 8;
			var lNumberOfWordsTempTwo = (lNumberOfWordsTempOne - (lNumberOfWordsTempOne % 64)) / 64;
			var lNumberOfWords = (lNumberOfWordsTempTwo + 1) * 16;
			var lWordArray = Array(lNumberOfWords - 1);
			var lBytePosition = 0;
			var lByteCount = 0;
			while (lByteCount < lMessageLength) {
				lWordCount = (lByteCount - (lByteCount % 4)) / 4;
				lBytePosition = (lByteCount % 4) * 8;
				lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition));
				lByteCount++;
			}
			lWordCount = (lByteCount - (lByteCount % 4)) / 4;
			lBytePosition = (lByteCount % 4) * 8;
			lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
			lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
			lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
			return lWordArray;
		};

		var wordToHex = function(lValue) {
			var WordToHexValue = "", WordToHexValueTemp = "", lByte, lCount;
			for (lCount = 0; lCount <= 3; lCount++) {
				lByte = (lValue >>> (lCount * 8)) & 255;
				WordToHexValueTemp = "0" + lByte.toString(16);
				WordToHexValue = WordToHexValue + WordToHexValueTemp.substr(WordToHexValueTemp.length - 2, 2);
			}
			return WordToHexValue;
		};

		var uTF8Encode = function(string) {
			string = string.replace(/\x0d\x0a/g, "\x0a");
			var output = "";
			for (var n = 0; n < string.length; n++) {
				var c = string.charCodeAt(n);
				if (c < 128) {
					output += String.fromCharCode(c);
				} else if ((c > 127) && (c < 2048)) {
					output += String.fromCharCode((c >> 6) | 192);
					output += String.fromCharCode((c & 63) | 128);
				} else {
					output += String.fromCharCode((c >> 12) | 224);
					output += String.fromCharCode(((c >> 6) & 63) | 128);
					output += String.fromCharCode((c & 63) | 128);
				}
			}
			return output;
		};

		jQuery.extend({
			md5: function(string) {
				var x = Array();
				var k, AA, BB, CC, DD, a, b, c, d;
				var S11=7, S12=12, S13=17, S14=22;
				var S21=5, S22=9 , S23=14, S24=20;
				var S31=4, S32=11, S33=16, S34=23;
				var S41=6, S42=10, S43=15, S44=21;
				string = uTF8Encode(string);
				x = convertToWordArray(string);
				a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
				for (k = 0; k < x.length; k += 16) {
					AA = a; BB = b; CC = c; DD = d;
					a = FF(a, b, c, d, x[k+0],  S11, 0xD76AA478);
					d = FF(d, a, b, c, x[k+1],  S12, 0xE8C7B756);
					c = FF(c, d, a, b, x[k+2],  S13, 0x242070DB);
					b = FF(b, c, d, a, x[k+3],  S14, 0xC1BDCEEE);
					a = FF(a, b, c, d, x[k+4],  S11, 0xF57C0FAF);
					d = FF(d, a, b, c, x[k+5],  S12, 0x4787C62A);
					c = FF(c, d, a, b, x[k+6],  S13, 0xA8304613);
					b = FF(b, c, d, a, x[k+7],  S14, 0xFD469501);
					a = FF(a, b, c, d, x[k+8],  S11, 0x698098D8);
					d = FF(d, a, b, c, x[k+9],  S12, 0x8B44F7AF);
					c = FF(c, d, a, b, x[k+10], S13, 0xFFFF5BB1);
					b = FF(b, c, d, a, x[k+11], S14, 0x895CD7BE);
					a = FF(a, b, c, d, x[k+12], S11, 0x6B901122);
					d = FF(d, a, b, c, x[k+13], S12, 0xFD987193);
					c = FF(c, d, a, b, x[k+14], S13, 0xA679438E);
					b = FF(b, c, d, a, x[k+15], S14, 0x49B40821);
					a = GG(a, b, c, d, x[k+1],  S21, 0xF61E2562);
					d = GG(d, a, b, c, x[k+6],  S22, 0xC040B340);
					c = GG(c, d, a, b, x[k+11], S23, 0x265E5A51);
					b = GG(b, c, d, a, x[k+0],  S24, 0xE9B6C7AA);
					a = GG(a, b, c, d, x[k+5],  S21, 0xD62F105D);
					d = GG(d, a, b, c, x[k+10], S22, 0x2441453);
					c = GG(c, d, a, b, x[k+15], S23, 0xD8A1E681);
					b = GG(b, c, d, a, x[k+4],  S24, 0xE7D3FBC8);
					a = GG(a, b, c, d, x[k+9],  S21, 0x21E1CDE6);
					d = GG(d, a, b, c, x[k+14], S22, 0xC33707D6);
					c = GG(c, d, a, b, x[k+3],  S23, 0xF4D50D87);
					b = GG(b, c, d, a, x[k+8],  S24, 0x455A14ED);
					a = GG(a, b, c, d, x[k+13], S21, 0xA9E3E905);
					d = GG(d, a, b, c, x[k+2],  S22, 0xFCEFA3F8);
					c = GG(c, d, a, b, x[k+7],  S23, 0x676F02D9);
					b = GG(b, c, d, a, x[k+12], S24, 0x8D2A4C8A);
					a = HH(a, b, c, d, x[k+5],  S31, 0xFFFA3942);
					d = HH(d, a, b, c, x[k+8],  S32, 0x8771F681);
					c = HH(c, d, a, b, x[k+11], S33, 0x6D9D6122);
					b = HH(b, c, d, a, x[k+14], S34, 0xFDE5380C);
					a = HH(a, b, c, d, x[k+1],  S31, 0xA4BEEA44);
					d = HH(d, a, b, c, x[k+4],  S32, 0x4BDECFA9);
					c = HH(c, d, a, b, x[k+7],  S33, 0xF6BB4B60);
					b = HH(b, c, d, a, x[k+10], S34, 0xBEBFBC70);
					a = HH(a, b, c, d, x[k+13], S31, 0x289B7EC6);
					d = HH(d, a, b, c, x[k+0],  S32, 0xEAA127FA);
					c = HH(c, d, a, b, x[k+3],  S33, 0xD4EF3085);
					b = HH(b, c, d, a, x[k+6],  S34, 0x4881D05);
					a = HH(a, b, c, d, x[k+9],  S31, 0xD9D4D039);
					d = HH(d, a, b, c, x[k+12], S32, 0xE6DB99E5);
					c = HH(c, d, a, b, x[k+15], S33, 0x1FA27CF8);
					b = HH(b, c, d, a, x[k+2],  S34, 0xC4AC5665);
					a = II(a, b, c, d, x[k+0],  S41, 0xF4292244);
					d = II(d, a, b, c, x[k+7],  S42, 0x432AFF97);
					c = II(c, d, a, b, x[k+14], S43, 0xAB9423A7);
					b = II(b, c, d, a, x[k+5],  S44, 0xFC93A039);
					a = II(a, b, c, d, x[k+12], S41, 0x655B59C3);
					d = II(d, a, b, c, x[k+3],  S42, 0x8F0CCC92);
					c = II(c, d, a, b, x[k+10], S43, 0xFFEFF47D);
					b = II(b, c, d, a, x[k+1],  S44, 0x85845DD1);
					a = II(a, b, c, d, x[k+8],  S41, 0x6FA87E4F);
					d = II(d, a, b, c, x[k+15], S42, 0xFE2CE6E0);
					c = II(c, d, a, b, x[k+6],  S43, 0xA3014314);
					b = II(b, c, d, a, x[k+13], S44, 0x4E0811A1);
					a = II(a, b, c, d, x[k+4],  S41, 0xF7537E82);
					d = II(d, a, b, c, x[k+11], S42, 0xBD3AF235);
					c = II(c, d, a, b, x[k+2],  S43, 0x2AD7D2BB);
					b = II(b, c, d, a, x[k+9],  S44, 0xEB86D391);
					a = addUnsigned(a, AA);
					b = addUnsigned(b, BB);
					c = addUnsigned(c, CC);
					d = addUnsigned(d, DD);
				}
				var tempValue = wordToHex(a) + wordToHex(b) + wordToHex(c) + wordToHex(d);
				return tempValue.toLowerCase();
			}
		});
	})(jQuery);

﻿/// <reference path="../../../lib/jquery-1.2.6.js" />
/*
	Masked Input plugin for jQuery
	Copyright (c) 2007-2009 Josh Bush (digitalbush.com)
	Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license) 
	Version: 1.2.2 (03/09/2009 22:39:06)
*/
(function($) {
	var pasteEventName = ($.browser.msie ? 'paste' : 'input') + ".mask";
	var iPhone = (window.orientation != undefined);

	$.mask = {
		//Predefined character definitions
		definitions: {
			'9': "[0-9]",
			'a': "[A-Za-z]",
			'*': "[A-Za-z0-9]"
		}
	};

	$.fn.extend({
		//Helper Function for Caret positioning
		caret: function(begin, end) {
			if (this.length == 0) return;
			if (typeof begin == 'number') {
				end = (typeof end == 'number') ? end : begin;
				return this.each(function() {
					if (this.setSelectionRange) {
						this.focus();
						this.setSelectionRange(begin, end);
					} else if (this.createTextRange) {
						var range = this.createTextRange();
						range.collapse(true);
						range.moveEnd('character', end);
						range.moveStart('character', begin);
						range.select();
					}
				});
			} else {
				if (this[0].setSelectionRange) {
					begin = this[0].selectionStart;
					end = this[0].selectionEnd;
				} else if (document.selection && document.selection.createRange) {
					var range = document.selection.createRange();
					begin = 0 - range.duplicate().moveStart('character', -100000);
					end = begin + range.text.length;
				}
				return { begin: begin, end: end };
			}
		},
		unmask: function() { return this.trigger("unmask"); },
		mask: function(mask, settings) {
			if (!mask && this.length > 0) {
				var input = $(this[0]);
				var tests = input.data("tests");
				return $.map(input.data("buffer"), function(c, i) {
					return tests[i] ? c : null;
				}).join('');
			}
			settings = $.extend({
				placeholder: "_",
				completed: null
			}, settings);

			var defs = $.mask.definitions;
			var tests = [];
			var partialPosition = mask.length;
			var firstNonMaskPos = null;
			var len = mask.length;

			$.each(mask.split(""), function(i, c) {
				if (c == '?') {
					len--;
					partialPosition = i;
				} else if (defs[c]) {
					tests.push(new RegExp(defs[c]));
					if(firstNonMaskPos==null)
						firstNonMaskPos =  tests.length - 1;
				} else {
					tests.push(null);
				}
			});

			return this.each(function() {
				var input = $(this);
				var buffer = $.map(mask.split(""), function(c, i) { if (c != '?') return defs[c] ? settings.placeholder : c });
				var ignore = false;  			//Variable for ignoring control keys
				var focusText = input.val();

				input.data("buffer", buffer).data("tests", tests);

				function seekNext(pos) {
					while (++pos <= len && !tests[pos]);
					return pos;
				};

				function shiftL(pos) {
					while (!tests[pos] && --pos >= 0);
					for (var i = pos; i < len; i++) {
						if (tests[i]) {
							buffer[i] = settings.placeholder;
							var j = seekNext(i);
							if (j < len && tests[i].test(buffer[j])) {
								buffer[i] = buffer[j];
							} else
								break;
						}
					}
					writeBuffer();
					input.caret(Math.max(firstNonMaskPos, pos));
				};

				function shiftR(pos) {
					for (var i = pos, c = settings.placeholder; i < len; i++) {
						if (tests[i]) {
							var j = seekNext(i);
							var t = buffer[i];
							buffer[i] = c;
							if (j < len && tests[j].test(t))
								c = t;
							else
								break;
						}
					}
				};

				function keydownEvent(e) {
					var pos = $(this).caret();
					var k = e.keyCode;
					ignore = (k < 16 || (k > 16 && k < 32) || (k > 32 && k < 41));

					//delete selection before proceeding
					if ((pos.begin - pos.end) != 0 && (!ignore || k == 8 || k == 46))
						clearBuffer(pos.begin, pos.end);

					//backspace, delete, and escape get special treatment
					if (k == 8 || k == 46 || (iPhone && k == 127)) {//backspace/delete
						shiftL(pos.begin + (k == 46 ? 0 : -1));
						return false;
					} else if (k == 27) {//escape
						input.val(focusText);
						input.caret(0, checkVal());
						return false;
					}
				};

				function keypressEvent(e) {
					if (ignore) {
						ignore = false;
						//Fixes Mac FF bug on backspace
						return (e.keyCode == 8) ? false : null;
					}
					e = e || window.event;
					var k = e.charCode || e.keyCode || e.which;
					var pos = $(this).caret();

					if (e.ctrlKey || e.altKey || e.metaKey) {//Ignore
						return true;
					} else if ((k >= 32 && k <= 125) || k > 186) {//typeable characters
						var p = seekNext(pos.begin - 1);
						if (p < len) {
							var c = String.fromCharCode(k);
							if (tests[p].test(c)) {
								shiftR(p);
								buffer[p] = c;
								writeBuffer();
								var next = seekNext(p);
								$(this).caret(next);
								if (settings.completed && next == len)
									settings.completed.call(input);
							}
						}
					}
					return false;
				};

				function clearBuffer(start, end) {
					for (var i = start; i < end && i < len; i++) {
						if (tests[i])
							buffer[i] = settings.placeholder;
					}
				};

				function writeBuffer() { return input.val(buffer.join('')).val(); };

				function checkVal(allow) {
					//try to place characters where they belong
					var test = input.val();
					var lastMatch = -1;
					for (var i = 0, pos = 0; i < len; i++) {
						if (tests[i]) {
							buffer[i] = settings.placeholder;
							while (pos++ < test.length) {
								var c = test.charAt(pos - 1);
								if (tests[i].test(c)) {
									buffer[i] = c;
									lastMatch = i;
									break;
								}
							}
							if (pos > test.length)
								break;
						} else if (buffer[i] == test[pos] && i!=partialPosition) {
							pos++;
							lastMatch = i;
						} 
					}
					if (!allow && lastMatch + 1 < partialPosition) {
						input.val("");
						clearBuffer(0, len);
					} else if (allow || lastMatch + 1 >= partialPosition) {
						writeBuffer();
						if (!allow) input.val(input.val().substring(0, lastMatch + 1));
					}
					return (partialPosition ? i : firstNonMaskPos);
				};

				if (!input.attr("readonly"))
					input
					.one("unmask", function() {
						input
							.unbind(".mask")
							.removeData("buffer")
							.removeData("tests");
					})
					.bind("focus.mask", function() {
						focusText = input.val();
						var pos = checkVal();
						writeBuffer();
						setTimeout(function() {
							if (pos == mask.length)
								input.caret(0, pos);
							else
								input.caret(pos);
						}, 0);
					})
					.bind("blur.mask", function() {
						checkVal();
						if (input.val() != focusText)
							input.change();
					})
					.bind("keydown.mask", keydownEvent)
					.bind("keypress.mask", keypressEvent)
					.bind(pasteEventName, function() {
						setTimeout(function() { input.caret(checkVal(true)); }, 0);
					});

				checkVal(); //Perform initial check for existing values
			});
		}
	});
})(jQuery);
/**
 * TableDnD plug-in for JQuery, allows you to drag and drop table rows
 * You can set up various options to control how the system will work
 * Copyright (c) Denis Howlett <denish@isocra.com>
 * Licensed like jQuery, see http://docs.jquery.com/License.
 *
 * Configuration options:
 * 
 * onDragStyle
 *     This is the style that is assigned to the row during drag. There are limitations to the styles that can be
 *     associated with a row (such as you can't assign a border--well you can, but it won't be
 *     displayed). (So instead consider using onDragClass.) The CSS style to apply is specified as
 *     a map (as used in the jQuery css(...) function).
 * onDropStyle
 *     This is the style that is assigned to the row when it is dropped. As for onDragStyle, there are limitations
 *     to what you can do. Also this replaces the original style, so again consider using onDragClass which
 *     is simply added and then removed on drop.
 * onDragClass
 *     This class is added for the duration of the drag and then removed when the row is dropped. It is more
 *     flexible than using onDragStyle since it can be inherited by the row cells and other content. The default
 *     is class is tDnD_whileDrag. So to use the default, simply customise this CSS class in your
 *     stylesheet.
 * onDrop
 *     Pass a function that will be called when the row is dropped. The function takes 2 parameters: the table
 *     and the row that was dropped. You can work out the new order of the rows by using
 *     table.rows.
 * onDragStart
 *     Pass a function that will be called when the user starts dragging. The function takes 2 parameters: the
 *     table and the row which the user has started to drag.
 * onAllowDrop
 *     Pass a function that will be called as a row is over another row. If the function returns true, allow 
 *     dropping on that row, otherwise not. The function takes 2 parameters: the dragged row and the row under
 *     the cursor. It returns a boolean: true allows the drop, false doesn't allow it.
 * scrollAmount
 *     This is the number of pixels to scroll if the user moves the mouse cursor to the top or bottom of the
 *     window. The page should automatically scroll up or down as appropriate (tested in IE6, IE7, Safari, FF2,
 *     FF3 beta
 * dragHandle
 *     This is the name of a class that you assign to one or more cells in each row that is draggable. If you
 *     specify this class, then you are responsible for setting cursor: move in the CSS and only these cells
 *     will have the drag behaviour. If you do not specify a dragHandle, then you get the old behaviour where
 *     the whole row is draggable.
 * 
 * Other ways to control behaviour:
 *
 * Add class="nodrop" to any rows for which you don't want to allow dropping, and class="nodrag" to any rows
 * that you don't want to be draggable.
 *
 * Inside the onDrop method you can also call $.tableDnD.serialize() this returns a string of the form
 * <tableID>[]=<rowID1>&<tableID>[]=<rowID2> so that you can send this back to the server. The table must have
 * an ID as must all the rows.
 *
 * Other methods:
 *
 * $("...").tableDnDUpdate() 
 * Will update all the matching tables, that is it will reapply the mousedown method to the rows (or handle cells).
 * This is useful if you have updated the table rows using Ajax and you want to make the table draggable again.
 * The table maintains the original configuration (so you don't have to specify it again).
 *
 * $("...").tableDnDSerialize()
 * Will serialize and return the serialized string as above, but for each of the matching tables--so it can be
 * called from anywhere and isn't dependent on the currentTable being set up correctly before calling
 *
 * Known problems:
 * - Auto-scoll has some problems with IE7  (it scrolls even when it shouldn't), work-around: set scrollAmount to 0
 * 
 * Version 0.2: 2008-02-20 First public version
 * Version 0.3: 2008-02-07 Added onDragStart option
 *                         Made the scroll amount configurable (default is 5 as before)
 * Version 0.4: 2008-03-15 Changed the noDrag/noDrop attributes to nodrag/nodrop classes
 *                         Added onAllowDrop to control dropping
 *                         Fixed a bug which meant that you couldn't set the scroll amount in both directions
 *                         Added serialize method
 * Version 0.5: 2008-05-16 Changed so that if you specify a dragHandle class it doesn't make the whole row
 *                         draggable
 *                         Improved the serialize method to use a default (and settable) regular expression.
 *                         Added tableDnDupate() and tableDnDSerialize() to be called when you are outside the table
 */
jQuery.tableDnD = {
    /** Keep hold of the current table being dragged */
    currentTable : null,
    /** Keep hold of the current drag object if any */
    dragObject: null,
    /** The current mouse offset */
    mouseOffset: null,
    /** Remember the old value of Y so that we don't do too much processing */
    oldY: 0,

    /** Actually build the structure */
    build: function(options) {
        // Set up the defaults if any

        this.each(function() {
            // This is bound to each matching table, set up the defaults and override with user options
            this.tableDnDConfig = jQuery.extend({
                onDragStyle: null,
                onDropStyle: null,
				// Add in the default class for whileDragging
				onDragClass: "tDnD_whileDrag",
                onDrop: null,
                onDragStart: null,
                scrollAmount: 5,
				serializeRegexp: /[^\-]*$/, // The regular expression to use to trim row IDs
				serializeParamName: null, // If you want to specify another parameter name instead of the table ID
                dragHandle: null // If you give the name of a class here, then only Cells with this class will be draggable
            }, options || {});
            // Now make the rows draggable
            jQuery.tableDnD.makeDraggable(this);
        });

        // Now we need to capture the mouse up and mouse move event
        // We can use bind so that we don't interfere with other event handlers
        jQuery(document)
            .bind('mousemove', jQuery.tableDnD.mousemove)
            .bind('mouseup', jQuery.tableDnD.mouseup);

        // Don't break the chain
        return this;
    },

    /** This function makes all the rows on the table draggable apart from those marked as "NoDrag" */
    makeDraggable: function(table) {
        var config = table.tableDnDConfig;
		if (table.tableDnDConfig.dragHandle) {
			// We only need to add the event to the specified cells
			var cells = jQuery("td."+table.tableDnDConfig.dragHandle, table);
			cells.each(function() {
				// The cell is bound to "this"
                jQuery(this).mousedown(function(ev) {
                    jQuery.tableDnD.dragObject = this.parentNode;
                    jQuery.tableDnD.currentTable = table;
                    jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
                    if (config.onDragStart) {
                        // Call the onDrop method if there is one
                        config.onDragStart(table, this);
                    }
                    return false;
                });
			})
		} else {
			// For backwards compatibility, we add the event to the whole row
	        var rows = jQuery("tr", table); // get all the rows as a wrapped set
	        rows.each(function() {
				// Iterate through each row, the row is bound to "this"
				var row = jQuery(this);
				if (! row.hasClass("nodrag")) {
	                row.mousedown(function(ev) {
	                    if (ev.target.tagName == "TD") {
	                        jQuery.tableDnD.dragObject = this;
	                        jQuery.tableDnD.currentTable = table;
	                        jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
	                        if (config.onDragStart) {
	                            // Call the onDrop method if there is one
	                            config.onDragStart(table, this);
	                        }
	                        return false;
	                    }
	                }).css("cursor", "move"); // Store the tableDnD object
				}
			});
		}
	},

	updateTables: function() {
		this.each(function() {
			// this is now bound to each matching table
			if (this.tableDnDConfig) {
				jQuery.tableDnD.makeDraggable(this);
			}
		})
	},

    /** Get the mouse coordinates from the event (allowing for browser differences) */
    mouseCoords: function(ev){
        if(ev.pageX || ev.pageY){
            return {x:ev.pageX, y:ev.pageY};
        }
        return {
            x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
            y:ev.clientY + document.body.scrollTop  - document.body.clientTop
        };
    },

    /** Given a target element and a mouse event, get the mouse offset from that element.
        To do this we need the element's position and the mouse position */
    getMouseOffset: function(target, ev) {
        ev = ev || window.event;

        var docPos    = this.getPosition(target);
        var mousePos  = this.mouseCoords(ev);
        return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
    },

    /** Get the position of an element by going up the DOM tree and adding up all the offsets */
    getPosition: function(e){
        var left = 0;
        var top  = 0;
        /** Safari fix -- thanks to Luis Chato for this! */
        if (e.offsetHeight == 0) {
            /** Safari 2 doesn't correctly grab the offsetTop of a table row
            this is detailed here:
            http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari/
            the solution is likewise noted there, grab the offset of a table cell in the row - the firstChild.
            note that firefox will return a text node as a first child, so designing a more thorough
            solution may need to take that into account, for now this seems to work in firefox, safari, ie */
            e = e.firstChild; // a table cell
        }

        while (e.offsetParent){
            left += e.offsetLeft;
            top  += e.offsetTop;
            e     = e.offsetParent;
        }

        left += e.offsetLeft;
        top  += e.offsetTop;

        return {x:left, y:top};
    },

    mousemove: function(ev) {
        if (jQuery.tableDnD.dragObject == null) {
            return;
        }

        var dragObj = jQuery(jQuery.tableDnD.dragObject);
        var config = jQuery.tableDnD.currentTable.tableDnDConfig;
        var mousePos = jQuery.tableDnD.mouseCoords(ev);
        var y = mousePos.y - jQuery.tableDnD.mouseOffset.y;
        //auto scroll the window
	    var yOffset = window.pageYOffset;
	 	if (document.all) {
	        // Windows version
	        //yOffset=document.body.scrollTop;
	        if (typeof document.compatMode != 'undefined' &&
	             document.compatMode != 'BackCompat') {
	           yOffset = document.documentElement.scrollTop;
	        }
	        else if (typeof document.body != 'undefined') {
	           yOffset=document.body.scrollTop;
	        }

	    }
		    
		if (mousePos.y-yOffset < config.scrollAmount) {
	    	window.scrollBy(0, -config.scrollAmount);
	    } else {
            var windowHeight = window.innerHeight ? window.innerHeight
                    : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
            if (windowHeight-(mousePos.y-yOffset) < config.scrollAmount) {
                window.scrollBy(0, config.scrollAmount);
            }
        }


        if (y != jQuery.tableDnD.oldY) {
            // work out if we're going up or down...
            var movingDown = y > jQuery.tableDnD.oldY;
            // update the old value
            jQuery.tableDnD.oldY = y;
            // update the style to show we're dragging
			if (config.onDragClass) {
				dragObj.addClass(config.onDragClass);
			} else {
	            dragObj.css(config.onDragStyle);
			}
            // If we're over a row then move the dragged row to there so that the user sees the
            // effect dynamically
            var currentRow = jQuery.tableDnD.findDropTargetRow(dragObj, y);
            if (currentRow) {
                // TODO worry about what happens when there are multiple TBODIES
                if (movingDown && jQuery.tableDnD.dragObject != currentRow) {
                    jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow.nextSibling);
                } else if (! movingDown && jQuery.tableDnD.dragObject != currentRow) {
                    jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow);
                }
            }
        }

        return false;
    },

    /** We're only worried about the y position really, because we can only move rows up and down */
    findDropTargetRow: function(draggedRow, y) {
        var rows = jQuery.tableDnD.currentTable.rows;
        for (var i=0; i<rows.length; i++) {
            var row = rows[i];
            var rowY    = this.getPosition(row).y;
            var rowHeight = parseInt(row.offsetHeight)/2;
            if (row.offsetHeight == 0) {
                rowY = this.getPosition(row.firstChild).y;
                rowHeight = parseInt(row.firstChild.offsetHeight)/2;
            }
            // Because we always have to insert before, we need to offset the height a bit
            if ((y > rowY - rowHeight) && (y < (rowY + rowHeight))) {
                // that's the row we're over
				// If it's the same as the current row, ignore it
				if (row == draggedRow) {return null;}
                var config = jQuery.tableDnD.currentTable.tableDnDConfig;
                if (config.onAllowDrop) {
                    if (config.onAllowDrop(draggedRow, row)) {
                        return row;
                    } else {
                        return null;
                    }
                } else {
					// If a row has nodrop class, then don't allow dropping (inspired by John Tarr and Famic)
                    var nodrop = jQuery(row).hasClass("nodrop");
                    if (! nodrop) {
                        return row;
                    } else {
                        return null;
                    }
                }
                return row;
            }
        }
        return null;
    },

    mouseup: function(e) {
        if (jQuery.tableDnD.currentTable && jQuery.tableDnD.dragObject) {
            var droppedRow = jQuery.tableDnD.dragObject;
            var config = jQuery.tableDnD.currentTable.tableDnDConfig;
            // If we have a dragObject, then we need to release it,
            // The row will already have been moved to the right place so we just reset stuff
			if (config.onDragClass) {
	            jQuery(droppedRow).removeClass(config.onDragClass);
			} else {
	            jQuery(droppedRow).css(config.onDropStyle);
			}
            jQuery.tableDnD.dragObject   = null;
            if (config.onDrop) {
                // Call the onDrop method if there is one
                config.onDrop(jQuery.tableDnD.currentTable, droppedRow);
            }
            jQuery.tableDnD.currentTable = null; // let go of the table too
        }
    },

    serialize: function() {
        if (jQuery.tableDnD.currentTable) {
            return jQuery.tableDnD.serializeTable(jQuery.tableDnD.currentTable);
        } else {
            return "Error: No Table id set, you need to set an id on your table and every row";
        }
    },

	serializeTable: function(table) {
        var result = "";
        var tableId = table.id;
        var rows = table.rows;
        for (var i=0; i<rows.length; i++) {
            if (result.length > 0) result += "&";
            var rowId = rows[i].id;
            if (rowId && rowId && table.tableDnDConfig && table.tableDnDConfig.serializeRegexp) {
                rowId = rowId.match(table.tableDnDConfig.serializeRegexp)[0];
            }

            result += tableId + '[]=' + rowId;
        }
        return result;
	},

	serializeTables: function() {
        var result = "";
        this.each(function() {
			// this is now bound to each matching table
			result += jQuery.tableDnD.serializeTable(this);
		});
        return result;
    }

}

jQuery.fn.extend(
	{
		tableDnD : jQuery.tableDnD.build,
		tableDnDUpdate : jQuery.tableDnD.updateTables,
		tableDnDSerialize: jQuery.tableDnD.serializeTables
	}
);

/**
 * WYSIWYG - jQuery plugin 0.4
 *
 * Copyright (c) 2008 Juan M Martinez
 * http://plugins.jquery.com/project/jWYSIWYG
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * $Id: $
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(k($){$.1k.F=k(){h a=5[0];7(a.1B.19()==\'1l\')q a.1a.F;t q $(5)};$.1k.1m=k(){h a=5[0];7(a.1a.F.1n)q a.1a.F.1n.1C().X;t q a.1a.Y().I()};$.1k.J=k(a){7(w.v>0&&w[0].Z==1o){h b=w[0].I();h c=[];K(h i=1;i<w.v;i++)c[i-1]=w[i];7(b L x){q 5.1D(k(){$.10(5,\'J\').11();x[b].1E(5,c)})}t q 5}h d={};7(a&&a.y){h d=a.y;2F a.y}h a=$.P({B:\'<\'+\'?1F 2G="1.0" 2H="1G-8"?\'+\'><!2I B 2J "-//2K//1H 2L 1.0 2M//2N" "12://1I.1J.1K/2O/1L/1H/1L-2P.2Q"><B 2R="12://1I.1J.1K/2S/2T" 1F:2U="2V"><1M><2W 12-2X="2Y-2Z" 30="X/B; 31=1G-8">1N</1M><M>1O</M></B>\',n:{},32:9,1b:l,1P:l,1Q:l,y:{},Q:{}},a);$.P(a.Q,x.1R);$.P(a.y,x.1S);K(h e L d){7(e L a.y)$.P(a.y[e],d[e]);t a.y[e]=d[e]}q 5.1D(k(){x(5,a)})};k x(a,b){q 5 33 x?5.1T(a,b):34 x(a,b)}$.P(x,{R:k(a,b){h c=$.10(5,\'J\');7(c.Z==x&&a&&a.v>0){7(b){c.m.z(\'R\',9,\'#1U#\');h d=c.1V(\'1W\',\'1X\',\'#1U#\');7(d){d.1X=a;K(h e L b){d.35(e,b[e])}}}t{c.m.z(\'R\',9,a)}}},14:k(a){h b=$.10(5,\'J\');7(b.Z==x&&a&&a.v>0){h c=$(b.C).1m();7(c.v>0){b.m.z(\'1p\',9,[]);b.m.z(\'14\',9,a)}t 7(b.o.Q.15)1Y(b.o.Q.15)}},1Z:k(){h a=$.10(5,\'J\');a.1c(\'\');a.N()},1R:{15:\'20 36 X 37 38 39 22\'},1S:{23:{j:l,p:[\'b\',\'3a\'],n:{3b:\'23\'}},24:{j:l,p:[\'i\',\'3c\'],n:{3d:\'24\'}},3e:{j:9,p:[\'s\',\'3f\'],n:{25:\'3g-3h\'}},26:{j:9,p:[\'u\'],n:{25:\'26\'}},3i:{j:9,A:l},3j:{j:9,n:{1d:\'3k\'}},3l:{j:9,p:[\'27\'],n:{1d:\'27\'}},3m:{j:9,n:{1d:\'3n\'}},3o:{j:9,n:{1d:\'3p\'}},3q:{j:9,A:l},3r:{j:9},3s:{j:9},3t:{j:9,A:l},3u:{j:9,p:[\'3v\']},3w:{j:9,p:[\'3x\']},3y:{j:9,A:l},3z:{j:9},3A:{j:9},3B:{j:9,A:l},3C:{j:9,p:[\'3D\']},3E:{j:9,p:[\'1q\']},3F:{j:9,p:[\'3G\']},3H:{A:l},14:{j:l,17:k(){h a=$(5.C).1m();7(a.v>0){7($.r.D)5.m.z(\'14\',l,S);t{h b=28(\'29\',\'12://\');7(b&&b.v>0){5.m.z(\'1p\',9,[]);5.m.z(\'14\',9,b)}}}t 7(5.o.Q.15)1Y(5.o.Q.15)},p:[\'a\']},R:{j:l,17:k(){7($.r.D)5.m.z(\'R\',l,S);t{h a=28(\'29\',\'12://\');7(a&&a.v>0)5.m.z(\'R\',9,a)}},p:[\'1W\']},3I:{A:l},3J:{j:l&&$.r.T,G:\'U\',E:\'1r\',w:[\'U\'],p:[\'U\']},3K:{j:l&&$.r.T,G:\'V\',E:\'1r\',w:[\'V\'],p:[\'V\']},3L:{j:l&&$.r.T,G:\'W\',E:\'1r\',w:[\'W\'],p:[\'W\']},U:{j:l&&!($.r.T),G:\'U\',E:\'1s\',w:[\'1t 1\'],p:[\'U\']},V:{j:l&&!($.r.T),G:\'V\',E:\'1s\',w:[\'1t 2\'],p:[\'V\']},W:{j:l&&!($.r.T),G:\'W\',E:\'1s\',w:[\'1t 3\'],p:[\'W\']},3M:{j:9,A:l},3N:{j:9},3O:{j:9},3P:{j:9},3Q:{A:l&&!($.r.D)},3R:{j:l&&!($.r.D),p:[\'3S\']},3T:{j:l&&!($.r.D),p:[\'3U\']},3V:{A:l},B:{j:9,17:k(){7(5.1e){5.1c($(5.H).2a());$(5.H).2b()}t{5.N();$(5.H).3W()}5.1e=!(5.1e)}},2c:{j:l,17:k(){5.m.z(\'2c\',9,[]);5.m.z(\'1p\',9,[])}}}});$.P(x.3X,{H:S,o:{},1u:S,C:S,1T:k(a,b){h c=5;5.C=a;5.o=b||{};$.10(a,\'J\',5);h d=a.1v||a.3Y;h e=a.2d||a.3Z;7(a.1B.19()==\'40\'){5.H=a;7(d==0&&a.2e)d=(a.2e*8)+21;7(e==0&&a.2f)e=(a.2f*16)+16;h f=5.C=$(\'<1l></1l>\').n({41:(e-6).I()+\'1f\',1v:(d-8).I()+\'1f\'}).2g(\'2h\',$(a).2g(\'2h\')+\'42\');7($.r.D){5.C.n(\'2d\',(e).I()+\'1f\')}}h g=5.O=$(\'<1q></1q>\').18(\'O\');5.2i();5.1u=$(\'<1g></1g>\').n({1v:(d>0)?(d).I()+\'1f\':\'43%\'}).18(\'J\').1h(g).1h($(\'<1g><!-- --></1g>\').n({1Z:\'44\'})).1h(f);$(a).2b().45(5.1u);5.1e=9;5.46=e-8;5.1w=$(a).X();5.2j();7(5.1w.v==0)5.1c(\'\');7(5.o.1b)$(\'47\').48(k(){c.N()})},2j:k(){h c=5;h d=\'\';7(5.o.n&&5.o.n.Z==1o)d=\'<22 49="4a" 4b="X/n" 4c="4d" 4e="\'+5.o.n+\'" />\';5.m=$(5.C).F();5.1i=9;2k{5.m.11=\'2l\';5.1i=l}2m(e){$(5.m).1x(k(){c.11()})}5.m.4f();5.m.4g(5.o.B.2n(/1O/,5.1w).2n(/1N/,d));5.m.4h();5.m.4i=\'l\';7($.r.D){2o(k(){$(c.m.M).n(\'4j\',\'4k\')},0)}$(5.m).4l(k(a){c.2p(a.2q?a.2q:a.4m)});$(5.H).1x(k(){$(c.m.M).1x()});7(5.o.1b){$(5.m).2r(k(){c.N()}).2s(k(){c.N()})}7(5.o.n){2o(k(){7(c.o.n.Z==1o){}t $(c.m).1y(\'M\').n(c.o.n)},0)}$(5.m).2r(k(a){7($.r.D&&c.o.1Q&&a.4n==13){h b=c.2t();b.4o(\'<2u />\');b.4p(9);b.20();q 9}})},11:k(){7(!(5.1i)){2k{5.m.11=\'2l\';5.1i=l}2m(e){}}},Y:k(){q(2v.Y)?2v.Y():F.1n},2t:k(){h a=5.Y();7(!(a))q S;q(a.4q>0)?a.4r(0):a.1C()},2w:k(){q $($(5.C).F()).1y(\'M\').B()},1c:k(a){$($(5.C).F()).1y(\'M\').B(a)},N:k(){7(5.H){h a=5.2w();7(5.o.1P)a=(a.1z(-4)==\'<2u>\')?a.1z(0,a.v-4):a;$(5.H).2a(a)}},2x:k(a,b,c,d){h e=5;h b=b||[];$(\'<1j></1j>\').1h($(\'<a><!-- --></a>\').18(c||a)).2s(k(){7(d)d.1E(e);t e.m.z(a,9,b);7(e.o.1b)e.N()}).2y(5.O)},2z:k(){$(\'<1j 4s="A"></1j>\').2y(5.O)},2i:k(){K(h a L 5.o.y){h b=5.o.y[a];7(b.A){7(b.j!==9)5.2z()}t 7(b.j){5.2x(b.E||a,b.w||[],b.G||b.E||a||\'2A\',b.17)}}},2p:k(a){K(h b L 5.o.y){h c=5.o.y[b];h d=c.G||c.E||b||\'2A\';$(\'.\'+d,5.O).4t(\'1A\');7(c.p){h e=a;2B{7(e.2C!=1)2D;7($.4u(e.4v.19(),c.p)!=-1)$(\'.\'+d,5.O).18(\'1A\')}2E(e=e.4w)}7(c.n){h e=$(a);2B{7(e[0].2C!=1)2D;K(h f L c.n)7(e.n(f).I().19()==c.n[f])$(\'.\'+d,5.O).18(\'1A\')}2E(e=e.4x())}}},1V:k(a,b,c){h d=5.m.4y(a);K(h i=0;i<d.v;i++){h e=d[i].4z(b);7($.r.D){e=e.1z(e.v-c.v)}7(e==c)q d[i]}q 9}})})(4A);',62,285,'|||||this||if||false||||||||var||visible|function|true|editorDoc|css|options|tags|return|browser||else||length|arguments|Wysiwyg|controls|execCommand|separator|html|editor|msie|command|document|className|original|toString|wysiwyg|for|in|body|saveContent|panel|extend|messages|insertImage|null|mozilla|h1|h2|h3|text|getSelection|constructor|data|designMode|http||createLink|nonSelection||exec|addClass|toLowerCase|contentWindow|autoSave|setContent|textAlign|viewHTML|px|div|append|editorDoc_designMode|li|fn|iframe|documentSelection|selection|String|unlink|ul|heading|formatBlock|Heading|element|width|initialContent|focus|find|substr|active|nodeName|createRange|each|apply|xml|UTF|DTD|www|w3|org|xhtml1|head|STYLE_SHEET|INITIAL_CONTENT|rmUnwantedBr|brIE|MSGS_EN|TOOLBAR|init|jwysiwyg|getElementByAttributeValue|img|src|alert|clear|select||link|bold|italic|textDecoration|underline|center|prompt|URL|val|hide|removeFormat|height|cols|rows|attr|id|appendControls|initFrame|try|on|catch|replace|setTimeout|checkTargets|target|keydown|mousedown|getRange|br|window|getContent|appendMenu|appendTo|appendMenuSeparator|empty|do|nodeType|break|while|delete|version|encoding|DOCTYPE|PUBLIC|W3C|XHTML|Strict|EN|TR|strict|dtd|xmlns|1999|xhtml|lang|en|meta|equiv|Content|Type|content|charset|debug|instanceof|new|setAttribute|the|you|wish|to|strong|fontWeight|em|fontStyle|strikeThrough|strike|line|through|separator00|justifyLeft|left|justifyCenter|justifyRight|right|justifyFull|justify|separator01|indent|outdent|separator02|subscript|sub|superscript|sup|separator03|undo|redo|separator04|insertOrderedList|ol|insertUnorderedList|insertHorizontalRule|hr|separator05|separator06|h1mozilla|h2mozilla|h3mozilla|separator07|cut|copy|paste|separator08|increaseFontSize|big|decreaseFontSize|small|separator09|show|prototype|clientWidth|clientHeight|textarea|minHeight|IFrame|100|both|before|initialHeight|form|submit|rel|stylesheet|type|media|screen|href|open|write|close|contentEditable|border|none|click|srcElement|keyCode|pasteHTML|collapse|rangeCount|getRangeAt|class|removeClass|inArray|tagName|parentNode|parent|getElementsByTagName|getAttribute|jQuery'.split('|'),0,{}))
/**
 * este metodo nos permite habrir en un pop-up un enlace de forma secilla
 * basicamente funciona agregando al atributo rel las propiedades del popup
 * rel="openinpopup_newresource:width=400,height=400"
 * luego se invoca desde jQuery
 * $('a[rel*=openinpopup]').popup();
 * 
 */
$.fn.popup = function() {

    function clickHandler(e) {
        // si el usuario ha utilizado una tecla de control
        // no hacemos nada
        if (e.ctrlKey || e.shiftKey || e.metaKey)
            return;

        var rel = this.rel;
        var brokenstring = rel.split(':');

        // abrimos la ventana
        var features = 'scrollbars=yes,resizable=yes,' + brokenstring[1];
        var winName = brokenstring[0];
        var w = window.open(this.href,winName,features);
        
        if (w && !w.closed) {
            // si efectivamente hemos logrado abrirla
            // la ponemos en foco
            w.focus();
            // y cancelamos el comportamiento por defecto
            // del enlace
            e.preventDefault();
        }
    }

    this
        .unbind()
        .filter('a[href]') // que no se nos cuele algo que no sea un enlace
        .bind('click', clickHandler);

    return this; // permitimos concatenabilidad

}
$.fn.ajax_action = function() {

    function clickHandler(e) {
        // si el usuario ha utilizado una tecla de control
        // no hacemos nada
        if (e.ctrlKey || e.shiftKey || e.metaKey)
            return;

        //var rel = this.rel;
        var action = this.href;

        if(window.confirm("Confirmar Accion / Confirm Action")){
            $.get(action,function(){
                alert('proceso realizado');
            });
        }

        // cancelamos el comportamiento natural del enlace
        e.preventDefault();
    }

    this
        .filter('a[href]') // que no se nos cuele algo que no sea un enlace
        .bind('click', clickHandler);

    return this; // permitimos concatenabilidad

}
/**
 * este metodo para jQuery es basicamente un cargador ayax de contenido
 * de forma dinamica.
 * uso comun:
 * $('a[rel*=orioncontentload]').OrionContentLoad(function(){.. aca ejecuto algo despues ..});
 * <a id="link_contacto" href="/Contacto" rel="orioncontentload" target="content">
 * el enlace sera cargado en el contenedor definido por el target del enlace
 *
 * autor: Oscar Añón
 * copyright Orion Framework 2009
 */

function OrionContentLoad(url,target,callback,data,history){
    //var target = 'content';
    //alert(history);

    if(typeof history == 'undefined')
        history = 1;

    if(typeof data == 'undefined'){
        data = {
            orionload : 1
        };
    }

    // dimensiones del contenedor
    var h = $('#' + target).height();
    var w = $('#' + target).width();

    //        if(h > 700){
    //            h = 700;
    //            $('#' + target).html('');
    //            $('#' + target).height('700px');
    //        }

    var t = (h / 2);

    //h = 0;
    var style = 'position:absolute;top:0px;vertical-align:middle;height:'+h+'px;width:'+w+'px;';
    style += 'z-index:200;background-color:#FFFFFF;filter:alpha(opacity=75);-moz-opacity:0.75;opacity:0.75;';
    var cargando = '<div align="center" style="'+style+'">';
    style = 'position:relative;top:'+t+'px;vertical-align:middle;';
    cargando += '<img style="'+style+'" align="middle" border="0" src="/Orion/factory/NebulaTools/resources/cargando.gif" />';
    cargando += '</div>';
    var position = $('#' + target).css('position');

    // fix de la posicion del div contenedor (todo div contenedor tiene que tener posicion)
    if(position == 'static')
        $('#' + target).css('position', 'relative');
    $('#' + target).prepend(cargando);
    $('#' + target).unbind('css');
    //$('#' + target).load(url, data, callback);

    // agregado para manejar el history load
    //alert(orion.history.main);
    if(target == orion.history.main && history == 1){//content

        // history2 (test)
        if(orion.history.mode == 'test'){
            orion.xhr.load(url, target, callback, data);
            return true;
        }

        var hash2 = url.replace(/^.*#/, '').replace(/\?.*/, '').replace('http', '', "gi");
        hash2 = hash2.replace('/', '', "gi").replace(':', '', "gi").replace('.', '', "gi");
        var hashtest = {};
        var parametros = '';
        var md5params = '';

        // IE8 patch
        hash2 = hash2.replace('/', '', "gi").replace('/', '', "gi").replace('/', '', "gi").replace('/', '', "gi").replace('.', '', "gi");
        hash2 = hash2.replace('.', '');
        //alert(hash2);

        if(url.match(/\?/)){
            parametros = url.replace(/^.*\?/, '');
            md5params = jQuery.md5(parametros);
            hash2 = hash2 + '_' + md5params;
        }

        eval('hashtest = "'+hash2+'" in historyobj? historyobj.'+hash2+' : ""');
        if(typeof hashtest.target !== 'undefined'){
            if(typeof history == 'undefined'){
                //alert('hashtest: ' + history);
                $.historyLoad(hash2);
            }else{
                $('#' + target).load(url, data, callback);
                orion.xhr.storeMap(url, target, data, callback);
            }
            //alert(hash2);
            //$.historyLoad(hash2);
            //location = '/#' + hash2;
        }else{
            //alert('undefined');
            //location = '#' + hash2;
            var historyobjactual = {
                'action' : url,
                'target' : target,
                'params' : data
            };

            //eval('historyobj.'+hash2+' = historyobjactual');
            //alert(historyobj.checkobject);
            jQuery(historyobj).attr(hash2, historyobjactual);

            // cargo otra ves la funcion para hacer el load por intermedio
            // de la funcion pageload del history
            $.historyLoad(hash2);
        }
        
    }else{
        // cargo de forma normal cualquier otra carga ajax que no sea en el
        // contenedor central
        $('#' + target).load(url, data, callback);
        orion.xhr.storeMap(url, target, data, callback);
    }

    return true;
}

$.fn.OrionContentLoad = function(callback) {

    function clickHandler(e) {
        // si el usuario ha utilizado una tecla de control
        // no hacemos nada
        if (e.ctrlKey || e.shiftKey || e.metaKey)
            return;

        //var rel = this.rel;
        var url = this.href;
        var target = this.target;

        OrionContentLoad(url,target,callback);

        // cancelamos el comportamiento natural del enlace
        e.preventDefault();
    }

    this
    .unbind()
    .filter('a[href]') // que no se nos cuele algo que no sea un enlace
    .bind('click', clickHandler);

    return this; // permitimos concatenabilidad

}

/**
 * plug_in para testear el nuevo history
 */
$.fn.OrionContentLoad_test = function(callback) {

    function clickHandler(e) {
        // si el usuario ha utilizado una tecla de control
        // no hacemos nada
        if (e.ctrlKey || e.shiftKey || e.metaKey)
            return;

        //var rel = this.rel;
        var url = this.href;
        var target = this.target ? this.target : orion.history.main;
        var data = {
            orionload : 1
        };
        // cargo de forma normal cualquier otra carga ajax que no sea en el
        // contenedor central, history2 (test)
        OrionContentLoad(url,target,callback);

        // cancelamos el comportamiento natural del enlace
        e.preventDefault();
    }

    this
    .unbind()
    .filter('a[href]') // que no se nos cuele algo que no sea un enlace
    .bind('click', clickHandler);

    return this; // permitimos concatenabilidad

}

/**
 * objeto JSON para manipular popups ajax
 * autor: Oscar Añón (nova)
 */
var orion_box_options = {
    botonera_img: '/Orion/shared/icons/32/preferences-desktop-notification.png',
    contenedor_background : '#FFFFFF',
    contenedor_top : '10%',
    contenedor_left : '30%',
    minimize: true,
    cointainerId : 'orion_box_contenedor'
}

var orion_box = {
    load : 0,
    botonera:1,
    control_minimized:0,
    options: orion_box_options,

    css_contenedor: {
        'background-attachment':'scroll',
        'background-color':orion_box_options.contenedor_background,
        'background-image':'none',
        'background-position':'0 0',
        'background-repeat':'repeat',
        'height':'600px',
        'position':'absolute',
        //'top':'200px',
        'vertical-align':'middle',
        'width':'430px',
        'z-index':'104',
        'text-align':'left',
        //'top':orion_box_options.contenedor_top,
        'left':orion_box_options.contenedor_left,
        'padding': '8px'
    },

    css_over: {
        'position': 'fixed',
        'z-index':'100',
        'top': '0px',
        'left': '0px',
        'height':'100%',
        'width':'100%',
        'background-color':'#000',
        'filter':'alpha(opacity=75)',
        '-moz-opacity': '0.75',
        'opacity': '0.75'
    },

    css_botonera: {
        //'background-image':'url('+orion_box_options.botonera_img+')'
    },

    init : function(container){

        if(typeof container == 'undefined'){
            container = 'body';
        }

        if(container != 'body'){
            container = '#' + container;
            orion_box.css_over.position = 'absolute';
            orion_box.css_contenedor.position = 'absolute';
            orion_box.css_over.height = '100%';
            orion_box.css_over.height = '100%';
            orion_box.css_over.opacity = '0.55';
        }else{
            orion_box.css_over.height = '200%';
            orion_box.css_over.opacity = '0.75';
        }
        
        var img_close = '<img alt="close" border="0" src="/Orion/shared/icons/22/window-close.png"/>';
        var img_min = '<img alt="min" border="0" src="/Orion/shared/icons/22/go-down.png"/>';
        var img_ancla = '<img alt="close" border="0" src="/Orion/shared/icons/32/go-up.png"/>';

        var div_over = '<div id="orion_box_over"></div>';
        var div_contenedor = '<div id="orion_box_contenedor" class="ui-corner-all"></div>';
        var botonera = '<div id="orion_box_botonera" style="display: none;"></div>';
        var botones =  '<a href="javascript:;" onclick="orion_box.close();">'+img_close+'</a>';
        botones += ' <a id="botonMinimizar" href="javascript:;" onclick="orion_box.minimize();">'+img_min+'</a>';

        //var div_icono = '<div style="display:none;z-index:104;position:absolute;" id="orion_box_max"><a href="javascript:;" onclick="orion_box.max();">MAX</a></div>';

        var div_icono = '<div style="display:none;z-index:104;top:130px;left:120px;position:fixed;" id="orion_box_max">';
        div_icono += '<a title="maximizar ventana" href="javascript:;" onclick="orion_box.max();">';
        div_icono += img_ancla+'</a></div>';

        if(this.load == 0){
            //alert(this.load);
            jQuery(container).append(div_over);
            jQuery(container).append(div_contenedor);
            jQuery(container).append(div_icono);
            jQuery('div#orion_box_over').css(orion_box.css_over);

            // parche IE6 (aplicar luego)
            //jQuery('div#zount_box_over').css('position','absolute');
            //jQuery('div#zount_box_over').css('height','200%');

            jQuery('div#orion_box_contenedor').css(orion_box.css_contenedor);

                // parche para la botonera, simpre se carga pero apagada
                jQuery('div#orion_box_contenedor').append(botonera);
                jQuery('div#orion_box_botonera').append(botones);
            if(orion_box.botonera == 1){
                //jQuery('div#orion_box_botonera').toggle();
                jQuery('div#orion_box_botonera').css('display', 'block');
            }

            jQuery('div#orion_box_botonera').css(orion_box.css_botonera);
            this.load = 1;
        }
    },

    /**
     * activo la botonera superior
     *
     * options es un JSON de propiedades
     * disabledMin:true (desactiva el boton de minimizado)
     * 
     */
    toolbarOn: function(options){
        if(typeof options != 'undefined'){
            if(typeof options.disabledMin != 'undefined'){
                jQuery('a#botonMinimizar').remove();
            }
        }

        //jQuery('div#orion_box_botonera').toggle();
        jQuery('div#orion_box_botonera').css('display', 'block');
        var contenedorHeight = jQuery('div#orion_box_contenedor').height();
        jQuery('div#orion_box_contenedor').height(contenedorHeight + 25);
    },

    // cargo un iframe dentro del contendor y lo apunto a un source
    iframe: function(src,width,height,container){
        if(typeof container == 'undefined'){
            container = 'body';
        }

        if(orion_box.control_minimized == 0){
            orion_box.close();
            orion_box.init(container);
            var iframe_html = '<iframe id="orion_box_iframeContent" frameborder="0" ';

            //width
            iframe_html += 'style="width: '+width+'px;';
            // height
            iframe_html += 'height: '+height+'px;" ';

            iframe_html += 'onload="" name="orion_box_iframeContent" src="'+src+'" hspace="0">';

            if(container == 'body'){
                jQuery('div#orion_box_contenedor').css('position', 'fixed');
            }else{
                height = height * 1;
                jQuery('div#' + container).height(height + 50);
            }

            jQuery('div#orion_box_contenedor').append(iframe_html);

            var margintop = height / 2;
            var marginleft = width / 2;

            if(container != 'body'){
                marginleft = (marginleft * 1) + 10;
            }
            
            var style = {
                'left': '50%',
                'top': '50%',
                'height': height+'px',
                'margin-top': '-'+margintop+'px',
                'width': width+'px',
                'margin-left': '-'+marginleft+'px'
            }

            jQuery('div#orion_box_contenedor').css(style);

        }else{//minimized
            orion_box.max();
        }

        // user defined function
        if(typeof callbackBox == 'function'){
            // ejecuto una funcion definida en el setup del sitio
            callbackBox.call();
        }

    },

    /**
     * cargo contenido ajax dentro del contendor
     * @param src URL de la llamada
     * @param width ancho de la caja
     * @param height alto de la caja
     * @param params datos GET enviados a la URL
     * @param container contenedor alternativo para contener el Box
     */
    xhr: function(src,width,height,params,container){
        containerBoxID = this.options.cointainerId;

        if(typeof container == 'undefined'){
            container = 'body';
        }

        if(orion_box.control_minimized == 0){
            orion_box.close();
            orion_box.init(container);
            //overflow-y:auto;
            jQuery('div#' + containerBoxID).css('position', 'fixed');
            jQuery('div#' + containerBoxID).css('overflow-y', 'auto');
            jQuery('div#' + containerBoxID).css('height', height + 'px');
            jQuery('div#' + containerBoxID).css('width', width + 'px');

            if(container == 'body'){
                //jQuery('div#orion_box_contenedor').css('position', 'fixed');
            }else{
                jQuery('div#' + container).height(height + 50);
            }

            if(typeof params == 'undefined' && params == null){
                params = {
                    orionload:  1,
                    modal:1
                };
            }

            params = jQuery.extend({
                'orionload':  1,
                'modal':1,
                'method':'get'
            }, params || {});


            jQuery.get(src, params, function(xhr){
                jQuery('div#' + containerBoxID).html(xhr);

                var margintop = height / 2;
                var marginleft = width / 2;

                if(container != 'body'){
                    marginleft = (marginleft * 1) + 10;
                }

                var style = {
                    'left': '50%',
                    'top': '50%',
                    'height': height+'px',
                    'margin-top': '-'+margintop+'px',
                    'width': width+'px',
                    'margin-left': '-'+marginleft+'px'
                }

                jQuery('div#' + containerBoxID).css(style);

            });

        }else{//minimized
            orion_box.max();
        }
    },

    /**
     * cargo la caja modal pero utilizo POST para enviarle parametros
     * @param src URL de la llamada
     * @param width ancho de la caja
     * @param height alto de la caja
     * @param sentdata datos POST enviados a la URL
     * @param container contenedor alternativo para contener el Box
     */
    xhrpost: function(src,width,height,sentdata,container){
        containerBoxID = this.options.cointainerId;

        if(typeof container == 'undefined'){
            container = 'body';
        }

        if(orion_box.control_minimized == 0){
            orion_box.close();
            orion_box.init(container);
            //overflow-y:auto;
            jQuery('div#' + containerBoxID).css('position', 'fixed');
            jQuery('div#' + containerBoxID).css('overflow-y', 'auto');
            jQuery('div#' + containerBoxID).css('height', height + 'px');
            jQuery('div#' + containerBoxID).css('width', width + 'px');

            if(typeof sentdata == 'undefined'){
                sentdata = {
                    orionload: 1,
                    modal: 1
                };
            }
            
            sentdata = jQuery.extend({
                'orionload': 1,
                'modal': 1,
                'method':'post'
            }, sentdata || {});

            jQuery('div#' + containerBoxID).load(src, sentdata, function(){
                var margintop = height / 2;
                var marginleft = width / 2;

                var style = {
                    'left': '50%',
                    'top': '50%',
                    'height': height+'px',
                    'margin-top': '-'+margintop+'px',
                    'width': width+'px',
                    'margin-left': '-'+marginleft+'px'
                }

                jQuery('div#' + containerBoxID).css(style);

            });

        }else{//minimized
            orion_box.max();
        }
    },

    close: function(){
        //alert('close');
        //jQuery('div#orion_box_contenedor').toggle(400);
        jQuery('div#orion_box_contenedor').remove();
        jQuery('div#orion_box_over').remove();
        jQuery('div#orion_box_max').remove();
        orion_box.control_minimized = 0;
        this.load = 0;
    },

    minimize: function(){
        //alert('min');
        if(orion_box_options.minimize == true){
            jQuery('div#orion_box_contenedor').toggle();
            jQuery('div#orion_box_max').toggle();
            jQuery('div#orion_box_over').toggle();
            orion_box.control_minimized = 1;
        }
    },

    max: function(){
        jQuery('div#orion_box_max').toggle();
        jQuery('div#orion_box_contenedor').toggle();
        jQuery('div#orion_box_over').toggle();
    }

}

/**
 * cargo por eventos los enlaces asociados en los box.
 * uso basico: $('a[rel*=box]').OrionBox();
 * uso basico: $('a[rel*=box]').OrionBox();
 *
 * <a href="url" rel="box:500:400" target="iframe">cargar en box iframe</a>
 * <a href="url" rel="box:500:400" target="xhr">cargar en box por ajax</a>
 * <a href="url" rel="box:500:400" target="content:iframe">cargar en box iframe dentro del div "content"</a>
 */
$.fn.OrionBox = function(callback) {

    function clickHandler(e) {
        // si el usuario ha utilizado una tecla de control
        // no hacemos nada
        if (e.ctrlKey || e.shiftKey || e.metaKey)
            return;

        var rel = this.rel;
        var url = this.href;
        var target = this.target;

        if((typeof(target) == "undefined")){
            target = 'xhr';
        }

        var width = '500';
        var height = '400';

        // obtengo las dimensiones del atributo "rel"
        var brokenstring = rel.split(':');

        if((typeof(brokenstring[1]) != "undefined")){
            width = brokenstring[1];
        }

        if((typeof(brokenstring[2]) != "undefined")){
            height = brokenstring[2];
        }

        //orion_box.botonera = 0;
        //alert(width + height);

        var base = 'body';
        var main = target;
        
        // cargamos en un contenedor alternativo
        if(target.match(/[:]/)){
            //alert(target);
            var contenedores = target.split(':');
            base = contenedores[0];
            main = contenedores[1];
        }
        //alert(base + ' ' + main);

        if(main == 'iframe'){
            orion_box.iframe(url, width, height,base);
        }else{
            orion_box.xhr(url, width, height,null,base);
        }

        // cancelamos el comportamiento natural del enlace
        e.preventDefault();
    }

    this
    .unbind()
    .filter('a[href]') // que no se nos cuele algo que no sea un enlace
    .bind('click', clickHandler);

    return this; // permitimos concatenabilidad

}
/**
 * AutoComplete Field - JavaScript Code
 *
 * This is a sample source code provided by fromvega.
 * Search for the complete article at http://www.fromvega.com
 *
 * Enjoy!
 *
 * @author fromvega
 *
 * modificaciones: Oscar Añón
 * adaptado a Orion
 * se transformo por completo a un objeto para permitir multiples instancias.
 * se agrego la funcion callback al metodo setAutoComplete, que
 * permite ejecutar una funcion al resultado luego de presionar enter
 * es ideal para enviar el valor al buscador etc ...
 *
 * se corrigieron varios bugs del script original.
 */

function OrionAutocomplete(){
    // global variables
    this.acListTotal   =  0;
    this.acListCurrent = -1;
    this.acDelay		  = 500;
//    this.acURL		  = null;
//    this.acSearchId	  = null;
//    this.acResultsId	  = null;
//    this.acSearchField = null;
//    this.acResultsDiv  = null;
}

OrionAutocomplete.prototype = {

    acURL: null,
    acSearchId: null,
    acResultsId: null,
    acSearchField: null,
    acResultsDiv: null,

    setAutoComplete: function(field_id, results_id, get_url,callback){
        // initialize vars
        this.acSearchId  = "#" + field_id;
        this.acResultsId = "#" + results_id;
        this.acURL 		= get_url;

        // sino existe el elemento no hacemos nada parche:  2010-08-13
        if(typeof jQuery(this.acSearchId).attr('id') == 'undefined'){
            return ;
        }
        
        var Obthis = this;

        var ResObject = jQuery('#' + results_id).attr('id');

        if(typeof ResObject == 'undefined'){
            // create the results div
            jQuery("body").append('<div id="' + results_id + '"></div>');
        }

        // register mostly used vars
        this.acSearchField	= jQuery(this.acSearchId);
        this.acResultsDiv	= jQuery(this.acResultsId);

        // reposition div
        this.repositionResultsDiv();

        // on blur listener
        this.acSearchField.blur(function(){
            setTimeout(function(){
                Obthis.clearAutoComplete();
            }, 200)
        });

        // on key up listener
        this.acSearchField.keyup(function (e) {

            // get keyCode (window.event is for IE)
            var keyCode = e.keyCode || window.event.keyCode;
            var lastVal = Obthis.acSearchField.val();

            // check an treat up and down arrows
            if(Obthis.updownArrow(keyCode)){
                return;
            }

            // check for an ENTER
            if(keyCode == 13){
                Obthis.clearAutoComplete();
                // nova
                //alert('enter');
                if(typeof callback != 'undefined')
                    callback.call(lastVal);

                return;
            }
            // check for an ESC
            if(keyCode == 27){
                Obthis.clearAutoComplete();
                return;
            }

            //jQuery('#minichart').html(Obthis.acDelay+' setauto:'+lastVal+'<br/>').css('color','red');
            
            // if is text, call with delay

            setTimeout(function () {
                Obthis.autoComplete(lastVal,callback)
                }, Obthis.acDelay);
        
        });
    },

    // treat the auto-complete action (delayed function)
    autoComplete: function(lastValue,callback){
        var Obthis = this;
        // get the field value
        var part = this.acSearchField.val();

        // if it's empty clear the resuts box and return
        if(part == ''){
            this.clearAutoComplete();
            return;
        }

        //jQuery('#minichart').append('zlastval:'+zlastval+' autoComplete:'+lastValue+' part:'+part+'<br/>').css('color','red');
        
        // if it's equal the value from the time of the call, allow
        //alert(lastValue+' '+part);
        if(lastValue != part){
            return;
        }

        // get remote data as JSON
        jQuery.getJSON(this.acURL + part, function(json){

            // get the total of results
            var ansLength = Obthis.acListTotal = json.length;

            var actualvalor = jQuery(Obthis.acSearchId).val();

            //alert(typeof actualvalor);

            // if there are results populate the results div
            if((ansLength > 0) && (typeof actualvalor != 'undefined')){
                //jQuery('#minichart').html(':'+actualvalor+':').css('color','red');
                var newData = '';

                // create a div for each result
                for(i=0; i < ansLength; i++) {
                    newData += '<div class="unselected">' + json[i] + '</div>';
                }

                //alert(newData);

                // update the results div
                Obthis.acResultsDiv.html(newData);
                Obthis.acResultsDiv.css("display","block");

                //acResultsDiv.css('background-color', 'red');
                Obthis.acResultsDiv.css('z-index', '300');

                // for all divs in results
                var divs = jQuery(Obthis.acResultsId + " > div");

                // on mouse over clean previous selected and set a new one
                divs.mouseover( function() {
                    divs.each(function(){
                        this.className = "unselected";
                    });
                    this.className = "selected";
                })

                // on click copy the result text to the search field and hide
                divs.click( function() {
                    Obthis.acSearchField.val(this.childNodes[0].nodeValue);
                    Obthis.clearAutoComplete();
                    if(typeof callback != 'undefined')
                        callback.call(this.childNodes[0].nodeValue);
                });

            } else {
                Obthis.clearAutoComplete();
            }
        });
    },

    // clear auto complete box
    clearAutoComplete: function (){
        if(typeof this.acResultsDiv == 'object'){
            this.acResultsDiv.html('');
            this.acResultsDiv.css("display","none");
        }
    },

    // reposition the results div accordingly to the search field
    repositionResultsDiv: function(){
        // get the field position
        var sf_pos    = this.acSearchField.offset();
        
        if(typeof sf_pos != 'undefined'){
            var sf_top    = sf_pos.top;
            var sf_left   = sf_pos.left;

            // get the field size
            var sf_height = this.acSearchField.height();
            var sf_width  = this.acSearchField.width();

            // apply the css styles - optimized for Firefox
            this.acResultsDiv.css("position","absolute");
            this.acResultsDiv.css("left", sf_left - 2);
            this.acResultsDiv.css("top", sf_top + sf_height + 5);
            this.acResultsDiv.css("width", sf_width - 2);
        }
    },


    // treat up and down key strokes defining the next selected element
    updownArrow:function(keyCode) {
        var Obthis = this;
    
        if(keyCode == 40 || keyCode == 38){

            if(keyCode == 38){ // keyUp
                if(this.acListCurrent == 0 || this.acListCurrent == -1){
                    this.acListCurrent = this.acListTotal-1;
                }else{
                    this.acListCurrent--;
                }
            } else { // keyDown
                if(this.acListCurrent == this.acListTotal-1){
                    this.acListCurrent = 0;
                }else {
                    this.acListCurrent++;
                }
            }

            // loop through each result div applying the correct style
            this.acResultsDiv.children().each(function(i){
                if(i == Obthis.acListCurrent){
                    Obthis.acSearchField.val(this.childNodes[0].nodeValue);
                    this.className = "selected";
                } else {
                    this.className = "unselected";
                }
            });

            return true;
        } else {
            // reset
            this.acListCurrent = -1;
            return false;
        }
    }

}



//(function(jQuery) {
/**
 * este plug-in es un filtro/control de caracteres para
 * elementos inputs de formularios.
 * @autor Oscar Añón
 * @version 1.0 2009-07-30
 *
 * filter puede tomar valores como ser:
 * "email" : permite solo caracteres validos para email
 * "basico" : conjunto de caracteres comunes (es el filtro por defecto)
 * "name" : es para inputs de nombres, apellidos
 * "url" : permite solo caracteres para Urls
 * "alpha" caracteres alfanumericos basicos
 * "numeric" : solo numeros y comas,puntos y signos de mas (+) y menos (-)
 * "numericstrict" : solo numeros de forma extricta con decimales separados por puntos
 * @todo
 *  completar los filtros por defecto y permitir crear los
 *  propios del usuario en options, como options.filter = regexp
 *  agregar en options options.maxchars = numero de caracteres maximos
 *
 *  
 */
jQuery.fn.sanityinputs = function(filter,options) {
    
    var _internal_process = function(event){
        var eventCode = event.keyCode;
        // teclas de navegacion 27,13,39,37
        if (eventCode != 13 &&
            eventCode != 27 &&
            eventCode != 39 &&
            eventCode != 37 &&
            eventCode != 8 &&
            eventCode != 46) {

            var match = jQuery(macheos).attr(filter);

            if(typeof match == 'undefined'){
                match = macheos.basic;
            }

            var valorprevio = Element.val();
            var valornuevo = valorprevio.replace(match, '','ig');
            //alert(valorprevio + ' ' + valornuevo);
            //alert(match);
            Element.val(valornuevo);
            return true;
        }

        return true;
    }
    
    if(filter == 'remove'){
        //this.unbind('keyup',_internal_process);
        this.unbind('keyup');
        return true;
    }

    if(typeof filter == 'undefined'){
        filter = 'basic';
    }

    if (!this.length) {
        // si no hay elemento seleccionado no hacemos nada
        return this;
    }

    if (typeof options == 'function')
        options = { success: options };

     var macheos = {};
     macheos.email = /[^a-z0-9_.@]/ig;
     macheos.basic = /[^a-z0-9_.@áéíóúäëïöüñ,;:?¿ -]/ig;
     macheos.name = /[^a-z0-9.áéíóúäëïöüñ ]/ig;
     macheos.url = /[^a-z0-9_./:-]/ig;
     macheos.alpha = /[^a-z0-9_.@áéíóúäëïöüñ, -]/ig;
     macheos.numeric = /[^0-9.,+-]/ig;
     macheos.numericstrict = /[^0-9.]/ig;
    
    options = jQuery.extend({
        cosa:  'sdsda',
        coso: 'sdsd',
        success: function(){}
    }, options || {});

    //this.unbind();
    var Element = this;

    //this.keyup(_internal_process);
    this.bind('keyup',_internal_process);

    // si por casualidad se obtiene una funcion se ejecuta luego de aplicar el
    // efecto
    options.success.call();

    return this; // permitimos concatenabilidad de efectos
}

//})(jQuery);


/* 
 * Este es un lindo efectito para poner en espera una accion ajax
 * mientras se ejecuta
 * @author Oscar Añón (nova)
 * @version 2009-07-24
 *
 * 
 */
//(function(jQuery) {

/**
 * aplicamos el efecto de loading sobre un div para generar el 
 * estado de espera para los ansiosos.
 * @param options {image:imagepath,color:backgroundcolor,success:function}
 * image - es la ruta a la imagen para el efecto
 * color - es el color de fondo def "#ffffff"
 * success - es una funcion que se ejecuta luego de aplicar el efecto
 * esta por compatibilidad
 * @description aplica el efecto loading sobre el div seleccionado
 * 
 */
jQuery.fn.showloading = function(options) {

     var _internal_showloading = function(target,image,color){
        // dimensiones del contenedor
        var h = jQuery('#' + target).height();
        var w = jQuery('#' + target).width();
        var t = (h / 2);

        //h = 0;
		
		//var contentID = this.attr('id');
		
        var style = 'position:absolute;top:0px;vertical-align:middle;height:'+h+'px;width:'+w+'px;';
        style += 'z-index:200;background-color:'+color+';filter:alpha(opacity=75);-moz-opacity:0.75;opacity:0.75;';
        var cargando = '<div id="ShowLoading_'+target+'" align="center" style="'+style+'">';
        style = 'position:relative;top:'+t+'px;vertical-align:middle;';
        cargando += '<img style="'+style+'" align="middle" border="0" src="'+image+'" />';
        cargando += '</div>';
        var position = jQuery('#' + target).css('position');

        // fix de la posicion del div contenedor (todo div contenedor tiene que tener posicion)
        if(position == 'static')
            jQuery('#' + target).css('position', 'relative');
        jQuery('#' + target).prepend(cargando);
        jQuery('#' + target).unbind('css');
    }

    if(options == 'remove'){
        var removeID = this.attr('id');
        jQuery('#ShowLoading_' + removeID ).remove();
        return this;
    }
    
    if (!this.length) {
        // si no hay elemento seleccionado no hacemos nada
        return this;
    }

    if (typeof options == 'function')
        options = { success: options };

    options = jQuery.extend({
        image:  '/Orion/base-javascript/showloading/spinner.gif',
        color: '#ffffff',
        success: function(){}
    }, options || {});

    // aca se mete el efecto
    //this.unbind();
    _internal_showloading(this.attr('id'),options.image,options.color);

    // si por casualidad se obtiene una funcion se ejecuta luego de aplicar el
    // efecto
    options.success.call();

    return this; // permitimos concatenabilidad de efectos
}

//})(jQuery);

/*
Como utilizar ayax de forma basica.

makeRequest(url):
efectua la llamada al php de datos.
ej: <a href="#" onclick="makeRequest('control/set.php?set=tortuga')">Make a request</a>

alertContents():
efectua la accion sobre la pagina actual.

http_request.responseText:
es la salida devuelta por el php invocado, ej anterior, control/set.php
*/

function makeRequest(url) {
	var http_request = false;

	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
	} else if (window.ActiveXObject) { // IE
		http_request = new ActiveXObject("Microsoft.XMLHTTP");
	}

	http_request.onreadystatechange = alertContents;

	http_request.open('GET', url, true);

	http_request.send("");

}

function alertContents() {
	//alert(http_request.readyState);
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			//RemoteData = http_request.responseText;
		} else {
			alert('There was a problem with the request.');
		}
	}

}


/**
Nuevas funciones
**/

/**
procesa url remota y obtiene el contenido.
url - es la url a invocar
callback_function - es la funcion a la cual se le pasara el contenido remoto para ser procesado, mostrado ... etc
return_xml - si lo que se regresa es un xml se pone en 1 para procesar de forma correcta
*/
	//var http_request = false;
function makeHttpRequest(url, callback_function, return_xml) {
	var http_request = false;

	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request) {
		alert('Tu navegador no soporta Ayax.');
		return false;
	}
	http_request.onreadystatechange = function() {
		if (http_request.readyState == 4) {
			if (http_request.status == 200) {
				if (callback_function){
					if (return_xml) {
						eval(callback_function + '(http_request.responseXML)');
					} else {
						eval(callback_function + '(http_request.responseText)');
					}
				}
			} else {
				//alert('Hay problemas con la peticion.(Code: ' + http_request.status + ')');
			}
		}
	}
	http_request.open('GET', url, true);
	http_request.send(null);
}

	function AjaxURLloadpage(page_request, containerid){
		if (page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf("http") == -1))
			document.getElementById(containerid).innerHTML= page_request.responseText
	};
	
/**
funcion que carga de forma simple el contenido de una url en un div

*/
function AjaxURLtoDiv(url, containerid){
	var bustcachevar=1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
	var loadedobjects= ""
	var rootdomain= ""+window.location.hostname
	var bustcacheparameter= ""
	var page_request = false

	if (window.XMLHttpRequest) // if Mozilla, Safari etc
	page_request = new XMLHttpRequest()
	else if (window.ActiveXObject){ // if IE
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP")
		}
		catch (e){
			try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP")
			}
			catch (e){}
		}
	}
	else
	return false
	page_request.onreadystatechange= function(){
		AjaxURLloadpage(page_request, containerid)
	}
	if (bustcachevar) //if bust caching of external page
	bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
	page_request.open('GET', url+bustcacheparameter, true)
	page_request.send(null)
};
function CentrarVentana(){
	x = (screen.width - 300) / 2;
	y = (screen.height - 200) / 2;
	moveTo(x, y);
}

function VentanaIsq(){
	x = (screen.width - 400) / 4;
	y = (screen.height - 400) / 4;
	moveTo(x, y);
}

function showPopup(){
	var popup = window.open(this.href, 'popup', 'height=800,width=600');
	popup.focus();
	return false;
}

function showInPopup(url){
	var popup = window.open(url, 'ventana', 'height=800,width=600');
	popup.focus();
	return true;
}

function popup_upload(url){
	window.open(url, 'ventana', 'height=200,width=400');
}


// nuevas - 2007 12 19
function obtener_valor_get(variable){
	var remplaza = /\+/gi;
	var url = window.location.href;

	url = unescape(url);
	url = url.replace(remplaza, " ");
	//url = url.toUpperCase();

	//var variable_may = variable.toUpperCase();
	var variable_may = variable;
	var variable_pos = url.indexOf(variable_may);

	if (variable_pos != -1)	{
		var pos_separador = url.indexOf("&", variable_pos);

		if (pos_separador != -1){
			return url.substring(variable_pos + variable_may.length + 1, pos_separador);
		}else{
			return url.substring(variable_pos + variable_may.length + 1, url.length);
		}
	}else{
		return "";
	}
}

function noNumbers(e) {
	var keynum
	var keychar
	var numcheck

	if(window.event) { // IE
		keynum = e.keyCode
	}
	else if(e.which) { // Netscape/Firefox/Opera
		keynum = e.which
	}
	keychar = String.fromCharCode(keynum)
	numcheck = /\d/
	return !numcheck.test(keychar)
}

function SoloNumerico(e){
	var keynum
	var keychar
	var numcheck
	numcheck = /\d/

	if(window.event){ // IE
		keynum = e.keyCode
	}
	else if(e.which){ // Firefox
		keynum = e.which
	}

	//alert(keynum);

	keychar = String.fromCharCode(keynum);

	if(keynum == 13 || keynum == 8 || keynum == 46){
		return keychar;
	}

	return numcheck.test(keychar)
}

/**
obtiene el valor seleccionado de un select
select_id es el ID del elemento select
*/
function Value_from_select(select_id){
	var selector = document.getElementById(select_id);
	var selected_option=selector.options.selectedIndex;
	return selector.options[selected_option].innerHTML;
}

/**
 * regresa el key del select (value del option)
 * @param {Object} select_id
 */
function Key_from_select(select_id){
	var selector = document.getElementById(select_id);
	var selected_option=selector.options.selectedIndex;
	return selector.options[selected_option].value;
}

/**
 * funcion para determinar la existencia de funciones
 * @param {Object} function_name
 * @return bool
 */
function function_exists( function_name ) {
    // Return TRUE if the given function has been defined
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_function_exists/
    // +       version: 804.1712
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Steve Clay
    // +   improved by: Legaev Andrey
    // *     example 1: function_exists('isFinite');
    // *     returns 1: true


    if (typeof function_name == 'string'){
        return (typeof window[function_name] == 'function');
    } else{
        return (function_name instanceof Function);
    }
}

/**
 * determina si existe una variable, como en PHP
 */
function isset(  ) {
    // Determine whether a variable is set
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_isset/
    // +       version: 804.1713
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: FremyCompany
    // *     example 1: isset( undefined, true);
    // *     returns 1: false
    // *     example 2: isset( 'Kevin van Zonneveld' );
    // *     returns 2: true

    var a=arguments; var l=a.length; var i=0;
    
    while ( i!=l ) {
        if (typeof(a[i])=='undefined') { 
            return false; 
        } else { 
            i++; 
        }
    }
    
    return true;
}

/**
 * selector de un checkbox a la ves, del grupo especificado
 * como element, clases objetos etc ...
 * 
 * @param {Object} element
 */
function jquery_checkboxes_selector_once(element){
	$(element).click( function() { 
	//clear("checkbox_tr"); 
	$(element).attr('checked',false);
	$(this).attr('checked',true);
} );
}

function selector_selectedIndex_change(selectid,index){
var selector = document.getElementById(selectid);

selector.options.selectedIndex = index;
}

function selector_selectedIndex(selectid,optvalue){
var selector = document.getElementById(selectid);

selector.options.selectedIndex = 2;
}

/**
 * como el nombre lo dice hace eso ...
 * @param {Object} iframeid
 * @param {Object} src
 */
function Orion_Iframe_change_src(iframeid,src){
	var iframe = document.getElementById(iframeid);
	iframe.src = src;
}

/**
convierte el contenido de un textarea en un array
*/
function Orion_textareaToArray(t){
	return t.value.split(/[\n\r]+/);
}

/**
permite visualizar un array en un alert, para depuracion
*/
function debug_showArray(a){
	var msg="";
	for(var i=0;i<a.length;i++){
		msg+=i+": "+a[i]+"\n";
	}
	alert(msg);
}

// modulo para jQuery, recarga de imagenes
// pasar las imagenes como argumento
jQuery.preloadImages = function(){
  for(var i = 0; i<arguments.length; i++){
    jQuery("<img>").attr("src", arguments[i]);
  }
}

/**
cortar palabras largas
uso: cortar_palabras("Hello everyone how are you doing? I'm writing an extravagently long string.", 6);
*/
function cortar_palabras(str, num) {
  return str.replace(RegExp("(\\w{" + num + "})(\\w)", "g"), function(all,text,char){
    return text + "<wbr>" + char;
  });
}

/**
linda funcion para recortar palabras y frases de forma rapida
*/
function recortar_palabras(str, num) {
	var cadena = '';
	var largo = str.length;

	if(largo > num){
		return str.substring(0,num)  + ' ..';
	}else{
		return str;
	}
}

/**
crea un div oculto, el cual sirve para mostrar informacion a los usuarios
llamandolo con jQuery y cargandole el contenido a traves de ajax
id del div contenido: avisos_content
utilizar toggle sobre avisos
*/
function notify_div_create(){
	// crear el div oculto para desplegar informacion al usuario
	$(document).ready( function() {

		// agregando los estilos al vuelo
		addCss('#avisos {display:none;position:fixed;top:150px;left:300px;background:#dddddd;z-index:40;}');
		if($.browser.msie){
		addCss('#avisos {display:none;position:absolute;top:300px;left:300px;background:#444444;z-index:40;}');
		//addCss('#avisos {position:fixed;}');
		}
		
		addCss('#avisos_content {position:relative;top:20px;padding:3px;margin-bottom:20px;}');
		addCss('.avisos_barra {margin-right:4px;position:absolute;right:0px;top:0px;}');

		addCss('#avisos_background {opacity:0.60;filter:alpha(opacity=60);width:100%;height:170%;display:none;position:absolute;top:0px;background:#444444;z-index:28;}');
		if($.browser.msie){
		addCss('#avisos_background {width:0px;height:0px;display:none;position:absolute;top:0px;left:0px;background:#444444;z-index:35;}');	
		}
		
		$('<div id="avisos_background"></div>').appendTo("body");
		
		$('<div id="avisos"><div id="avisos_content"> avisos loading ... </div></div>').appendTo("body");
		$('<div class="avisos_barra"> <a href="javascript:;" rel="avisos_toggle" id="avisos_cerrar">cerrar</a> </div>').appendTo("div#avisos");
		//$("div#avisos").load("/html/algo.html");

		// efecto de acultacion del div de avisos
		$("a[rel='avisos_toggle']").click(function() {
			$("#avisos_background").toggle(100);
			$("#avisos").toggle(400);
		});
		
		$("div#avisos_background").click(function() {
			$("#avisos_background").toggle(100);
			$("#avisos").toggle(400);
		});		

	} );
}

/**
 *despliega los mensajes a los usuarios
 */
function form_messages_show(a){
	var msg="";
	for(var i=0;i<a.length;i++){
		msg += a[i]+"\n";
	}
	alert(msg);
}

/**
 * procesa los mensajes recividos como respuesta de los
 * formularios ajaxForm a traves de la API nebula
 */
function form_processJson(data){
    //var errors = data.errors;
    var errors = 'errors' in data? data.errors : "";
    //var notice = data.notice;
    var notice = 'errors' in data? data.notice : "";

    var on_sucess = 'on_sucess' in data? data.on_sucess : "";

    var sin_errores = true;

    if(on_sucess.length > 0){
        eval(on_sucess);
        return true;
    }

    if(errors.length > 0){
    form_messages_show(errors);
     sin_errores = false;
    }

    if(notice.length > 0){
    form_messages_show(notice);
    }

    return sin_errores;
}

/**
 * procesa los mensajes recividos como respuesta de los
 * formularios ajaxForm a traves de la API nebula
 * regresando respuesta solo si hay errores.
 */
function api_processJson(data){
    //var errors = data.errors;
    var errors = 'errors' in data? data.errors : "";
    //var notice = data.notice;
    var notice = 'errors' in data? data.notice : "";

    var on_sucess = 'on_sucess' in data? data.on_sucess : "";

    var sin_errores = true;

    if(on_sucess.length > 0){
        eval(on_sucess);
        return true;
    }

    if(errors.length > 0){
    form_messages_show(errors);
     sin_errores = false;
    }

    return sin_errores;
}

function formularios(){

    // control de formularios basico
    var options = {
        dataType:  'json',
        success:   form_processJson
    }

     // formulario de comentarios
    var options_formcontacto = {
        dataType:  'json',
        success:   function(data){
         form_processJson(data);
         $('#formcontacto').clearForm();
         //$('form[id*=orionform]').clearForm();
        }
    }
    
    $('#formcontacto').ajaxForm(options_formcontacto);
    $('form[id*=orionform]').ajaxForm(options_formcontacto);

}

/**
 *esta funcion es de suma importancia para las interacciones ajax
 */
function ajaxpostload(){
   // acciones ayax - mandar los enlaces al centro //
    $('a[rel*=orioncontentload]').OrionContentLoad(function(){
        // formularios dinamicos (ayax)
        formularios();
        //ajaxpostload();
    });

    orion.xhr.preload();
    // asigno popups a los enlaces que contengan "openinpopup"
    //$('a[rel*=openinpopup]').popup();

    // Nebula API links
    //$('a[rel*=napi_action]').ajax_action();
}


/**
 * esta funcion carga la URL en un contenedor
 * es ideal para ser llamada desde flash.
 */
function orion_flajax(url,target){
//    $('#'+target).load(url,{orionload:1},function(){
//        ajaxpostload();
//    });
//orion.xhr.load(url, target);
    OrionContentLoad(url, target, function(){
        ajaxpostload();
        formularios();
    });
}

/**
 * carga la url en el contenedor "target",
 * params son los parametros al estilo JSON y son enviados
 * por POST
 *
 * 
 */
function orion_flajax_param(url,target,params,callback){
    params.orionload = 1;

    $('#'+target).load(url,params,function(){
        ajaxpostload();
        if(typeof(callback) != "undefined"){
            callback();
        }
    });
}

function urlencode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer
    // +      input by: Ratheous
    // %          note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'

    var hash_map = {}, unicodeStr='', hexEscStr='';
    var ret = (str+'').toString();

    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };

    // The hash_map is identical to the one in urldecode.
    hash_map["'"]   = '%27';
    hash_map['(']   = '%28';
    hash_map[')']   = '%29';
    hash_map['*']   = '%2A';
    hash_map['~']   = '%7E';
    hash_map['!']   = '%21';
    hash_map['%20'] = '+';
    hash_map['\u00DC'] = '%DC';
    hash_map['\u00FC'] = '%FC';
    hash_map['\u00C4'] = '%D4';
    hash_map['\u00E4'] = '%E4';
    hash_map['\u00D6'] = '%D6';
    hash_map['\u00F6'] = '%F6';
    hash_map['\u00DF'] = '%DF';
    hash_map['\u20AC'] = '%80';
    hash_map['\u0081'] = '%81';
    hash_map['\u201A'] = '%82';
    hash_map['\u0192'] = '%83';
    hash_map['\u201E'] = '%84';
    hash_map['\u2026'] = '%85';
    hash_map['\u2020'] = '%86';
    hash_map['\u2021'] = '%87';
    hash_map['\u02C6'] = '%88';
    hash_map['\u2030'] = '%89';
    hash_map['\u0160'] = '%8A';
    hash_map['\u2039'] = '%8B';
    hash_map['\u0152'] = '%8C';
    hash_map['\u008D'] = '%8D';
    hash_map['\u017D'] = '%8E';
    hash_map['\u008F'] = '%8F';
    hash_map['\u0090'] = '%90';
    hash_map['\u2018'] = '%91';
    hash_map['\u2019'] = '%92';
    hash_map['\u201C'] = '%93';
    hash_map['\u201D'] = '%94';
    hash_map['\u2022'] = '%95';
    hash_map['\u2013'] = '%96';
    hash_map['\u2014'] = '%97';
    hash_map['\u02DC'] = '%98';
    hash_map['\u2122'] = '%99';
    hash_map['\u0161'] = '%9A';
    hash_map['\u203A'] = '%9B';
    hash_map['\u0153'] = '%9C';
    hash_map['\u009D'] = '%9D';
    hash_map['\u017E'] = '%9E';
    hash_map['\u0178'] = '%9F';

    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);

    for (unicodeStr in hash_map) {
        hexEscStr = hash_map[unicodeStr];
        ret = replacer(unicodeStr, hexEscStr, ret); // Custom replace. No regexing
    }

    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
}
var Global_deleteID=0;
var Global_editID=0;
var Global_viewID=0;

function ChangeDivFrameDelete(){
	if (deletereg(Global_deleteID) == 1){
		return true;
	}
}

function ChangeDivFrameEdit(){
	if (editreg(Global_editID) == 1){
		return true;
	}
}

function ChangeDivFrameView(){
	if (viewreg(Global_viewID) == 1){
		return true;
	}
}

function ChangeDivFrame(id){
	Global_deleteID=id;
	Global_editID=id;
	Global_viewID=id;
	document.getElementById("DELETE").onclick=ChangeDivFrameDelete;
	document.getElementById("EDIT").onclick=ChangeDivFrameEdit;
	document.getElementById("VIEW").onclick=ChangeDivFrameView;
}

function PintarField(field){
	document.getElementById('field'+field).className="pintar_field";
	document.getElementById('BarraSID').innerHTML = field;
	ChangeDivFrame(field);

	document.getElementById('DELETE').disabled=false;
	document.getElementById('EDIT').disabled=false;
	document.getElementById('VIEW').disabled=false;
}

function deletereg(id){
	var url_action_delete=document.getElementById('url_action_delete').value;
	if(confirm('Confirmacion de Borrado: '+id) == true){

		makeRequest(url_action_delete+'?item='+id);

		var tabla=document.getElementById('tablita');
		var fila=document.getElementById('field'+id);
		tabla.removeChild(fila);
		return 1;
	}

	return false;
}

function editreg(id){
	var url_action_edit=document.getElementById('url_action_edit').value;
	var sizewindows=document.getElementById('sizewindows').value;
	var popup = window.open(url_action_edit+'?item='+id, 'edicion de registro', sizewindows);
	popup.focus();
	return 1;
}

function viewreg(id){
	var url_action_view=document.getElementById('url_action_view').value;
	var sizewindows=document.getElementById('sizewindows').value;
	var popup = window.open(url_action_view+'?item='+id, 'informacion de registro', sizewindows);
	popup.focus();
	return 1;
}


function pagina(pg){
	if (!(pg > 0))
	exit;

	var pgshow=document.getElementById('pgshow').value;
	var restanxpag=document.getElementById('restanxpag').value;
	var search=document.getElementById('search').value;

	var init=(pg-1)*pgshow;
	location='?pginit='+init+'&pgend='+pgshow+'&search='+search;
}


function pagina_con_url(pg, valores){
	if (!(pg > 0))
	exit;

	var pgshow=document.getElementById('pgshow').value;
	var restanxpag=document.getElementById('restanxpag').value;
	var search=document.getElementById('search').value;

	var init=(pg-1)*pgshow;
	location='?'+ valores +'pginit='+init+'&pgend='+pgshow+'&search='+search;
}

function PintarNombreCampo(campo){
	document.getElementById(campo).className="pintar_campo";
}

function busqueda(b,biteml){
	location='?search='+b+'&search_item='+biteml;
}

function ChangeContent(element,text){
	document.getElementById(element).innerHTML = text;
}

function busqueda_item(campo){
	selant=document.getElementById('search_item').value;

	if(selant !== ""){
		document.getElementById(selant).className="";
	}

	document.getElementById('search_item').value=campo;
	document.getElementById(campo).className="pintar_texto";

	traslate=document.getElementById(campo).innerHTML;
	ChangeContent('buscar_por',traslate);

}

/**
 * funcion para los paginados donde estilo es el estido a dejar,
 * al liberar la busqueda.
 *  
 * @param {Object} campo
 * @param {Object} estilo
 */
function busqueda_item_2(campo,estilomarcar,estilolibera){
	selant=document.getElementById('search_item').value;

	if(selant !== ""){
		//alert('pototo');
		document.getElementById(selant).className="";
	}

	document.getElementById('search_item').value=campo;
	document.getElementById(campo).className=estilomarcar;
	traslate=document.getElementById(campo).innerHTML;

	ChangeContent('buscar_por',traslate);
}

function paginate_state(){
	var search_item = obtener_valor_get('search_item');
	//document.getElementById('buscar_por').innerHTML="pepon";

	if (search_item !== ""){
		document.getElementById(search_item).className="pintar_texto";
		var traslate=document.getElementById(search_item).innerHTML;
		ChangeContent('buscar_por',traslate);
	}

}


/**
funcion para detectar el navegador
 */
function detectar_navegador(){
    var navegador = navigator.appName
    var ret;
	
    if (navegador == "Microsoft Internet Explorer")
	ret = 'IE';
    else
	ret = 'W3C';
	
    return ret;
}

/**
imgname - nombre imagen
id - id del elemento img
imgdirpath - directorio base de las imagenes
*/
function ChangeImgSourceOpt(imgname,id,imgdirpath){
	var UserPhoto = document.getElementById(id);
	UserPhoto.src = '/usr/images/normal/' + imgname;
}

/**
element - elemento imagen
zoom - incremento de la imagen
usar asi: onmouseout="EfectoMac_01(this,0.5);" onmouseover="EfectoMac_01(this,2);"
*/
function EfectoMac_01(element,zoom){
	//width="80" height="60"
	var width = element.width;
	var height = element.height;
	
	var zoom_width = width * zoom;
	var zoom_height = height * zoom;
	
	element.width = zoom_width;
	element.height = zoom_height;
}

/**
usar asi: onmouseover="EfectoMac_01_div_on(this,30);" onmouseout="EfectoMac_01_div_out(this);"
*/
function EfectoMac_01_div_on(element,position){
	//element.style = 'position: relative; top: -' +position+ 'px;';
	element.style.position = 'relative';
	element.style.top = '-' +position+ 'px';
}

function EfectoMac_01_div_out(element){
	element.style.position = '';
	element.style.top = '';
}

/**
funcion simple que cambia entre dos hojas de estilo a un objeto,
util para mostrar u ocultar divs.
id - id del elemento (div)
css_show - class utilizado para desplegar el div
css_hide - class para ocultar el div
*/
var show_div_01 = 0;
function EfectoOcultarDiv_01(id,css_show,css_hide){
	var div = document.getElementById(id);
	
	//alert(navigator.appName);
	
	if(show_div_01 == 1){
		div.setAttribute("className", css_hide);
		div.setAttribute("class", css_hide);
		show_div_01 = 0;
	}else{
		div.setAttribute("class", css_show);
		div.setAttribute("className", css_show);
		show_div_01 = 1;
	}
}

/**
lleva un div a la parte mas baja, ideal para sistemas de mensajeria o noticias.
*/
function DivScrolltoBottom(elementid){
	var objDiv = document.getElementById(elementid);
	objDiv.scrollTop = objDiv.scrollHeight;
}

/**
elimina un tr de una tabla
*/
function eliminar_tr(tableid,trid){
		var tabla=document.getElementById(tableid);
		var fila=document.getElementById(trid);
		tabla.removeChild(fila);
}


function addCss(cssCode) { 
    var styleElement = document.createElement("style"); 
    styleElement.type = "text/css"; 
    if (styleElement.styleSheet) { 
        styleElement.styleSheet.cssText = cssCode; 
    } else { 
        styleElement.appendChild(document.createTextNode(cssCode)) 
    } 
    document.getElementsByTagName("head")[0].appendChild(styleElement); 
}

function OcultarDiv_tras_un_tiempo(DivID,time){
    var div = document.getElementById(DivID);
    //setTimeOut / setInterval
       
	   
	//$("div#"+DivID).slideUp("slow",function(){alert("Animation Done.");});
	   
    if(detectar_navegador() == 'IE'){
        
    	//div.style.setAttribute('cssText', 'background-color: blue;', 0);//funciona
        //div.style.setAttribute('cssText', 'height: 10;', 0);//no funciona
        
        //div.setAttribute("className", 'pintar_texto');//funciona
        //addCss('.tama{height:10px;}');
        //div.setAttribute("className", 'tama');//funciona
        
		//setTimeout("resource_ocultar_div_ie('"+ DivID +"')",time);
		
		// usando jQuery
		setTimeout("$('div#"+ DivID +"').slideUp('slow');",time);
		
        //alert(DivID + 'IE6+');
    }else{
		
		// usando jQuery
		setTimeout("$('div#"+ DivID +"').slideUp('slow');",time);
		
		/*
		//alert('Firefox');
        var atribute = 'style';//Firefox
        setTimeout("var div = document.getElementById('"+ DivID +"');div.setAttribute('"+atribute+"', 'height:30px;');",time - 500);
        setTimeout("var div = document.getElementById('"+ DivID +"');div.setAttribute('"+atribute+"', 'height:20px;');",time - 300);
        setTimeout("var div = document.getElementById('"+ DivID +"');div.setAttribute('"+atribute+"', 'height:10px;');",time - 200);
        setTimeout("var div = document.getElementById('"+ DivID +"');div.setAttribute('"+atribute+"', 'display:none;');",time);
        */
    }
}

/**
OcultarDiv_tras_un_tiempo: recurso
*/
function resource_ocultar_div_ie(ddd){
		var div = document.getElementById(ddd);
		div.style.display='none';
}

/**
 * funcion para cerrar o habrir un div
 * requiere jQuery para funcionar
 * @param {Object} idDetalle
 */
function jQuery_show_div_data(idDetalle){
    if ($("div#" + idDetalle).is(":hidden")) {
        $("div#" + idDetalle).slideDown("slow");
    }
    else {
        $("div#" + idDetalle).slideUp("slow");
    }
}


function jQuery_slideUp(divid){
	$('div#'+divid).slideUp('slow');
}

function jQuery_slideDown(divid){
	$('div#'+divid).slideDown('slow');
}

/**
 * efecto con slide y desvanecimento lateral para acultar y activar un div
 * divid es el div a aplicarle el efecto
 * cliked es el elemento al cual al hacerle click activa el efecto
 * @param {string} divid
 * @param {string} cliked
 */
function jQuery_toggle_efect(divid,cliked){
  $('#'+cliked).click(function() {
    $('#'+divid).toggle(400);
    return false;
  });
}

/**
 * efecto tipo slide para acultar y activar un div
 * divid es el div a aplicarle el efecto
 * cliked es el elemento al cual al hacerle click activa el efecto
 * @param {string} divid
 * @param {string} cliked
 */
function jQuery_toggle_slide(divid,cliked){
  $('#'+cliked).click(function() {
    $('#'+divid).toggle(400);
    return false;
  });
}

function Orion_resizeIframe(idIframe,w){
          var miIframe=document.getElementById(idIframe);
          var alturaPagina=miIframe.contentWindow.document.body.scrollHeight+20;
          miIframe.style.height=alturaPagina; 
			
          miIframe.setAttribute("style", "width:" + w + "px;height:" + alturaPagina + "px;");
}

var colorete = 0;
function Color_Return(elemento,color_a,color_b){

	if(colorete == 0){
		$("#"+elemento).attr("bgcolor",color_a);
		colorete = 1;
	}else{
		$("#"+elemento).attr("bgcolor",color_b);
		colorete = 0;
	}

}
/*
 * Precargas de acciones y controles propios del Framework
 * autor: Oscar Añón
 * copyright Oscar Añón (Orion Framework 2009)
 */

function orion_ajax_forms(){
    // limpio los formularios tipo add por un bug con el Firefox
    //$("form[name='ajaxForm:add']").clearForm();

    $("form[name='ajaxForm:add'] input").clearFields();
    //$("form[name='ajaxForm:add' :input]").val("");

    // todo formulario con el atributo name="ajaxForm:add"
    // sera procesado por ajaxForm
    $("form[name='ajaxForm:add']").ajaxForm({
        dataType:  'json',
        success:   function(data){
            if(form_processJson(data) == true){
                // limpio el formulario si se proceso correctamente
                $(this).clearForm();
                orion.xhr.preload();
            }

        }
    });

    $("form[name='ajaxForm:mod']").ajaxForm({
        dataType:  'json',
        success:   function(data){
            if(form_processJson(data) == true){
                //$(this).clearForm();
                orion.xhr.preload();
            }

        }
    });

    $("form[name='ajaxForm:edit']").ajaxForm({
        dataType:  'json',
        success:   function(data){
            if(form_processJson(data) == true){
                //$(this).clearForm();
                orion.xhr.preload();
            }

        }
    });
}

/**
 * determina si existe o no un elemento dentro del dom
 * por su ID
 */
function existElement(ElementID){
    var check = jQuery('#' + ElementID).attr('id');
    if(typeof check != 'undefined'){
        return true;
    }

    return false;
}

var orion = function(){

}

// inicio de la extructura javascript (interfaces)
var $App = {};
//var App = {};

/**
 * utilidades varias para ayudar en el desarrollo
 */
orion.helpers = {
    /**
     * helper para convertir un json en parametros get string
     */
    JsonToUrlParams: function(json){
        var ret = '';

        jQuery.each(json, function(i,n){
            ret += i + '=' + encodeURI(n) + '&';
        })
        // quito el ultimo &
        ret = ret.replace(/&$/,'');

        return ret;
    },

    /**
     *  transforma los parametros url a JSON
     */
    UrlParamsToJson: function(params){
        params = params.replace('?', '');
        var pjson = {};
        var arrayOfStrings = params.split('&');
        for (var i=0; i < arrayOfStrings.length; i++) {
            var re = /=(.*)$/gi;
            var mth = /=.+/;
            if(arrayOfStrings[i].match(mth)){
                var newstr = arrayOfStrings[i].replace(re, "='$1'");
                eval('pjson.'+newstr);
            }
        }

        return pjson;
    }
}

/**
 * objeto para fijar valores por defecto al modulo history
 * atras en el navegador
 * se desactiva y activa con la linea en el setup del sitio
 * orion.history.enable = 0; ó orion.history.enable = 1;
 */
orion.history = {
    'enable' : 1,
    'main' : 'content',
    'mode' : 'stable',

    /**
     * suma md5 de la url actual cargada
     **/
    checksum : '',

    /**
     * esta funcion es llamada en las cargas por history2 (test)
     */
    callback : function(){},

    pageload : function(hash) {
        if(hash) {
            if($.browser.msie) {
                hash = encodeURIComponent(hash);
            }
            // aca se realiza la carga del history
            var preload = {};
            
            preload = jQuery(historyobj).attr(hash);
            if(typeof preload !== 'undefined'){
                orion.xhr.load(preload.action,preload.target,null,preload.params,1);
            }
            
        //            eval('preload = "'+hash+'" in historyobj? historyobj.'+hash+' : ""');
        //            if(typeof preload.target !== 'undefined'){
        //                orion.xhr.load(preload.action,preload.target,null,preload.params,1);
        //            }

        } else {
    //$("#load").empty();
    }
    }
}

/**
 * objeto para manejar los eventos y cargas por Ajax (XHR)
 */
orion.xhr = {

    /**
     * en este objeto se guardan los IDs de los divs contenedores
     * con la url cargada actualmente en ellos
     */
    map: {},

    load : function(url,target,callback,data,history){

        if(typeof target == 'undefined'){
            target = orion.history.main;
        }
        
        if(target == orion.history.main){
            if(orion.history.mode == 'test'){
                url = url.replace(/http[s]?[:]\/\/(www\.)?([a-z0-9_.]*)?[a-z0-9_]*\.[lcon][ore][mcgt](\.[ua][yr])?/, '');
                //alert('#' + url);
                var checksum = $.md5(url);

                if(typeof callback == 'function')
                orion.history.callback = callback;

                if(checksum != orion.history.checksum){
                    //orion.history.checksum = checksum;
                    url = encodeURI(url);
                    document.location = '#' + url;
                }else{
                    data = {
                        orionload : 1
                    };
                    $('#' + target).showloading();
                    $('#' + target).load(url, data, function(){
                    orion.xhr.preload_test();
                    orion.history.callback.call();
                    orion.history.callback = function(){};
                    $(this).showloading('remove');
                });

                }
                return true;
            }
        }

        OrionContentLoad(url,target,function(){
            orion.xhr.preload();
            //alert(typeof callback);
            if(typeof callback != 'undefined' && callback != null)
                callback.call();
        },data,history);

        return true;
    },

    /**
     * carga directa de datos por ajax
     */
    directload : function(url,target,callback,data){
        this.load(url, target, callback, data, 0);
    },

    /**
     * recarga el contenido en un contenedor
     * por defecto es el contenedor central
     * @param target es el ElementID del div contenedor
     */
    refresh: function(target){
        if (typeof target == 'undefined')
            target = 'content';

        var dataobj = jQuery(this.map).attr(target);
        if(typeof dataobj !== 'undefined'){
            this.load(dataobj.action, dataobj.target, dataobj.callback, dataobj.params, 0);
        }
    },

    preload : function(){
        $('a[rel*=xhr]').OrionContentLoad(function(){
            orion.xhr.preload();
        });

        $('a[rel*=box]').OrionBox(function(){
            orion.xhr.preload();
        });
        
        $('a[rel*=openinpopup]').popup();//deprecated
        this._popup();
        $('a[rel*=napi_action]').unbind().ajax_action();
        $('a[rel*=lightbox]').unbind().lightBox();
        orion_ajax_forms();
    },

    /**
     * este metodo es para testear las nuevas funcionalidades
     * del nuevo motor de history
     */
    preload_test : function(){
        $('a[rel*=xhr]').OrionContentLoad_test(function(){
            orion.xhr.preload_test();
        });

        $('a[rel*=box]').OrionBox(function(){
            orion.xhr.preload_test();
        });

        $('a[rel*=openinpopup]').popup();//deprecated
        this._popup();
        $('a[rel*=napi_action]').unbind().ajax_action();
        $('a[rel*=lightbox]').unbind().lightBox();
        orion_ajax_forms();
    },

    /**
     * helper para lanzar los nuevos popups
     * agrega las propiedades pw(width),ph(height) y ps(scrollbars) al
     * elemento <a> para levantar la url en popup.
     * donde target es el nombre de la ventana
     * y rel="popup" es utilizado para hacer el bind del plug-in
     * ej: <a href="/uri" pw="400" ph="300" ps="1" rel="popup">habrir aqui</a>
     */
    _popup : function(){
        $('a[rel*=popup]').unbind("click");
        $('a[rel*=popup]').bind("click", function(e) {
            // cancela el comportamiento por defecto
            var anchor = this;
            e.preventDefault();
            var url = this.href;
            var params = 'popup=1';

            var target = 'popup';
            var ancho = $(this).attr('pw') ? jQuery(this).attr('pw') : '700';
            var largo = $(this).attr('ph') ? jQuery(this).attr('ph') : '600';
            var scroll = $(this).attr('ps') ? jQuery(this).attr('ps') : 'yes';
            var atarget = $(this).attr('target');
            
            if(typeof atarget == 'string'){
                if(atarget.length > 0)
                target = atarget;
            }
            
            if(scroll == 0){
                scroll = 'no';
            }
            
            if(scroll == 1){
                scroll = 'yes';
            }
            
            if(url.match(/[?].*/)){
                url += '&' + params;
            }
            
            if(url.match(/[?]$/)){
                url += params;
            }
            
            if(!url.match(/[?]/)){
                url += '?' + params;
            }
            
            var window2 = window.open(url,'MsgWindow','menubar=no,width='+ancho+',height='+largo+',screenX=200,screenY=200,top=150,left=200, status=no,resizable=yes,scrollbars=' + scroll);
            if (window2.opener == null) window2.opener = self;
        });
    },
    
    /**
     * guarda referencia del contenido cargado en un DIV contenedor
     */
    storeMap: function(url,target,data,callback){
        var objactual = {
                'action' : url,
                'target' : target,
                'params' : data,
                'callback' : callback
            };

       jQuery(this.map).attr(target,objactual);
    }
}

/**
 * objeto para manejar los eventos de los formularios del framework
 */
orion.forms = {

    messages_init_css : {
        'background-attachment':'scroll',
        'background-color':'red',
        'background-image':'none',
        'background-position':'0 0',
        'background-repeat':'repeat',
        'color':'#FFFFFF',
        'display' : 'none',
        'margin' : '0 auto',
        'width' : '90%',
        'padding' : '4px',
        '-moz-border-radius' : '8px 8px 8px 8px',
        'font-family':'lucida Grande',
        'font-size':'12px',
        'font-weight':'bold',
        'border':'2px solid #ffffff'
    },

    /**
     * ID del div contenedor de los mensajes
     * aca se activa el uso de un div para desplegar los mensajes
     * al usuario final.
     * por ejemplo: orion.forms.messagesId = 'form_branches_messages';
     */
    messagesId : null,

    /**
     * este metodo se encarga de desplegar los mensajes al usuario
     * ya sea en un div o un simple Alert.
     *
     * @param obj JsonResponseObject respuesta del server en formato json
     */
    jsonMessages_show : function(obj){
        var time = 8000;
        var msg="";
        var msghtml = "";
        for(var i=0;i<obj.length;i++){
            msg += obj[i]+"\n";
            msghtml += obj[i]+"<br />\n";
        }

        if(this.messagesId == null)
            alert(msg);
        else{
            // cargo el mensaje en el div de mensajeria "messagesId"
            if($('div#' + this.messagesId)){
                $('div#' + this.messagesId).css(this.messages_init_css);
                $('div#' + this.messagesId).html(msghtml);
                $('div#' + this.messagesId).css('display','list-item');
                setTimeout("$('div#"+ this.messagesId +"').slideUp('slow');",time);

            }else{
                alert(msg);
            }

            this.messagesId = null;
        }
    },
    
    /**
     * obtengo la respuesta del server y la proceso
     * para mostrar mensajes o ejecutar acciones.
     *
     * @param data json object
     * @param show_notice int 0|1 
     */
    jsonResponse : function(data,show_notice){

        if(typeof show_notice == 'undefined')
            show_notice = 0;

        //var errors = data.errors;
        var errors = 'errors' in data? data.errors : "";
        //var notice = data.notice;
        var notice = 'errors' in data? data.notice : "";

        var on_sucess = 'on_sucess' in data? data.on_sucess : "";

        var sin_errores = true;

        if(on_sucess.length > 0){
            eval(on_sucess);
            return true;
        }

        /* compativilidad con el sistema nuevo de mensajes de errores */
        var error = 'error' in data? data.error * 1: 99;
        var message = 'message' in data? data.message : "";

        if(error == 1){
            notice = new Array();
            errors = new Array();
            errors[0] = message;
        }

        if(error == 0){
            notice = new Array();
            errors = new Array();
            notice[0] = message;
        }

        if(errors.length > 0){
            this.jsonMessages_show(errors);
            sin_errores = false;
        }

        if(notice.length > 0){
            if(show_notice != 0)
                this.jsonMessages_show(notice);
        }

        return sin_errores;
    },

    /**
     * metodo para mandar un formulario por ayax
     * de forma rapida, utilizando el bknd de Orion
     * y regresando los datos para procesar
     *
     * Este metodo ya despliega mensajes
     *
     *
     */
    xhr: function(formID,callback,beforeSubmit){
        var thisObj = this;
        $(document).ready(function() {

            // preparo el contenedor de los mensajes
            var cosoID = formID + '_messages';
            var mess = jQuery('#' + cosoID).attr('id');
            
            if(typeof mess == 'undefined'){
                jQuery("form#" + formID).append('<div id="'+cosoID+'" class="shadow"></div>');
            }

            jQuery("form#" + formID).ajaxForm({
                'dataType':  'json',
                'beforeSubmit': beforeSubmit,
                'success': function(data){
                    thisObj.messagesId = cosoID;
                    
                    if(thisObj.jsonResponse(data, 1) == true){

                        var errors = 'errors' in data? data.errors : "";

                        if(errors.length == 0){
                            if(typeof callback != 'undefined'){
                                var params = data;
                                callback.call(params,data);
                            }
                        }
                    }
                }
            });

        });
    }
}

/**
 * interface para cargar los widgets "apps del sistema
 * autor: Oscar Añón
 */
orion.widgets = {
    baseUrl: '/Widgets/',
    version:'1.1',

    /**
     * en este objeto se guardan los IDs de los divs contenedores
     * con la url cargada actualmente en ellos
     */
    map: {},

    /**
     * guarda referencia del contenido cargado en un DIV contenedor
     * del widget, como indice se utiliza el ID del div contenedor.
     */
    storeMap: function(widgetName,container,data,callback,type){
        var objactual = {
                'widgetName' : widgetName,
                'container' : container,
                'data' : data,
                'callback' : callback,
                'type' : type
            };
       jQuery(this.map).attr(container,objactual);
    },
    
    /**
     * helper para cargar un widget
     * @param widgetName string nombre del contrlador de la app
     * @param container string div donde cargar la app
     * @param data string json para enviar e la app
     * @param callback string funcion a ejecutar luego de cargar
     * @param type string tipo de carga xhr,iframe
     */
    load: function(widgetName,container,data,callback,type){
        if (typeof data == 'undefined')
            data = {};

        if (typeof data == 'function'){
            callback = data;
            data = {};
        }

        if (typeof callback == 'string')
            type = callback;

        if (typeof type == 'undefined')
            type = 'xhr';

        // guardo referencia del widget para los refresh
        this.storeMap(widgetName, container, data, callback, type);
        
        var url = this.baseUrl + widgetName;

        if(type == 'xhr'){
            if(typeof data == 'object'){
                data = jQuery.extend({
                    'ajaxload':  1
                }, data || {});
            }
            orion.xhr.directload(url, container, callback, data);
        }else{
            if(typeof data == 'object'){
                data = jQuery.extend({
                    'directload':  1
                }, data || {});
            }
            this._iframe(url, container, data);
        }

    },

    /**
     * recarga el contenido en un contenedor
     * por defecto es el contenedor central
     * @param container es el ElementID del div contenedor
     */
    refresh: function(container){
        var dataobj = jQuery(this.map).attr(container);
        //alert(jQuery(this.map).attr(container).widgetName);
        //alert('mapeo:'+this.mapeo.pepe + ', Wmap:' + Wmap.pepe);
        if(typeof dataobj !== 'undefined'){
            this.load(dataobj.widgetName, dataobj.container, dataobj.data, dataobj.callback, dataobj.type);
        }
    },
    
    /**
     * carga el src en un iframe dentro del contenedor principal
     * del widget
     */
    _iframe: function(src,container, data){

        if(src.match(/\?/))
            src = src + '&WidgetType=iframe';
        else
            src = src + '?WidgetType=iframe';

        // datos
        if(typeof data == 'object'){
            var params = orion.helpers.JsonToUrlParams(data);
            //ajaxload=1
            src +=  '&' + params;
        }
        var iframe_html = '<iframe id="Iframe'+container+'" frameborder="0"';

        width = jQuery('#' + container).width();
        height = jQuery('#' + container).height();

        if(width == 0)
            width = '100%';
        else
            width = width + 'px';

        if(height == 0)
            height = '100%';
        else
            height = height + 'px';

        iframe_html += 'style="overflow-x:hidden;overflow-y:auto;background:none;width: '+width+';';
        iframe_html += 'height: '+height+';" ';
        iframe_html += 'onload="" src="'+src+'" hspace="0">';

        if(typeof jQuery('#Iframe'+container).attr('id') == 'undefined'){
            jQuery('div#' + container).append(iframe_html);
        }else{
            jQuery('iframe#Iframe' + container).attr('src', src);
        }

        // ajustando las dimensiones del iframe para que se ajuste al contenedor
        jQuery('#Iframe'+container).load(function(){
           //this.style.height = this.contentWindow.document.body.offsetHeight + 'px';
           var getBodyHeight = this.contentWindow.document.body.offsetHeight;
           if(getBodyHeight == 0){
               getBodyHeight = 500;// de por mientras
           }

           getBodyHeight = getBodyHeight + 20;
           jQuery(this).height(getBodyHeight + 'px');
        });

    },

    /**
     * redimensiona un iframe para ocupar todo el alto posible
     */
    redimensionarIframe: function(container){
           var iframebody;
           var myiframe = jQuery('#Iframe'+container);
           var getBodyHeight = 500; // default

           if (myiframe.get(0).contentDocument) {
			iframebody = jQuery(myiframe.get(0).contentDocument.body);
		} else {
			iframebody = jQuery(myiframe.get(0).contentWindow.document.body);
		}


           getBodyHeight = iframebody.height() + 35;

           if(getBodyHeight > 35){
               jQuery('#Iframe'+container).css('overflow-x', 'hidden');
           }

           jQuery('#Iframe'+container).height(getBodyHeight + 'px');
    }




}


/**
 * esta clase procesa los mensajes provenientes
 * de las acciones del framework de una forma mas clara,
 * e intuitiva
 *
 * @author Oscar Añón (nova)
 */
orion.messages = {

    /**
     * tiempo que se mantiene el cartelito por defecto
     */
    showtime : 8000,

    /**
     * despliego un mensaje en un div de forma rapida, a partir de la
     * respuesta de una accion que regresa un json (message,error)
     * @param response objeto JSON con (message(text) y error(0,1))
     * @param container div donde desplegar el mensaje, sino se despliega en el
     * div showResponseMessages del layout base
     * @param hiddetime oculta el mensaje luego de un tiempo
     */
    show: function(response,container,hiddetime){

        if(typeof hiddetime == 'undefined'){
            hiddetime = this.showtime;
        }

        if(typeof container == 'undefined'){
            container = 'showResponseMessages';//default

            var c = jQuery('#showResponseMessages').attr('id');
            if(typeof c == 'undefined'){

                var respDiv = '<div style="position: fixed;top: 200px;font-size:12px;">'
                + '<div id="showResponseMessages" style="width:200px;height:50px;display:none;z-index: 1004;font-size:12px;"></div>'
                + '</div>';

                jQuery('body').append(respDiv);
            }

        }

        var error = 0;
        var message = 'error desconocido';

        /* parche legacy para soportar las dos formas de procesar errores */
        var errors = 'errors' in response? response.errors : "";
        var notice = 'errors' in response? response.notice : "";

        if(errors.length > 0){
            error = 1;
            message = '';
            message += response.errors[0] + '. ' + "<br />\n";
        }

        if(notice.length > 0){
            message = '';
            message += response.notice[0] + '. ' + "<br />\n";
        }
        /* fin del parche */

        if(typeof response.error != 'undefined'){
            error = response.error;
        }
        if(typeof response.message != 'undefined'){
            message = response.message;
        }

        jQuery('#' + container).css('z-index', 1004);

        var mensajero = '';

        var mensajero_error = '<div style="padding: 0pt 0.7em;" class="ui-state-error ui-corner-all">';
        mensajero_error += '<p><span style="float: left; margin-right: 0.3em;" class="ui-icon ui-icon-alert"></span>';
        mensajero_error += '<strong>Notificación:</strong> <span id="Message'+container+'">'+message+'</span> </p>';
        mensajero_error += '</div>';

        var mensajero_aviso = '<div style="padding: 0pt 0.7em;" class="ui-state-highlight ui-corner-all">';
        mensajero_aviso += '<p><span style="float: left; margin-right: 0.3em;" class="ui-icon ui-icon-alert"></span>';
        mensajero_aviso += '<strong>Notificación:</strong> <span id="Message'+container+'">'+message+'</span> </p>';
        mensajero_aviso += '</div>';

        if(error == 0){
            mensajero = mensajero_aviso;
        }else{
            mensajero = mensajero_error;
        }

        // removemos el contenido del mensajero
        jQuery("#" + container).html('');

        if(typeof jQuery('#Message'+container).attr('id') == 'undefined'){
            jQuery('#' + container).append(mensajero);
        }

        jQuery("#" + container).show('slide',{},500,this._hidden(container,hiddetime));
    },

    /**
     * apago el div despues de un tiempo
     */
    _hidden: function(container,hiddetime){
        setTimeout(function(){
            jQuery("#"+container+":visible").removeAttr('style').hide().fadeOut();
        }, hiddetime);
    }


}
/**** SiteUsersOnline ****/
function SiteUsersOnline_status_call(uid){
	//alert(uid);
	var url='/Add-ons/complements/SiteUsersOnLine/action_online_user_get?uid=' + uid;
		makeHttpRequest(url,'SiteUsersOnline_status_action');
}

function SiteUsersOnline_status_action(data){
	icono = document.getElementById('ONLINE_STATUS');
	if(data == 1){
	icono.src = '/themes/default/images/es/imagenesprueba/iconossolos/48/conectado.png';
	}else{
	icono.src = '/themes/default/images/es/imagenesprueba/iconossolos/48/desconectado.png';
	}
}

/**
chequea cada 60 segundos si el usuario esta online
*/
function SiteUsersOnline_check_clock(uid){
	//rec_uid = document.getElementById(element_uid).value;
	Onuid = uid;
	setInterval("SiteUsersOnline_status_call(Onuid)",60000);
}

// mantiene el estado online del usuario
function SiteUsersOnline_set_call(){
	//alert(uid);
	var url='/Add-ons/complements/SiteUsersOnLine/action_online_user_set';
		makeHttpRequest(url);
}

function SiteUsersOnline_set_clock(){
	setInterval("SiteUsersOnline_set_call()",60000);
}


function UsersDelete_call(uid){
	var url='/Add-ons/complements/SiteUsersActions/action_users_delete?uid=' + uid;
	if(confirm('SiteUsers: Confirmacion de Borrado: ') == true){
		var tabla = document.getElementById('tablita');
		var fila = document.getElementById('field' + uid);
		tabla.removeChild(fila);
		makeHttpRequest(url);
	}
}
/********** obtengo los mensajes de la charla actual entre los usuarios **********/
function MessageBoard_check_call(uid){
	var url='/Add-ons/complements/MessageBoard_cpls/chat_show?uid=' + uid;
	// show_div_01 - es seteado en efects.js
	if(show_div_01 == 1){
		makeHttpRequest(url,'MessageBoard_check_action');
	}
}

function MessageBoard_check_action(data){
	var mensajesenviados = document.getElementById('mensajesenviados');
		mensajesenviados.innerHTML = data;
		DivScrolltoBottom('mensajesenviados');
}

/**
refresca la ventana de charla cada 10 segundos
*/
function MessageBoard_check_clock(element_uid){
	rec_uid = document.getElementById(element_uid).value;
	setInterval("MessageBoard_check_call(rec_uid)",10000);
}

// control de mensajes
function MessageBoard_close_call(chatid,tb,tr){
	//var url='/Actions/action_close_chat?chatid=' + chatid;
	var url='/Add-ons/complements/MessageBoard_cpls/action_close_chat?chatid=' + chatid;

	if(confirm('Confirmacion de Cerrado: ') == true){
		eliminar_tr(tb,tr);
		makeHttpRequest(url,'MessageBoard_close_action');
	}
}

function MessageBoard_close_action(data){
	var algo = data;
}

function MessageBoard_ban_call(chatid,tb,tr){
	var url='/Add-ons/complements/MessageBoard_cpls/action_ban_chat?chatid=' + chatid;
	if(confirm('Atencion esta accion es permanente no podras comunicarte mas con el participante!!!: ') == true){
		eliminar_tr(tb,tr);
		makeHttpRequest(url);
	}
}


/**
* funcion que se utiliza en conjunto con el metodo
* ExtendedForm::form_date_select_gen de las extensiones de Orion
* @param {string} element
*/
function magic_date(element){
	var elemento = document.getElementById(element);
	var m_day = document.getElementById('m_day');
	var m_month = document.getElementById('m_month');
	var m_year = document.getElementById('m_year');
	elemento.value = m_year.value + '-' + m_month.value + '-' + m_day.value;
}

/**
* funcion que se utiliza en conjunto con el metodo
* ExtendedForm::form_datetime_select_gen de las extensiones de Orion
* @param {string} element
* @param {string} prefix
*/
function ExtendedForm_date_time(element,prefix){
	var elemento = document.getElementById(element);

	var d = document.getElementById(prefix + '_day').value;
	var m = document.getElementById(prefix + '_month').value;
	var Y = document.getElementById(prefix + '_year').value;

	var H = document.getElementById(prefix + '_hora').value;
	var i = document.getElementById(prefix + '_min').value;
	var s = document.getElementById(prefix + '_seg').value;

	elemento.value = Y + '-' + m + '-' + d + ' ' + H + ':' + i + ':' + s;
}

/**
* esta funcion captura las acciones de los select con botonera y las ejecuta
* pasandoles los argumentos.
*
* @param {string} select_id
* @param {string} act
*/
function ExtendedForm_ayax_select(select_id,act, url){
	if(function_exists(select_id + '_' + act)){
		eval(select_id + '_' + act + "('"+ select_id +"','" + act + "','" + url + "')");
	}else{
		alert('no se ha definido una funcion:' + select_id + '_' + act + '(select_id,action)');
	}

}

/**
 * flor de funcion, jeje
 * esta funcion es parte de la extension ExtendedForm y es utilizada para automatizar 
 * la creacion de los select con barra de acciones.
 * @param {Object} selid
 * @param {Object} act
 * @param {Object} url
 */
function ExtendedForm_ayax_select_fast(selid, act, url){

	//alert(url);

	if (act == 'add'){
		var FieldName;
		var selector = document.getElementById(selid);
		
		var titulo = selector.title;
		
		if (FieldName = prompt('- '+titulo+' -', '[ new '+titulo+' ]')) {
			//alert(nombre);

			$.get(url, {
				action: "add",
				FieldName: FieldName
			}, function(data){
				//alert("Data Loaded: " + data);
				selector.innerHTML = data;
			});
		}
	}

	if (act == 'del'){
		var selector = document.getElementById(selid);selid
		var selected = Key_from_select(selid);
		var Field = Value_from_select(selid);

		if (confirm('confirmar borrado de ' + Field)) {
			$.get(url, {
				action: "del",
				FieldID: selected
			}, function(data){
				//alert("Data Loaded: " + data);
				selector.innerHTML = data;
			});
		}
	}

}



/**
 * Orion Setup
 * script para inicializar variables y objetos comunes a todos
 * los sistemas
 * autor: Oscar Añón
 */
var historyobj = {
    'checkobject':'ok'
};

orion.history.mode = 'test';

// por compativilidad
$.historyLoad = function(ddf){
    alert(ddf);
};

$(document).ready( function() {

    // cargo los eventos XHR para que funcionen las cargas ajax dinamicas
    //orion_xhr.preload();
    orion.xhr.preload_test();

    // formularios de carga normal
    orion_ajax_forms();

    $("body").ajaxSuccess(function(evt, request, settings){
        //$(this).append("<li>Request: " +settings.url+"</li>");
        //$(this).append("<li>Request: " +settings.dataType+"</li>"); //tipo de dato
        //$(this).append("<li>Request: " +settings.data+"</li>");// parametros

        if(settings.dataType == 'html'){
            // transformo la request en html
            //data = jQuery.httpData(request,settings.dataType)// deprecated
            //$(this).append(data);
        }

    });

    // settings condicionales
    if(orion.history.enable == 1){
        //$.historyInit(orion.history.pageload);

        $(window).hashchange( function(){
            // Alerts every time the hash changes!
            //alert( location.hash );
            var url = location.hash;
            var target = orion.history.main;
            var data = {
                orionload : 1
            };

            url = url.replace('#', '');
            var match1 = url.match(/^\//);
            var match2 = url.match(/^http[s]?[:]/);
            var checksum = $.md5(url);

            orion.history.checksum = checksum;
            
            if(url.length > 0 && (match1 || match2) ){
                //alert(url);
                $('#' + target).showloading();
                $('#' + target).load(url, data, function(){
                    orion.xhr.preload_test();
                    orion.history.callback.call();
                    orion.history.callback = function(){};
                    orion.xhr.storeMap(url, target, data, orion.history.callback);
                    $(this).showloading('remove');
                });
            }
        })
        // Trigger the event (useful on page load).
        $(window).hashchange();
    }

} );


