/*
 * jQuery 1.2.4 - New Wave Javascript
 *
 * Copyright (c) 2008 John Resig (jquery.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * $Date: 2008-05-18 23:05:38 -0400 (Sun, 18 May 2008) $
 * $Rev: 5631 $
 */
(function(){if(window.jQuery)var _jQuery=window.jQuery;var jQuery=window.jQuery=function(selector,context){return new jQuery.prototype.init(selector,context);};if(window.$)var _$=window.$;window.$=jQuery;var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/;var isSimple=/^.[^:#\[\.]*$/;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(selector.nodeType){this[0]=selector;this.length=1;return this;}else if(typeof selector=="string"){var match=quickExpr.exec(selector);if(match&&(match[1]||!context)){if(match[1])selector=jQuery.clean([match[1]],context);else{var elem=document.getElementById(match[3]);if(elem)if(elem.id!=match[3])return jQuery().find(selector);else{this[0]=elem;this.length=1;return this;}else
selector=[];}}else
return new jQuery(context).find(selector);}else if(jQuery.isFunction(selector))return new jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(selector.constructor==Array&&selector||(selector.jquery||selector.length&&selector!=window&&!selector.nodeType&&selector[0]!=undefined&&selector[0].nodeType)&&jQuery.makeArray(selector)||[selector]);},jquery:"1.2.4",size:function(){return this.length;},length:0,get:function(num){return num==undefined?jQuery.makeArray(this):this[num];},pushStack:function(elems){var ret=jQuery(elems);ret.prevObject=this;return ret;},setArray:function(elems){this.length=0;Array.prototype.push.apply(this,elems);return this;},each:function(callback,args){return jQuery.each(this,callback,args);},index:function(elem){var ret=-1;this.each(function(i){if(this==elem)ret=i;});return ret;},attr:function(name,value,type){var options=name;if(name.constructor==String)if(value==undefined)return this.length&&jQuery[type||"attr"](this[0],name)||undefined;else{options={};options[name]=value;}return this.each(function(i){for(name in options)jQuery.attr(type?this.style:this,name,jQuery.prop(this,options[name],type,i,name));});},css:function(key,value){if((key=='width'||key=='height')&&parseFloat(value)<0)value=undefined;return this.attr(key,value,"curCSS");},text:function(text){if(typeof text!="object"&&text!=null)return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(text));var ret="";jQuery.each(text||this,function(){jQuery.each(this.childNodes,function(){if(this.nodeType!=8)ret+=this.nodeType!=1?this.nodeValue:jQuery.fn.text([this]);});});return ret;},wrapAll:function(html){if(this[0])jQuery(html,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var elem=this;while(elem.firstChild)elem=elem.firstChild;return elem;}).append(this);return this;},wrapInner:function(html){return this.each(function(){jQuery(this).contents().wrapAll(html);});},wrap:function(html){return this.each(function(){jQuery(this).wrapAll(html);});},append:function(){return this.domManip(arguments,true,false,function(elem){if(this.nodeType==1)this.appendChild(elem);});},prepend:function(){return this.domManip(arguments,true,true,function(elem){if(this.nodeType==1)this.insertBefore(elem,this.firstChild);});},before:function(){return this.domManip(arguments,false,false,function(elem){this.parentNode.insertBefore(elem,this);});},after:function(){return this.domManip(arguments,false,true,function(elem){this.parentNode.insertBefore(elem,this.nextSibling);});},end:function(){return this.prevObject||jQuery([]);},find:function(selector){var elems=jQuery.map(this,function(elem){return jQuery.find(selector,elem);});return this.pushStack(/[^+>] [^+>]/.test(selector)||selector.indexOf("..")>-1?jQuery.unique(elems):elems);},clone:function(events){var ret=this.map(function(){if(jQuery.browser.msie&&!jQuery.isXMLDoc(this)){var clone=this.cloneNode(true),container=document.createElement("div");container.appendChild(clone);return jQuery.clean([container.innerHTML])[0];}else
return this.cloneNode(true);});var clone=ret.find("*").andSelf().each(function(){if(this[expando]!=undefined)this[expando]=null;});if(events===true)this.find("*").andSelf().each(function(i){if(this.nodeType==3)return;var events=jQuery.data(this,"events");for(var type in events)for(var handler in events[type])jQuery.event.add(clone[i],type,events[type][handler],events[type][handler].data);});return ret;},filter:function(selector){return this.pushStack(jQuery.isFunction(selector)&&jQuery.grep(this,function(elem,i){return selector.call(elem,i);})||jQuery.multiFilter(selector,this));},not:function(selector){if(selector.constructor==String)if(isSimple.test(selector))return this.pushStack(jQuery.multiFilter(selector,this,true));else
selector=jQuery.multiFilter(selector,this);var isArrayLike=selector.length&&selector[selector.length-1]!==undefined&&!selector.nodeType;return this.filter(function(){return isArrayLike?jQuery.inArray(this,selector)<0:this!=selector;});},add:function(selector){return!selector?this:this.pushStack(jQuery.merge(this.get(),selector.constructor==String?jQuery(selector).get():selector.length!=undefined&&(!selector.nodeName||jQuery.nodeName(selector,"form"))?selector:[selector]));},is:function(selector){return selector?jQuery.multiFilter(selector,this).length>0:false;},hasClass:function(selector){return this.is("."+selector);},val:function(value){if(value==undefined){if(this.length){var elem=this[0];if(jQuery.nodeName(elem,"select")){var index=elem.selectedIndex,values=[],options=elem.options,one=elem.type=="select-one";if(index<0)return null;for(var i=one?index:0,max=one?index+1:options.length;i<max;i++){var option=options[i];if(option.selected){value=jQuery.browser.msie&&!option.attributes.value.specified?option.text:option.value;if(one)return value;values.push(value);}}return values;}else
return(this[0].value||"").replace(/\r/g,"");}return undefined;}return this.each(function(){if(this.nodeType!=1)return;if(value.constructor==Array&&/radio|checkbox/.test(this.type))this.checked=(jQuery.inArray(this.value,value)>=0||jQuery.inArray(this.name,value)>=0);else if(jQuery.nodeName(this,"select")){var values=value.constructor==Array?value:[value];jQuery("option",this).each(function(){this.selected=(jQuery.inArray(this.value,values)>=0||jQuery.inArray(this.text,values)>=0);});if(!values.length)this.selectedIndex=-1;}else
this.value=value;});},html:function(value){return value==undefined?(this.length?this[0].innerHTML:null):this.empty().append(value);},replaceWith:function(value){return this.after(value).remove();},eq:function(i){return this.slice(i,i+1);},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem);}));},andSelf:function(){return this.add(this.prevObject);},data:function(key,value){var parts=key.split(".");parts[1]=parts[1]?"."+parts[1]:"";if(value==null){var data=this.triggerHandler("getData"+parts[1]+"!",[parts[0]]);if(data==undefined&&this.length)data=jQuery.data(this[0],key);return data==null&&parts[1]?this.data(parts[0]):data;}else
return this.trigger("setData"+parts[1]+"!",[parts[0],value]).each(function(){jQuery.data(this,key,value);});},removeData:function(key){return this.each(function(){jQuery.removeData(this,key);});},domManip:function(args,table,reverse,callback){var clone=this.length>1,elems;return this.each(function(){if(!elems){elems=jQuery.clean(args,this.ownerDocument);if(reverse)elems.reverse();}var obj=this;if(table&&jQuery.nodeName(this,"table")&&jQuery.nodeName(elems[0],"tr"))obj=this.getElementsByTagName("tbody")[0]||this.appendChild(this.ownerDocument.createElement("tbody"));var scripts=jQuery([]);jQuery.each(elems,function(){var elem=clone?jQuery(this).clone(true)[0]:this;if(jQuery.nodeName(elem,"script")){scripts=scripts.add(elem);}else{if(elem.nodeType==1)scripts=scripts.add(jQuery("script",elem).remove());callback.call(obj,elem);}});scripts.each(evalScript);});}};jQuery.prototype.init.prototype=jQuery.prototype;function evalScript(i,elem){if(elem.src)jQuery.ajax({url:elem.src,async:false,dataType:"script"});else
jQuery.globalEval(elem.text||elem.textContent||elem.innerHTML||"");if(elem.parentNode)elem.parentNode.removeChild(elem);}jQuery.extend=jQuery.fn.extend=function(){var target=arguments[0]||{},i=1,length=arguments.length,deep=false,options;if(target.constructor==Boolean){deep=target;target=arguments[1]||{};i=2;}if(typeof target!="object"&&typeof target!="function")target={};if(length==1){target=this;i=0;}for(;i<length;i++)if((options=arguments[i])!=null)for(var name in options){if(target===options[name])continue;if(deep&&options[name]&&typeof options[name]=="object"&&target[name]&&!options[name].nodeType)target[name]=jQuery.extend(deep,target[name],options[name]);else if(options[name]!=undefined)target[name]=options[name];}return target;};var expando="jQuery"+(new Date()).getTime(),uuid=0,windowData={};var exclude=/z-?index|font-?weight|opacity|zoom|line-?height/i;jQuery.extend({noConflict:function(deep){window.$=_$;if(deep)window.jQuery=_jQuery;return jQuery;},isFunction:function(fn){return!!fn&&typeof fn!="string"&&!fn.nodeName&&fn.constructor!=Array&&/function/i.test(fn+"");},isXMLDoc:function(elem){return elem.documentElement&&!elem.body||elem.tagName&&elem.ownerDocument&&!elem.ownerDocument.body;},globalEval:function(data){data=jQuery.trim(data);if(data){var head=document.getElementsByTagName("head")[0]||document.documentElement,script=document.createElement("script");script.type="text/javascript";if(jQuery.browser.msie)script.text=data;else
script.appendChild(document.createTextNode(data));head.appendChild(script);head.removeChild(script);}},nodeName:function(elem,name){return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();},cache:{},data:function(elem,name,data){elem=elem==window?windowData:elem;var id=elem[expando];if(!id)id=elem[expando]=++uuid;if(name&&!jQuery.cache[id])jQuery.cache[id]={};if(data!=undefined)jQuery.cache[id][name]=data;return name?jQuery.cache[id][name]:id;},removeData:function(elem,name){elem=elem==window?windowData:elem;var id=elem[expando];if(name){if(jQuery.cache[id]){delete jQuery.cache[id][name];name="";for(name in jQuery.cache[id])break;if(!name)jQuery.removeData(elem);}}else{try{delete elem[expando];}catch(e){if(elem.removeAttribute)elem.removeAttribute(expando);}delete jQuery.cache[id];}},each:function(object,callback,args){if(args){if(object.length==undefined){for(var name in object)if(callback.apply(object[name],args)===false)break;}else
for(var i=0,length=object.length;i<length;i++)if(callback.apply(object[i],args)===false)break;}else{if(object.length==undefined){for(var name in object)if(callback.call(object[name],name,object[name])===false)break;}else
for(var i=0,length=object.length,value=object[0];i<length&&callback.call(value,i,value)!==false;value=object[++i]){}}return object;},prop:function(elem,value,type,i,name){if(jQuery.isFunction(value))value=value.call(elem,i);return value&&value.constructor==Number&&type=="curCSS"&&!exclude.test(name)?value+"px":value;},className:{add:function(elem,classNames){jQuery.each((classNames||"").split(/\s+/),function(i,className){if(elem.nodeType==1&&!jQuery.className.has(elem.className,className))elem.className+=(elem.className?" ":"")+className;});},remove:function(elem,classNames){if(elem.nodeType==1)elem.className=classNames!=undefined?jQuery.grep(elem.className.split(/\s+/),function(className){return!jQuery.className.has(classNames,className);}).join(" "):"";},has:function(elem,className){return jQuery.inArray(className,(elem.className||elem).toString().split(/\s+/))>-1;}},swap:function(elem,options,callback){var old={};for(var name in options){old[name]=elem.style[name];elem.style[name]=options[name];}callback.call(elem);for(var name in options)elem.style[name]=old[name];},css:function(elem,name,force){if(name=="width"||name=="height"){var val,props={position:"absolute",visibility:"hidden",display:"block"},which=name=="width"?["Left","Right"]:["Top","Bottom"];function getWH(){val=name=="width"?elem.offsetWidth:elem.offsetHeight;var padding=0,border=0;jQuery.each(which,function(){padding+=parseFloat(jQuery.curCSS(elem,"padding"+this,true))||0;border+=parseFloat(jQuery.curCSS(elem,"border"+this+"Width",true))||0;});val-=Math.round(padding+border);}if(jQuery(elem).is(":visible"))getWH();else
jQuery.swap(elem,props,getWH);return Math.max(0,val);}return jQuery.curCSS(elem,name,force);},curCSS:function(elem,name,force){var ret;function color(elem){if(!jQuery.browser.safari)return false;var ret=document.defaultView.getComputedStyle(elem,null);return!ret||ret.getPropertyValue("color")=="";}if(name=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(elem.style,"opacity");return ret==""?"1":ret;}if(jQuery.browser.opera&&name=="display"){var save=elem.style.outline;elem.style.outline="0 solid black";elem.style.outline=save;}if(name.match(/float/i))name=styleFloat;if(!force&&elem.style&&elem.style[name])ret=elem.style[name];else if(document.defaultView&&document.defaultView.getComputedStyle){if(name.match(/float/i))name="float";name=name.replace(/([A-Z])/g,"-$1").toLowerCase();var getComputedStyle=document.defaultView.getComputedStyle(elem,null);if(getComputedStyle&&!color(elem))ret=getComputedStyle.getPropertyValue(name);else{var swap=[],stack=[];for(var a=elem;a&&color(a);a=a.parentNode)stack.unshift(a);for(var i=0;i<stack.length;i++)if(color(stack[i])){swap[i]=stack[i].style.display;stack[i].style.display="block";}ret=name=="display"&&swap[stack.length-1]!=null?"none":(getComputedStyle&&getComputedStyle.getPropertyValue(name))||"";for(var i=0;i<swap.length;i++)if(swap[i]!=null)stack[i].style.display=swap[i];}if(name=="opacity"&&ret=="")ret="1";}else if(elem.currentStyle){var camelCase=name.replace(/\-(\w)/g,function(all,letter){return letter.toUpperCase();});ret=elem.currentStyle[name]||elem.currentStyle[camelCase];if(!/^\d+(px)?$/i.test(ret)&&/^\d/.test(ret)){var style=elem.style.left,runtimeStyle=elem.runtimeStyle.left;elem.runtimeStyle.left=elem.currentStyle.left;elem.style.left=ret||0;ret=elem.style.pixelLeft+"px";elem.style.left=style;elem.runtimeStyle.left=runtimeStyle;}}return ret;},clean:function(elems,context){var ret=[];context=context||document;if(typeof context.createElement=='undefined')context=context.ownerDocument||context[0]&&context[0].ownerDocument||document;jQuery.each(elems,function(i,elem){if(!elem)return;if(elem.constructor==Number)elem=elem.toString();if(typeof elem=="string"){elem=elem.replace(/(<(\w+)[^>]*?)\/>/g,function(all,front,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?all:front+"></"+tag+">";});var tags=jQuery.trim(elem).toLowerCase(),div=context.createElement("div");var wrap=!tags.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!tags.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||tags.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!tags.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!tags.indexOf("<td")||!tags.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!tags.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||jQuery.browser.msie&&[1,"div<div>","</div>"]||[0,"",""];div.innerHTML=wrap[1]+elem+wrap[2];while(wrap[0]--)div=div.lastChild;if(jQuery.browser.msie){var tbody=!tags.indexOf("<table")&&tags.indexOf("<tbody")<0?div.firstChild&&div.firstChild.childNodes:wrap[1]=="<table>"&&tags.indexOf("<tbody")<0?div.childNodes:[];for(var j=tbody.length-1;j>=0;--j)if(jQuery.nodeName(tbody[j],"tbody")&&!tbody[j].childNodes.length)tbody[j].parentNode.removeChild(tbody[j]);if(/^\s/.test(elem))div.insertBefore(context.createTextNode(elem.match(/^\s*/)[0]),div.firstChild);}elem=jQuery.makeArray(div.childNodes);}if(elem.length===0&&(!jQuery.nodeName(elem,"form")&&!jQuery.nodeName(elem,"select")))return;if(elem[0]==undefined||jQuery.nodeName(elem,"form")||elem.options)ret.push(elem);else
ret=jQuery.merge(ret,elem);});return ret;},attr:function(elem,name,value){if(!elem||elem.nodeType==3||elem.nodeType==8)return undefined;var fix=jQuery.isXMLDoc(elem)?{}:jQuery.props;if(name=="selected"&&jQuery.browser.safari)elem.parentNode.selectedIndex;if(fix[name]){if(value!=undefined)elem[fix[name]]=value;return elem[fix[name]];}else if(jQuery.browser.msie&&name=="style")return jQuery.attr(elem.style,"cssText",value);else if(value==undefined&&jQuery.browser.msie&&jQuery.nodeName(elem,"form")&&(name=="action"||name=="method"))return elem.getAttributeNode(name).nodeValue;else if(elem.tagName){if(value!=undefined){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)throw"type property can't be changed";elem.setAttribute(name,""+value);}if(jQuery.browser.msie&&/href|src/.test(name)&&!jQuery.isXMLDoc(elem))return elem.getAttribute(name,2);return elem.getAttribute(name);}else{if(name=="opacity"&&jQuery.browser.msie){if(value!=undefined){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseFloat(value).toString()=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter&&elem.filter.indexOf("opacity=")>=0?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100).toString():"";}name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});if(value!=undefined)elem[name]=value;return elem[name];}},trim:function(text){return(text||"").replace(/^\s+|\s+$/g,"");},makeArray:function(array){var ret=[];if(array.constructor!=Array)for(var i=0,length=array.length;i<length;i++)ret.push(array[i]);else
ret=array.slice(0);return ret;},inArray:function(elem,array){for(var i=0,length=array.length;i<length;i++)if(array[i]==elem)return i;return-1;},merge:function(first,second){if(jQuery.browser.msie){for(var i=0;second[i];i++)if(second[i].nodeType!=8)first.push(second[i]);}else
for(var i=0;second[i];i++)first.push(second[i]);return first;},unique:function(array){var ret=[],done={};try{for(var i=0,length=array.length;i<length;i++){var id=jQuery.data(array[i]);if(!done[id]){done[id]=true;ret.push(array[i]);}}}catch(e){ret=array;}return ret;},grep:function(elems,callback,inv){var ret=[];for(var i=0,length=elems.length;i<length;i++)if(!inv&&callback(elems[i],i)||inv&&!callback(elems[i],i))ret.push(elems[i]);return ret;},map:function(elems,callback){var ret=[];for(var i=0,length=elems.length;i<length;i++){var value=callback(elems[i],i);if(value!==null&&value!=undefined){if(value.constructor!=Array)value=[value];ret=ret.concat(value);}}return ret;}});var userAgent=navigator.userAgent.toLowerCase();jQuery.browser={version:(userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[])[1],safari:/webkit/.test(userAgent),opera:/opera/.test(userAgent),msie:/msie/.test(userAgent)&&!/opera/.test(userAgent),mozilla:/mozilla/.test(userAgent)&&!/(compatible|webkit)/.test(userAgent)};var styleFloat=jQuery.browser.msie?"styleFloat":"cssFloat";jQuery.extend({boxModel:!jQuery.browser.msie||document.compatMode=="CSS1Compat",props:{"for":"htmlFor","class":"className","float":styleFloat,cssFloat:styleFloat,styleFloat:styleFloat,innerHTML:"innerHTML",className:"className",value:"value",disabled:"disabled",checked:"checked",readonly:"readOnly",selected:"selected",maxlength:"maxLength",selectedIndex:"selectedIndex",defaultValue:"defaultValue",tagName:"tagName",nodeName:"nodeName"}});jQuery.each({parent:function(elem){return elem.parentNode;},parents:function(elem){return jQuery.dir(elem,"parentNode");},next:function(elem){return jQuery.nth(elem,2,"nextSibling");},prev:function(elem){return jQuery.nth(elem,2,"previousSibling");},nextAll:function(elem){return jQuery.dir(elem,"nextSibling");},prevAll:function(elem){return jQuery.dir(elem,"previousSibling");},siblings:function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},children:function(elem){return jQuery.sibling(elem.firstChild);},contents:function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}},function(name,fn){jQuery.fn[name]=function(selector){var ret=jQuery.map(this,fn);if(selector&&typeof selector=="string")ret=jQuery.multiFilter(selector,ret);return this.pushStack(jQuery.unique(ret));};});jQuery.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(name,original){jQuery.fn[name]=function(){var args=arguments;return this.each(function(){for(var i=0,length=args.length;i<length;i++)jQuery(args[i])[original](this);});};});jQuery.each({removeAttr:function(name){jQuery.attr(this,name,"");if(this.nodeType==1)this.removeAttribute(name);},addClass:function(classNames){jQuery.className.add(this,classNames);},removeClass:function(classNames){jQuery.className.remove(this,classNames);},toggleClass:function(classNames){jQuery.className[jQuery.className.has(this,classNames)?"remove":"add"](this,classNames);},remove:function(selector){if(!selector||jQuery.filter(selector,[this]).r.length){jQuery("*",this).add(this).each(function(){jQuery.event.remove(this);jQuery.removeData(this);});if(this.parentNode)this.parentNode.removeChild(this);}},empty:function(){jQuery(">*",this).remove();while(this.firstChild)this.removeChild(this.firstChild);}},function(name,fn){jQuery.fn[name]=function(){return this.each(fn,arguments);};});jQuery.each(["Height","Width"],function(i,name){var type=name.toLowerCase();jQuery.fn[type]=function(size){return this[0]==window?jQuery.browser.opera&&document.body["client"+name]||jQuery.browser.safari&&window["inner"+name]||document.compatMode=="CSS1Compat"&&document.documentElement["client"+name]||document.body["client"+name]:this[0]==document?Math.max(Math.max(document.body["scroll"+name],document.documentElement["scroll"+name]),Math.max(document.body["offset"+name],document.documentElement["offset"+name])):size==undefined?(this.length?jQuery.css(this[0],type):null):this.css(type,size.constructor==String?size:size+"px");};});var chars=jQuery.browser.safari&&parseInt(jQuery.browser.version)<417?"(?:[\\w*_-]|\\\\.)":"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",quickChild=new RegExp("^>\\s*("+chars+"+)"),quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)"),quickClass=new RegExp("^([#.]?)("+chars+"*)");jQuery.extend({expr:{"":function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},"#":function(a,i,m){return a.getAttribute("id")==m[2];},":":{lt:function(a,i,m){return i<m[3]-0;},gt:function(a,i,m){return i>m[3]-0;},nth:function(a,i,m){return m[3]-0==i;},eq:function(a,i,m){return m[3]-0==i;},first:function(a,i){return i==0;},last:function(a,i,m,r){return i==r.length-1;},even:function(a,i){return i%2==0;},odd:function(a,i){return i%2;},"first-child":function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},"last-child":function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},"only-child":function(a){return!jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},parent:function(a){return a.firstChild;},empty:function(a){return!a.firstChild;},contains:function(a,i,m){return(a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},visible:function(a){return"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},hidden:function(a){return"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},enabled:function(a){return!a.disabled;},disabled:function(a){return a.disabled;},checked:function(a){return a.checked;},selected:function(a){return a.selected||jQuery.attr(a,"selected");},text:function(a){return"text"==a.type;},radio:function(a){return"radio"==a.type;},checkbox:function(a){return"checkbox"==a.type;},file:function(a){return"file"==a.type;},password:function(a){return"password"==a.type;},submit:function(a){return"submit"==a.type;},image:function(a){return"image"==a.type;},reset:function(a){return"reset"==a.type;},button:function(a){return"button"==a.type||jQuery.nodeName(a,"button");},input:function(a){return/input|select|textarea|button/i.test(a.nodeName);},has:function(a,i,m){return jQuery.find(m[3],a).length;},header:function(a){return/h\d/i.test(a.nodeName);},animated:function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+chars+"+)")],multiFilter:function(expr,elems,not){var old,cur=[];while(expr&&expr!=old){old=expr;var f=jQuery.filter(expr,elems,not);expr=f.t.replace(/^\s*,\s*/,"");cur=not?elems=f.r:jQuery.merge(cur,f.r);}return cur;},find:function(t,context){if(typeof t!="string")return[t];if(context&&context.nodeType!=1&&context.nodeType!=9)return[];context=context||document;var ret=[context],done=[],last,nodeName;while(t&&last!=t){var r=[];last=t;t=jQuery.trim(t);var foundToken=false;var re=quickChild;var m=re.exec(t);if(m){nodeName=m[1].toUpperCase();for(var i=0;ret[i];i++)for(var c=ret[i].firstChild;c;c=c.nextSibling)if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName))r.push(c);ret=r;t=t.replace(re,"");if(t.indexOf(" ")==0)continue;foundToken=true;}else{re=/^([>+~])\s*(\w*)/i;if((m=re.exec(t))!=null){r=[];var merge={};nodeName=m[2].toUpperCase();m=m[1];for(var j=0,rl=ret.length;j<rl;j++){var n=m=="~"||m=="+"?ret[j].nextSibling:ret[j].firstChild;for(;n;n=n.nextSibling)if(n.nodeType==1){var id=jQuery.data(n);if(m=="~"&&merge[id])break;if(!nodeName||n.nodeName.toUpperCase()==nodeName){if(m=="~")merge[id]=true;r.push(n);}if(m=="+")break;}}ret=r;t=jQuery.trim(t.replace(re,""));foundToken=true;}}if(t&&!foundToken){if(!t.indexOf(",")){if(context==ret[0])ret.shift();done=jQuery.merge(done,ret);r=ret=[context];t=" "+t.substr(1,t.length);}else{var re2=quickID;var m=re2.exec(t);if(m){m=[0,m[2],m[3],m[1]];}else{re2=quickClass;m=re2.exec(t);}m[2]=m[2].replace(/\\/g,"");var elem=ret[ret.length-1];if(m[1]=="#"&&elem&&elem.getElementById&&!jQuery.isXMLDoc(elem)){var oid=elem.getElementById(m[2]);if((jQuery.browser.msie||jQuery.browser.opera)&&oid&&typeof oid.id=="string"&&oid.id!=m[2])oid=jQuery('[@id="'+m[2]+'"]',elem)[0];ret=r=oid&&(!m[3]||jQuery.nodeName(oid,m[3]))?[oid]:[];}else{for(var i=0;ret[i];i++){var tag=m[1]=="#"&&m[3]?m[3]:m[1]!=""||m[0]==""?"*":m[2];if(tag=="*"&&ret[i].nodeName.toLowerCase()=="object")tag="param";r=jQuery.merge(r,ret[i].getElementsByTagName(tag));}if(m[1]==".")r=jQuery.classFilter(r,m[2]);if(m[1]=="#"){var tmp=[];for(var i=0;r[i];i++)if(r[i].getAttribute("id")==m[2]){tmp=[r[i]];break;}r=tmp;}ret=r;}t=t.replace(re2,"");}}if(t){var val=jQuery.filter(t,r);ret=r=val.r;t=jQuery.trim(val.t);}}if(t)ret=[];if(ret&&context==ret[0])ret.shift();done=jQuery.merge(done,ret);return done;},classFilter:function(r,m,not){m=" "+m+" ";var tmp=[];for(var i=0;r[i];i++){var pass=(" "+r[i].className+" ").indexOf(m)>=0;if(!not&&pass||not&&!pass)tmp.push(r[i]);}return tmp;},filter:function(t,r,not){var last;while(t&&t!=last){last=t;var p=jQuery.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break;}}if(!m)break;if(m[1]==":"&&m[2]=="not")r=isSimple.test(m[3])?jQuery.filter(m[3],r,true).r:jQuery(r).not(m[3]);else if(m[1]==".")r=jQuery.classFilter(r,m[2],not);else if(m[1]=="["){var tmp=[],type=m[3];for(var i=0,rl=r.length;i<rl;i++){var a=r[i],z=a[jQuery.props[m[2]]||m[2]];if(z==null||/href|src|selected/.test(m[2]))z=jQuery.attr(a,m[2])||'';if((type==""&&!!z||type=="="&&z==m[5]||type=="!="&&z!=m[5]||type=="^="&&z&&!z.indexOf(m[5])||type=="$="&&z.substr(z.length-m[5].length)==m[5]||(type=="*="||type=="~=")&&z.indexOf(m[5])>=0)^not)tmp.push(a);}r=tmp;}else if(m[1]==":"&&m[2]=="nth-child"){var merge={},tmp=[],test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"0n+"+m[3]||m[3]),first=(test[1]+(test[2]||1))-0,last=test[3]-0;for(var i=0,rl=r.length;i<rl;i++){var node=r[i],parentNode=node.parentNode,id=jQuery.data(parentNode);if(!merge[id]){var c=1;for(var n=parentNode.firstChild;n;n=n.nextSibling)if(n.nodeType==1)n.nodeIndex=c++;merge[id]=true;}var add=false;if(first==0){if(node.nodeIndex==last)add=true;}else if((node.nodeIndex-last)%first==0&&(node.nodeIndex-last)/first>=0)add=true;if(add^not)tmp.push(node);}r=tmp;}else{var fn=jQuery.expr[m[1]];if(typeof fn=="object")fn=fn[m[2]];if(typeof fn=="string")fn=eval("false||function(a,i){return "+fn+";}");r=jQuery.grep(r,function(elem,i){return fn(elem,i,m,r);},not);}}return{r:r,t:t};},dir:function(elem,dir){var matched=[];var cur=elem[dir];while(cur&&cur!=document){if(cur.nodeType==1)matched.push(cur);cur=cur[dir];}return matched;},nth:function(cur,result,dir,elem){result=result||1;var num=0;for(;cur;cur=cur[dir])if(cur.nodeType==1&&++num==result)break;return cur;},sibling:function(n,elem){var r=[];for(;n;n=n.nextSibling){if(n.nodeType==1&&(!elem||n!=elem))r.push(n);}return r;}});jQuery.event={add:function(elem,types,handler,data){if(elem.nodeType==3||elem.nodeType==8)return;if(jQuery.browser.msie&&elem.setInterval!=undefined)elem=window;if(!handler.guid)handler.guid=this.guid++;if(data!=undefined){var fn=handler;handler=function(){return fn.apply(this,arguments);};handler.data=data;handler.guid=fn.guid;}var events=jQuery.data(elem,"events")||jQuery.data(elem,"events",{}),handle=jQuery.data(elem,"handle")||jQuery.data(elem,"handle",function(){var val;if(typeof jQuery=="undefined"||jQuery.event.triggered)return val;val=jQuery.event.handle.apply(arguments.callee.elem,arguments);return val;});handle.elem=elem;jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];handler.type=parts[1];var handlers=events[type];if(!handlers){handlers=events[type]={};if(!jQuery.event.special[type]||jQuery.event.special[type].setup.call(elem)===false){if(elem.addEventListener)elem.addEventListener(type,handle,false);else if(elem.attachEvent)elem.attachEvent("on"+type,handle);}}handlers[handler.guid]=handler;jQuery.event.global[type]=true;});elem=null;},guid:1,global:{},remove:function(elem,types,handler){if(elem.nodeType==3||elem.nodeType==8)return;var events=jQuery.data(elem,"events"),ret,index;if(events){if(types==undefined||(typeof types=="string"&&types.charAt(0)=="."))for(var type in events)this.remove(elem,type+(types||""));else{if(types.type){handler=types.handler;types=types.type;}jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];if(events[type]){if(handler)delete events[type][handler.guid];else
for(handler in events[type])if(!parts[1]||events[type][handler].type==parts[1])delete events[type][handler];for(ret in events[type])break;if(!ret){if(!jQuery.event.special[type]||jQuery.event.special[type].teardown.call(elem)===false){if(elem.removeEventListener)elem.removeEventListener(type,jQuery.data(elem,"handle"),false);else if(elem.detachEvent)elem.detachEvent("on"+type,jQuery.data(elem,"handle"));}ret=null;delete events[type];}}});}for(ret in events)break;if(!ret){var handle=jQuery.data(elem,"handle");if(handle)handle.elem=null;jQuery.removeData(elem,"events");jQuery.removeData(elem,"handle");}}},trigger:function(type,data,elem,donative,extra){data=jQuery.makeArray(data||[]);if(type.indexOf("!")>=0){type=type.slice(0,-1);var exclusive=true;}if(!elem){if(this.global[type])jQuery("*").add([window,document]).trigger(type,data);}else{if(elem.nodeType==3||elem.nodeType==8)return undefined;var val,ret,fn=jQuery.isFunction(elem[type]||null),event=!data[0]||!data[0].preventDefault;if(event)data.unshift(this.fix({type:type,target:elem}));data[0].type=type;if(exclusive)data[0].exclusive=true;if(jQuery.isFunction(jQuery.data(elem,"handle")))val=jQuery.data(elem,"handle").apply(elem,data);if(!fn&&elem["on"+type]&&elem["on"+type].apply(elem,data)===false)val=false;if(event)data.shift();if(extra&&jQuery.isFunction(extra)){ret=extra.apply(elem,val==null?data:data.concat(val));if(ret!==undefined)val=ret;}if(fn&&donative!==false&&val!==false&&!(jQuery.nodeName(elem,'a')&&type=="click")){this.triggered=true;try{elem[type]();}catch(e){}}this.triggered=false;}return val;},handle:function(event){var val;event=jQuery.event.fix(event||window.event||{});var parts=event.type.split(".");event.type=parts[0];var handlers=jQuery.data(this,"events")&&jQuery.data(this,"events")[event.type],args=Array.prototype.slice.call(arguments,1);args.unshift(event);for(var j in handlers){var handler=handlers[j];args[0].handler=handler;args[0].data=handler.data;if(!parts[1]&&!event.exclusive||handler.type==parts[1]){var ret=handler.apply(this,args);if(val!==false)val=ret;if(ret===false){event.preventDefault();event.stopPropagation();}}}if(jQuery.browser.msie)event.target=event.preventDefault=event.stopPropagation=event.handler=event.data=null;return val;},fix:function(event){var originalEvent=event;event=jQuery.extend({},originalEvent);event.preventDefault=function(){if(originalEvent.preventDefault)originalEvent.preventDefault();originalEvent.returnValue=false;};event.stopPropagation=function(){if(originalEvent.stopPropagation)originalEvent.stopPropagation();originalEvent.cancelBubble=true;};if(!event.target)event.target=event.srcElement||document;if(event.target.nodeType==3)event.target=originalEvent.target.parentNode;if(!event.relatedTarget&&event.fromElement)event.relatedTarget=event.fromElement==event.target?event.toElement:event.fromElement;if(event.pageX==null&&event.clientX!=null){var doc=document.documentElement,body=document.body;event.pageX=event.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc.clientLeft||0);event.pageY=event.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc.clientTop||0);}if(!event.which&&((event.charCode||event.charCode===0)?event.charCode:event.keyCode))event.which=event.charCode||event.keyCode;if(!event.metaKey&&event.ctrlKey)event.metaKey=event.ctrlKey;if(!event.which&&event.button)event.which=(event.button&1?1:(event.button&2?3:(event.button&4?2:0)));return event;},special:{ready:{setup:function(){bindReady();return;},teardown:function(){return;}},mouseenter:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseover",jQuery.event.special.mouseenter.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseover",jQuery.event.special.mouseenter.handler);return true;},handler:function(event){if(withinElement(event,this))return true;arguments[0].type="mouseenter";return jQuery.event.handle.apply(this,arguments);}},mouseleave:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseout",jQuery.event.special.mouseleave.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseout",jQuery.event.special.mouseleave.handler);return true;},handler:function(event){if(withinElement(event,this))return true;arguments[0].type="mouseleave";return jQuery.event.handle.apply(this,arguments);}}}};jQuery.fn.extend({bind:function(type,data,fn){return type=="unload"?this.one(type,data,fn):this.each(function(){jQuery.event.add(this,type,fn||data,fn&&data);});},one:function(type,data,fn){return this.each(function(){jQuery.event.add(this,type,function(event){jQuery(this).unbind(event);return(fn||data).apply(this,arguments);},fn&&data);});},unbind:function(type,fn){return this.each(function(){jQuery.event.remove(this,type,fn);});},trigger:function(type,data,fn){return this.each(function(){jQuery.event.trigger(type,data,this,true,fn);});},triggerHandler:function(type,data,fn){if(this[0])return jQuery.event.trigger(type,data,this[0],false,fn);return undefined;},toggle:function(){var args=arguments;return this.click(function(event){this.lastToggle=0==this.lastToggle?1:0;event.preventDefault();return args[this.lastToggle].apply(this,arguments)||false;});},hover:function(fnOver,fnOut){return this.bind('mouseenter',fnOver).bind('mouseleave',fnOut);},ready:function(fn){bindReady();if(jQuery.isReady)fn.call(document,jQuery);else
jQuery.readyList.push(function(){return fn.call(this,jQuery);});return this;}});jQuery.extend({isReady:false,readyList:[],ready:function(){if(!jQuery.isReady){jQuery.isReady=true;if(jQuery.readyList){jQuery.each(jQuery.readyList,function(){this.apply(document);});jQuery.readyList=null;}jQuery(document).triggerHandler("ready");}}});var readyBound=false;function bindReady(){if(readyBound)return;readyBound=true;if(document.addEventListener&&!jQuery.browser.opera)document.addEventListener("DOMContentLoaded",jQuery.ready,false);if(jQuery.browser.msie&&window==top)(function(){if(jQuery.isReady)return;try{document.documentElement.doScroll("left");}catch(error){setTimeout(arguments.callee,0);return;}jQuery.ready();})();if(jQuery.browser.opera)document.addEventListener("DOMContentLoaded",function(){if(jQuery.isReady)return;for(var i=0;i<document.styleSheets.length;i++)if(document.styleSheets[i].disabled){setTimeout(arguments.callee,0);return;}jQuery.ready();},false);if(jQuery.browser.safari){var numStyles;(function(){if(jQuery.isReady)return;if(document.readyState!="loaded"&&document.readyState!="complete"){setTimeout(arguments.callee,0);return;}if(numStyles===undefined)numStyles=jQuery("style, link[rel=stylesheet]").length;if(document.styleSheets.length!=numStyles){setTimeout(arguments.callee,0);return;}jQuery.ready();})();}jQuery.event.add(window,"load",jQuery.ready);}jQuery.each(("blur,focus,load,resize,scroll,unload,click,dblclick,"+"mousedown,mouseup,mousemove,mouseover,mouseout,change,select,"+"submit,keydown,keypress,keyup,error").split(","),function(i,name){jQuery.fn[name]=function(fn){return fn?this.bind(name,fn):this.trigger(name);};});var withinElement=function(event,elem){var parent=event.relatedTarget;while(parent&&parent!=elem)try{parent=parent.parentNode;}catch(error){parent=elem;}return parent==elem;};jQuery(window).bind("unload",function(){jQuery("*").add(document).unbind();});jQuery.fn.extend({load:function(url,params,callback){if(jQuery.isFunction(url))return this.bind("load",url);var off=url.indexOf(" ");if(off>=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}callback=callback||function(){};var type="GET";if(params)if(jQuery.isFunction(params)){callback=params;params=null;}else{params=jQuery.param(params);type="POST";}var self=this;jQuery.ajax({url:url,type:type,dataType:"html",data:params,complete:function(res,status){if(status=="success"||status=="notmodified")self.html(selector?jQuery("<div/>").append(res.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(selector):res.responseText);self.each(callback,[res.responseText,status,res]);}});return this;},serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){return jQuery.nodeName(this,"form")?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:val.constructor==Array?jQuery.map(val,function(val,i){return{name:elem.name,value:val};}):{name:elem.name,value:val};}).get();}});jQuery.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){jQuery.fn[o]=function(f){return this.bind(o,f);};});var jsc=(new Date).getTime();jQuery.extend({get:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data=null;}return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type});},getScript:function(url,callback){return jQuery.get(url,null,callback,"script");},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},post:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data={};}return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type});},ajaxSetup:function(settings){jQuery.extend(jQuery.ajaxSettings,settings);},ajaxSettings:{global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null,username:null,password:null,accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(s){var jsonp,jsre=/=\?(&|$)/g,status,data;s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));if(s.data&&s.processData&&typeof s.data!="string")s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(s.type.toLowerCase()=="get"){if(!s.url.match(jsre))s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?";}else if(!s.data||!s.data.match(jsre))s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";s.dataType="json";}if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){jsonp="jsonp"+jsc++;if(s.data)s.data=(s.data+"").replace(jsre,"="+jsonp+"$1");s.url=s.url.replace(jsre,"="+jsonp+"$1");s.dataType="script";window[jsonp]=function(tmp){data=tmp;success();complete();window[jsonp]=undefined;try{delete window[jsonp];}catch(e){}if(head)head.removeChild(script);};}if(s.dataType=="script"&&s.cache==null)s.cache=false;if(s.cache===false&&s.type.toLowerCase()=="get"){var ts=(new Date()).getTime();var ret=s.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+ts+"$2");s.url=ret+((ret==s.url)?(s.url.match(/\?/)?"&":"?")+"_="+ts:"");}if(s.data&&s.type.toLowerCase()=="get"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++)jQuery.event.trigger("ajaxStart");if((!s.url.indexOf("http")||!s.url.indexOf("//"))&&s.dataType=="script"&&s.type.toLowerCase()=="get"){var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=s.url;if(s.scriptCharset)script.charset=s.scriptCharset;if(!jsonp){var done=false;script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){done=true;success();complete();head.removeChild(script);}};}head.appendChild(script);return undefined;}var requestDone=false;var xml=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();xml.open(s.type,s.url,s.async,s.username,s.password);try{if(s.data)xml.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)xml.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xml.setRequestHeader("X-Requested-With","XMLHttpRequest");xml.setRequestHeader("Accept",s.dataType&&s.accepts[s.dataType]?s.accepts[s.dataType]+", */*":s.accepts._default);}catch(e){}if(s.beforeSend)s.beforeSend(xml);if(s.global)jQuery.event.trigger("ajaxSend",[xml,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xml&&(xml.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xml)&&"error"||s.ifModified&&jQuery.httpNotModified(xml,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xml,s.dataType);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xml.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes)jQuery.lastModified[s.url]=modRes;if(!jsonp)success();}else
jQuery.handleError(s,xml,status);complete();if(s.async)xml=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)setTimeout(function(){if(xml){xml.abort();if(!requestDone)onreadystatechange("timeout");}},s.timeout);}try{xml.send(s.data);}catch(e){jQuery.handleError(s,xml,null,e);}if(!s.async)onreadystatechange();function success(){if(s.success)s.success(data,status);if(s.global)jQuery.event.trigger("ajaxSuccess",[xml,s]);}function complete(){if(s.complete)s.complete(xml,status);if(s.global)jQuery.event.trigger("ajaxComplete",[xml,s]);if(s.global&&!--jQuery.active)jQuery.event.trigger("ajaxStop");}return xml;},handleError:function(s,xml,status,e){if(s.error)s.error(xml,status,e);if(s.global)jQuery.event.trigger("ajaxError",[xml,s,e]);},active:0,httpSuccess:function(r){try{return!r.status&&location.protocol=="file:"||(r.status>=200&&r.status<300)||r.status==304||r.status==1223||jQuery.browser.safari&&r.status==undefined;}catch(e){}return false;},httpNotModified:function(xml,url){try{var xmlRes=xml.getResponseHeader("Last-Modified");return xml.status==304||xmlRes==jQuery.lastModified[url]||jQuery.browser.safari&&xml.status==undefined;}catch(e){}return false;},httpData:function(r,type){var ct=r.getResponseHeader("content-type");var xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0;var data=xml?r.responseXML:r.responseText;if(xml&&data.documentElement.tagName=="parsererror")throw"parsererror";if(type=="script")jQuery.globalEval(data);if(type=="json")data=eval("("+data+")");return data;},param:function(a){var s=[];if(a.constructor==Array||a.jquery)jQuery.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value));});else
for(var j in a)if(a[j]&&a[j].constructor==Array)jQuery.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this));});else
s.push(encodeURIComponent(j)+"="+encodeURIComponent(a[j]));return s.join("&").replace(/%20/g,"+");}});jQuery.fn.extend({show:function(speed,callback){return speed?this.animate({height:"show",width:"show",opacity:"show"},speed,callback):this.filter(":hidden").each(function(){this.style.display=this.oldblock||"";if(jQuery.css(this,"display")=="none"){var elem=jQuery("<"+this.tagName+" />").appendTo("body");this.style.display=elem.css("display");if(this.style.display=="none")this.style.display="block";elem.remove();}}).end();},hide:function(speed,callback){return speed?this.animate({height:"hide",width:"hide",opacity:"hide"},speed,callback):this.filter(":visible").each(function(){this.oldblock=this.oldblock||jQuery.css(this,"display");this.style.display="none";}).end();},_toggle:jQuery.fn.toggle,toggle:function(fn,fn2){return jQuery.isFunction(fn)&&jQuery.isFunction(fn2)?this._toggle(fn,fn2):fn?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},fn,fn2):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();});},slideDown:function(speed,callback){return this.animate({height:"show"},speed,callback);},slideUp:function(speed,callback){return this.animate({height:"hide"},speed,callback);},slideToggle:function(speed,callback){return this.animate({height:"toggle"},speed,callback);},fadeIn:function(speed,callback){return this.animate({opacity:"show"},speed,callback);},fadeOut:function(speed,callback){return this.animate({opacity:"hide"},speed,callback);},fadeTo:function(speed,to,callback){return this.animate({opacity:to},speed,callback);},animate:function(prop,speed,easing,callback){var optall=jQuery.speed(speed,easing,callback);return this[optall.queue===false?"each":"queue"](function(){if(this.nodeType!=1)return false;var opt=jQuery.extend({},optall);var hidden=jQuery(this).is(":hidden"),self=this;for(var p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)return jQuery.isFunction(opt.complete)&&opt.complete.apply(this);if(p=="height"||p=="width"){opt.display=jQuery.css(this,"display");opt.overflow=this.style.overflow;}}if(opt.overflow!=null)this.style.overflow="hidden";opt.curAnim=jQuery.extend({},prop);jQuery.each(prop,function(name,val){var e=new jQuery.fx(self,opt,name);if(/toggle|show|hide/.test(val))e[val=="toggle"?hidden?"show":"hide":val](prop);else{var parts=val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(parts){var end=parseFloat(parts[2]),unit=parts[3]||"px";if(unit!="px"){self.style[name]=(end||1)+unit;start=((end||1)/e.cur(true))*start;self.style[name]=start+unit;}if(parts[1])end=((parts[1]=="-="?-1:1)*end)+start;e.custom(start,end,unit);}else
e.custom(start,val,"");}});return true;});},queue:function(type,fn){if(jQuery.isFunction(type)||(type&&type.constructor==Array)){fn=type;type="fx";}if(!type||(typeof type=="string"&&!fn))return queue(this[0],type);return this.each(function(){if(fn.constructor==Array)queue(this,type,fn);else{queue(this,type).push(fn);if(queue(this,type).length==1)fn.apply(this);}});},stop:function(clearQueue,gotoEnd){var timers=jQuery.timers;if(clearQueue)this.queue([]);this.each(function(){for(var i=timers.length-1;i>=0;i--)if(timers[i].elem==this){if(gotoEnd)timers[i](true);timers.splice(i,1);}});if(!gotoEnd)this.dequeue();return this;}});var queue=function(elem,type,array){if(!elem)return undefined;type=type||"fx";var q=jQuery.data(elem,type+"queue");if(!q||array)q=jQuery.data(elem,type+"queue",array?jQuery.makeArray(array):[]);return q;};jQuery.fn.dequeue=function(type){type=type||"fx";return this.each(function(){var q=queue(this,type);q.shift();if(q.length)q[0].apply(this);});};jQuery.extend({speed:function(speed,easing,fn){var opt=speed&&speed.constructor==Object?speed:{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&easing.constructor!=Function&&easing};opt.duration=(opt.duration&&opt.duration.constructor==Number?opt.duration:{slow:600,fast:200}[opt.duration])||400;opt.old=opt.complete;opt.complete=function(){if(opt.queue!==false)jQuery(this).dequeue();if(jQuery.isFunction(opt.old))opt.old.apply(this);};return opt;},easing:{linear:function(p,n,firstNum,diff){return firstNum+diff*p;},swing:function(p,n,firstNum,diff){return((-Math.cos(p*Math.PI)/2)+0.5)*diff+firstNum;}},timers:[],timerId:null,fx:function(elem,options,prop){this.options=options;this.elem=elem;this.prop=prop;if(!options.orig)options.orig={};}});jQuery.fx.prototype={update:function(){if(this.options.step)this.options.step.apply(this.elem,[this.now,this]);(jQuery.fx.step[this.prop]||jQuery.fx.step._default)(this);if(this.prop=="height"||this.prop=="width")this.elem.style.display="block";},cur:function(force){if(this.elem[this.prop]!=null&&this.elem.style[this.prop]==null)return this.elem[this.prop];var r=parseFloat(jQuery.css(this.elem,this.prop,force));return r&&r>-10000?r:parseFloat(jQuery.curCSS(this.elem,this.prop))||0;},custom:function(from,to,unit){this.startTime=(new Date()).getTime();this.start=from;this.end=to;this.unit=unit||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var self=this;function t(gotoEnd){return self.step(gotoEnd);}t.elem=this.elem;jQuery.timers.push(t);if(jQuery.timerId==null){jQuery.timerId=setInterval(function(){var timers=jQuery.timers;for(var i=0;i<timers.length;i++)if(!timers[i]())timers.splice(i--,1);if(!timers.length){clearInterval(jQuery.timerId);jQuery.timerId=null;}},13);}},show:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.show=true;this.custom(0,this.cur());if(this.prop=="width"||this.prop=="height")this.elem.style[this.prop]="1px";jQuery(this.elem).show();},hide:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0);},step:function(gotoEnd){var t=(new Date()).getTime();if(gotoEnd||t>this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var done=true;for(var i in this.options.curAnim)if(this.options.curAnim[i]!==true)done=false;if(done){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(jQuery.css(this.elem,"display")=="none")this.elem.style.display="block";}if(this.options.hide)this.elem.style.display="none";if(this.options.hide||this.options.show)for(var p in this.options.curAnim)jQuery.attr(this.elem.style,p,this.options.orig[p]);}if(done&&jQuery.isFunction(this.options.complete))this.options.complete.apply(this.elem);return false;}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=jQuery.easing[this.options.easing||(jQuery.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update();}return true;}};jQuery.fx.step={scrollLeft:function(fx){fx.elem.scrollLeft=fx.now;},scrollTop:function(fx){fx.elem.scrollTop=fx.now;},opacity:function(fx){jQuery.attr(fx.elem.style,"opacity",fx.now);},_default:function(fx){fx.elem.style[fx.prop]=fx.now+fx.unit;}};jQuery.fn.offset=function(){var left=0,top=0,elem=this[0],results;if(elem)with(jQuery.browser){var parent=elem.parentNode,offsetChild=elem,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522&&!/adobeair/i.test(userAgent),fixed=jQuery.css(elem,"position")=="fixed";if(elem.getBoundingClientRect){var box=elem.getBoundingClientRect();add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));add(-doc.documentElement.clientLeft,-doc.documentElement.clientTop);}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&!/^t(able|d|h)$/i.test(offsetParent.tagName)||safari&&!safari2)border(offsetParent);if(!fixed&&jQuery.css(offsetParent,"position")=="fixed")fixed=true;offsetChild=/^body$/i.test(offsetParent.tagName)?offsetChild:offsetParent;offsetParent=offsetParent.offsetParent;}while(parent&&parent.tagName&&!/^body|html$/i.test(parent.tagName)){if(!/^inline|table.*$/i.test(jQuery.css(parent,"display")))add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&jQuery.css(parent,"overflow")!="visible")border(parent);parent=parent.parentNode;}if((safari2&&(fixed||jQuery.css(offsetChild,"position")=="absolute"))||(mozilla&&jQuery.css(offsetChild,"position")!="absolute"))add(-doc.body.offsetLeft,-doc.body.offsetTop);if(fixed)add(Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));}results={top:top,left:left};}function border(elem){add(jQuery.curCSS(elem,"borderLeftWidth",true),jQuery.curCSS(elem,"borderTopWidth",true));}function add(l,t){left+=parseInt(l)||0;top+=parseInt(t)||0;}return results;};jQuery.each(["Height","Width"],function(i,name){var tl=name=="Height"?"Top":"Left",br=name=="Height"?"Bottom":"Right";jQuery.fn["inner"+name]=function(){return this[name.toLowerCase()]()+num(this,"padding"+tl)+num(this,"padding"+br);};jQuery.fn["outer"+name]=function(margin){return this["inner"+name]()+num(this,"border"+tl+"Width")+num(this,"border"+br+"Width")+(!!margin?num(this,"margin"+tl)+num(this,"margin"+br):0);};});function num(elem,prop){elem=elem.jquery?elem[0]:elem;return elem&&parseInt(jQuery.curCSS(elem,prop,true))||0;}})();

/* =========================================================

// 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.12 (06/07/2008)
 * @requires jQuery v1.2.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
 *
 * Revision: $Id$
 */
(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() {
            $(this).ajaxSubmit({
                target: '#output'
            });
            return false; // <-- important!
        });
    });

    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;
    }

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

    options = $.extend({
        url:  this.attr('action') || window.location.toString(),
        type: this.attr('method') || 'GET'
    }, 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;
   }

    var a = this.formToArray(options.semantic);
    if (options.data) {
        options.extraData = options.data;
        for (var n in options.data)
            a.push( { name: n, value: options.data[n] } );
    }

    // 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 $form = this, 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) {
            $(options.target).html(data).each(oldSuccess, arguments);
        });
    }
    else if (options.success)
        callbacks.push(options.success);

    options.success = function(data, status) {
        for (var i=0, max=callbacks.length; i < max; i++)
            callbacks[i](data, status, $form);
    };

    // are there files to upload?
    var files = $('input:file', this).fieldValue();
    var found = false;
    for (var j=0; j < files.length; j++)
        if (files[j])
            found = true;

    // options.iframe allows user to force iframe mode
   if (options.iframe || found) { 
       // hack to fix Safari hang (thanks to Tim Molendijk for this)
       // see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
       if ($.browser.safari && options.closeKeepAlive)
           $.get(options.closeKeepAlive, fileUpload);
       else
           fileUpload();
       }
   else
       $.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() {
        var form = $form[0];
        
        if ($(':input[name=submit]', form).length) {
            alert('Error: Form elements must not be named "submit".');
            return;
        }
        
        var opts = $.extend({}, $.ajaxSettings, options);

        var id = 'jqFormIO' + (new Date().getTime());
        var $io = $('<iframe id="' + id + '" name="' + id + '" />');
        var io = $io[0];

        if ($.browser.msie || $.browser.opera) 
            io.src = 'javascript:false;document.write("");';
        $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });

        var xhr = { // mock object
            responseText: null,
            responseXML: null,
            status: 0,
            statusText: 'n/a',
            getAllResponseHeaders: function() {},
            getResponseHeader: function() {},
            setRequestHeader: function() {}
        };

        var g = opts.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, opts]);

        var cbInvoked = 0;
        var timedOut = 0;

        // add submitting element to data if we know it
        var sub = form.clk;
        if (sub) {
            var n = sub.name;
            if (n && !sub.disabled) {
                options.extraData = options.extraData || {};
                options.extraData[n] = sub.value;
                if (sub.type == "image") {
                    options.extraData[name+'.x'] = form.clk_x;
                    options.extraData[name+'.y'] = form.clk_y;
                }
            }
        }
        
        // take a breath so that pending repaints get some cpu time before the upload starts
        setTimeout(function() {
            // make sure form attrs are set
            var t = $form.attr('target'), a = $form.attr('action');
            $form.attr({
                target:   id,
                encoding: 'multipart/form-data',
                enctype:  'multipart/form-data',
                method:   'POST',
                action:   opts.url
            });

            // support timout
            if (opts.timeout)
                setTimeout(function() { timedOut = true; cb(); }, opts.timeout);

            // add "extra" data to form if provided in options
            var extraInputs = [];
            try {
                if (options.extraData)
                    for (var n in options.extraData)
                        extraInputs.push(
                            $('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
                                .appendTo(form)[0]);
            
                // add iframe to doc and submit the form
                $io.appendTo('body');
                io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
                form.submit();
            }
            finally {
                // reset attrs and remove "extra" input elements
                $form.attr('action', a);
                t ? $form.attr('target', t) : $form.removeAttr('target');
                $(extraInputs).remove();
            }
        }, 10);

        function cb() {
            if (cbInvoked++) return;
            
            io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);

            var operaHack = 0;
            var ok = true;
            try {
                if (timedOut) throw 'timeout';
                // extract the server response from the iframe
                var data, doc;

                doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
                
                if (doc.body == null && !operaHack && $.browser.opera) {
                    // In Opera 9.2.x the iframe DOM is not always traversable when
                    // the onload callback fires so we give Opera 100ms to right itself
                    operaHack = 1;
                    cbInvoked--;
                    setTimeout(cb, 100);
                    return;
                }
                
                xhr.responseText = doc.body ? doc.body.innerHTML : null;
                xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
                xhr.getResponseHeader = function(header){
                    var headers = {'content-type': opts.dataType};
                    return headers[header];
                };

                if (opts.dataType == 'json' || opts.dataType == 'script') {
                    var ta = doc.getElementsByTagName('textarea')[0];
                    xhr.responseText = ta ? ta.value : xhr.responseText;
                }
                else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
                    xhr.responseXML = toXml(xhr.responseText);
                }
                data = $.httpData(xhr, opts.dataType);
            }
            catch(e){
                ok = false;
                $.handleError(opts, xhr, 'error', e);
            }

            // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
            if (ok) {
                opts.success(data, 'success');
                if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
            }
            if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
            if (g && ! --$.active) $.event.trigger("ajaxStop");
            if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');

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

        function toXml(s, doc) {
            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.tagName != 'parsererror') ? doc : null;
        };
    };
};

/**
 * 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) {
    return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
        $(this).ajaxSubmit(options);
        return false;
    }).each(function() {
        // store options in hash
        $(":submit,input:image", this).bind('click.form-plugin',function(e) {
            var $form = this.form;
            $form.clk = this;
            if (this.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 = $(this).offset();
                    $form.clk_x = e.pageX - offset.left;
                    $form.clk_y = e.pageY - offset.top;
                } else {
                    $form.clk_x = e.pageX - this.offsetLeft;
                    $form.clk_y = e.pageY - this.offsetTop;
                }
            }
            // clear form vars
            setTimeout(function() { $form.clk = $form.clk_x = $form.clk_y = null; }, 10);
        });
    });
};

// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
    this.unbind('submit.form-plugin');
    return this.each(function() {
        $(":submit,input:image", this).unbind('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;
    for(var i=0, max=els.length; i < max; i++) {
        var el = els[i];
        var 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+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
            continue;
        }

        var v = $.fieldValue(el, true);
        if (v && v.constructor == Array) {
            for(var 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 them here
        var inputs = form.getElementsByTagName("input");
        for(var i=0, max=inputs.length; i < max; i++) {
            var input = inputs[i];
            var n = input.name;
            if(n && !input.disabled && input.type == "image" && form.clk == input)
                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 (typeof 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) {
                // extra pain for IE...
                var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
                if (one) return v;
                a.push(v);
            }
        }
        return a;
    }
    return el.value;
};

/**
 * 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() {
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (t == 'text' || t == 'password' || 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.select = 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').select(false);
            }
            this.selected = select;
        }
    });
};

// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
    if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
        window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};

})(jQuery);


/**
 * 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 history plugin
 *
 * sample page: http://www.mikage.to/jquery/jquery_history.html
 *
 * Copyright (c) 2006-2009 Taku Sano (Mikage Sawatari)
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Modified by Lincoln Cooper to add Safari support and only call the callback once during initialization
 * for msie when no initial hash supplied.
 */


jQuery.extend({
	historyCurrentHash: undefined,
	historyCallback: undefined,
	historyIframeSrc: undefined,

	historyInit: function(callback, src){
		jQuery.historyCallback = callback;
		if (src) jQuery.historyIframeSrc = src;
		var current_hash = location.hash.replace(/\?.*$/, '');

		jQuery.historyCurrentHash = current_hash;
		// if ((jQuery.browser.msie) && (jQuery.browser.version < 8)) {
		if (jQuery.browser.msie) {
			// To stop the callback firing twice during initilization if no hash present
			if (jQuery.historyCurrentHash == '') {
			jQuery.historyCurrentHash = '#';
		}

			// add hidden iframe for IE
			jQuery("body").prepend('<iframe id="jQuery_history" style="display: none;"'+
				(jQuery.historyIframeSrc ? ' src="'+jQuery.historyIframeSrc+'"' : '')
				+'></iframe>'
			);
			var ihistory = jQuery("#jQuery_history")[0];
			var iframe = ihistory.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = current_hash;
		}
		else if (jQuery.browser.safari) {
			// etablish back/forward stacks
			jQuery.historyBackStack = [];
			jQuery.historyBackStack.length = history.length;
			jQuery.historyForwardStack = [];
			jQuery.lastHistoryLength = history.length;

			jQuery.isFirst = true;
		}
		if(current_hash)
			jQuery.historyCallback(current_hash.replace(/^#/, ''));
		setInterval(jQuery.historyCheck, 100);
	},

	historyAddHistory: function(hash) {
		// This makes the looping function do something
		jQuery.historyBackStack.push(hash);

		jQuery.historyForwardStack.length = 0; // clear forwardStack (true click occured)
		this.isFirst = true;
	},

	historyCheck: function(){
		// if ((jQuery.browser.msie) && (jQuery.browser.version < 8)) {
		if (jQuery.browser.msie) {
			// On IE, check for location.hash of iframe
			var ihistory = jQuery("#jQuery_history")[0];
			var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
			var current_hash = iframe.location.hash.replace(/\?.*$/, '');
			if(current_hash != jQuery.historyCurrentHash) {

				location.hash = current_hash;
				jQuery.historyCurrentHash = current_hash;
				jQuery.historyCallback(current_hash.replace(/^#/, ''));

			}
		} else if (jQuery.browser.safari) {
			if(jQuery.lastHistoryLength == history.length && jQuery.historyBackStack.length > jQuery.lastHistoryLength) {
				jQuery.historyBackStack.shift();
			}
			if (!jQuery.dontCheck) {
				var historyDelta = history.length - jQuery.historyBackStack.length;
				jQuery.lastHistoryLength = history.length;

				if (historyDelta) { // back or forward button has been pushed
					jQuery.isFirst = false;
					if (historyDelta < 0) { // back button has been pushed
						// move items to forward stack
						for (i = 0; i < Math.abs(historyDelta); i++) jQuery.historyForwardStack.unshift(jQuery.historyBackStack.pop());
					} else { // forward button has been pushed
						// move items to back stack
						for (i = 0; i < historyDelta; i++) jQuery.historyBackStack.push(jQuery.historyForwardStack.shift());
					}
					var cachedHash = jQuery.historyBackStack[jQuery.historyBackStack.length - 1];
					if (cachedHash != undefined) {
						jQuery.historyCurrentHash = location.hash.replace(/\?.*$/, '');
						jQuery.historyCallback(cachedHash);
					}
				} else if (jQuery.historyBackStack[jQuery.historyBackStack.length - 1] == undefined && !jQuery.isFirst) {
					// back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
					// document.URL doesn't change in Safari
					if (location.hash) {
						current_hash = location.hash;
						jQuery.historyCallback(location.hash.replace(/^#/, ''));
					} else {
						current_hash = '';
						jQuery.historyCallback('');
					}
					jQuery.isFirst = true;
				}
			}
		} else {
			// otherwise, check for location.hash
			current_hash = location.hash.replace(/\?.*$/, '');
			if(current_hash != jQuery.historyCurrentHash) {
				jQuery.historyCurrentHash = current_hash;
				jQuery.historyCallback(current_hash.replace(/^#/, ''));
			}
		}
	},
	historyLoad: function(hash){
		var newhash;
		hash = decodeURIComponent(hash.replace(/\?.*$/, ''));

		if (jQuery.browser.safari) {
			newhash = hash;
		}
		else {
			newhash = '#' + hash;
			location.hash = newhash;
		}
		jQuery.historyCurrentHash = newhash;

		// if ((jQuery.browser.msie) && (jQuery.browser.version < 8)) {
		if (jQuery.browser.msie) {
			var ihistory = jQuery("#jQuery_history")[0];
			var iframe = ihistory.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = newhash;
			jQuery.lastHistoryLength = history.length;
			jQuery.historyCallback(hash);
		}
		else if (jQuery.browser.safari) {
			jQuery.dontCheck = true;
			// Manually keep track of the history values for Safari
			this.historyAddHistory(hash);

			// Wait a while before allowing checking so that Safari has time to update the "history" object
			// correctly (otherwise the check loop would detect a false change in hash).
			var fn = function() {jQuery.dontCheck = false;};
			window.setTimeout(fn, 200);
			jQuery.historyCallback(hash);
			// N.B. "location.hash=" must be the last line of code for Safari as execution stops afterwards.
			//      By explicitly using the "location.hash" command (instead of using a variable set to "location.hash") the
			//      URL in the browser and the "history" object are both updated correctly.
			location.hash = newhash;
		}
		else {
		  jQuery.historyCallback(hash);
		}
	}
});







	/**
	 * 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
	}
);



/**
 * 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
        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);
    }
}

$.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

}



/**
 * 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;

        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 (){
        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',

    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){
        
        OrionContentLoad(url,target,function(){
            orion.xhr.preload();
            //alert(typeof callback);
            if(typeof callback != 'undefined' && callback != null)
                callback.call();
        },data,history);
    },

    /**
     * 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'){
            //alert(dataobj.action);
            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();
        $('a[rel*=napi_action]').unbind().ajax_action();
        $('a[rel*=lightbox]').unbind().lightBox();
        orion_ajax_forms();
    },

    /**
     * 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;
        }

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

        if(notice.length > 0){
            //jQuery('div#' + this.messagesId).css('background-color', 'green');
            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');
    }




}



/**** 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);
	}
}

/**
* 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;
			});
		}
	}

}




var hide_empty_list=true;

addListGroup("vehicles", "car-makers");

addList("car-makers", "Select a maker", "", "dummy-maker");
addList("car-makers", "Toyota", "Toyota", "Toyota");
addList("car-makers", "Honda", "Honda", "Honda");
addList("car-makers", "Chrysler", "Chrysler", "Chrysler", 1);

addList("dummy-maker", "Not available", "", "dummy-car");

addOption("dummy-car", "Not available", "");

addList("Toyota", "Select vehicle type", "", "dummy-toyota");
addList("Toyota", "Cars", "car", "Toyota-Cars");
addList("Toyota", "SUVs/Van", "suv", "Toyota-SUVs/Van");
addList("Toyota", "Trucks", "truck", "Toyota-Trucks", 1);

addOption("dummy-toyota", "Not available", "");

addOption("Toyota-Cars", "Select a model", "");
addOption("Toyota-Cars", "Avalon", "Avalon");
addOption("Toyota-Cars", "Camry", "Camry");
addOption("Toyota-Cars", "Celica", "Celica");
addOption("Toyota-Cars", "Corolla", "Corolla");
addOption("Toyota-Cars", "ECHO", "ECHO");

addOption("Toyota-SUVs/Van", "Select a model", "");
addOption("Toyota-SUVs/Van", "4Runner", "4Runner");
addOption("Toyota-SUVs/Van", "Highlander", "Highlander");
addOption("Toyota-SUVs/Van", "Land Cruiser", "Land Cruiser");
addOption("Toyota-SUVs/Van", "RAV4", "RAV4");

addOption("Toyota-Trucks", "Select a model", "");
addOption("Toyota-Trucks", "Tacoma", "Tacoma");
addOption("Toyota-Trucks", "Tundra", "Tundra", 1);

addList("Honda", "Select vehicle type", "", "dummy-honda");
addList("Honda", "Cars", "car", "Honda-Cars");
addList("Honda", "SUVs/Van", "suv", "Honda-SUVs/Van", 1);

addOption("dummy-honda", "Not available", "");

addOption("Honda-Cars", "Select a model", "");
addOption("Honda-Cars", "Accord Sedan", "Accord Sedan");
addOption("Honda-Cars", "Accord Coupe", "Accord Coupe");
addOption("Honda-Cars", "Civic Sedan", "Civic Sedan");
addOption("Honda-Cars", "Civic Coupe", "Civic Coupe");
addOption("Honda-Cars", "Civic Hybrid", "Civic Hybrid");

addOption("Honda-SUVs/Van", "Select a model", "");
addOption("Honda-SUVs/Van", "CR-V", "CR-V");
addOption("Honda-SUVs/Van", "Pilot", "Pilot");
addOption("Honda-SUVs/Van", "Odyssey", "Odyssey", 1);

addList("Chrysler", "Select vehicle type", "", "dummy-chrysler");
addList("Chrysler", "Cars", "car", "Chrysler-Cars", 1);
addList("Chrysler", "SUVs/Van", "suv", "Chrysler-SUVs/Van");

addOption("dummy-chrysler", "Not available", "");

addOption("Chrysler-Cars", "Select a model", "");
addOption("Chrysler-Cars", "300M", "300M");
addOption("Chrysler-Cars", "PT Cruiser", "PT Cruiser", 1);
addOption("Chrysler-Cars", "Concorde", "Concorde");
addOption("Chrysler-Cars", "Sebring Coupe", "Sebring Coupe");

addOption("Chrysler-SUVs/Van", "Select a model", "");
addOption("Chrysler-SUVs/Van", "Town & Country", "Town & Country");
addOption("Chrysler-SUVs/Van", "Voyager", "Voyager");


var fadeimages=new Array()
//SET IMAGE PATHS. Extend or contract array as needed

var fadeimages2=new Array() //2nd array set example. Remove or add more sets as needed.
//SET IMAGE PATHS. Extend or contract array as needed
fadeimages2[0]=["imagenes/Galeria_Fotos/foto01.jpg", "", ""] //plain image syntax
fadeimages2[1]=["imagenes/Galeria_Fotos/foto02.jpg", "", ""] //image with link syntax
fadeimages2[2]=["imagenes/Galeria_Fotos/foto03.jpg", "", ""] //image with link and target syntax
fadeimages2[3]=["imagenes/Galeria_Fotos/foto04.jpg", "", ""] //image with link and target syntax
 
var fadebgcolor="#FFFFFF"
 
////NO need to edit beyond here/////////////
 
var fadearray=new Array() //array to cache fadeshow instances
var fadeclear=new Array() //array to cache corresponding clearinterval pointers
 
var dom=(document.getElementById) //modern dom browsers
var iebrowser=document.all
 
function fadeshow(theimages, fadewidth, fadeheight, borderwidth, delay, pause, displayorder){
this.pausecheck=pause
this.mouseovercheck=0
this.delay=delay
this.degree=10 //initial opacity degree (10%)
this.curimageindex=0
this.nextimageindex=1
fadearray[fadearray.length]=this
this.slideshowid=fadearray.length-1
this.canvasbase="canvas"+this.slideshowid
this.curcanvas=this.canvasbase+"_0"
if (typeof displayorder!="undefined")
theimages.sort(function() {return 0.5 - Math.random();}) //thanks to Mike (aka Mwinter) :)
this.theimages=theimages
this.imageborder=parseInt(borderwidth)
this.postimages=new Array() //preload images
for (p=0;p<theimages.length;p++){
this.postimages[p]=new Image()
this.postimages[p].src=theimages[p][0]
}
 
var fadewidth=fadewidth+this.imageborder*2
var fadeheight=fadeheight+this.imageborder*2
 
if (iebrowser&&dom||dom) //if IE5+ or modern browsers (ie: Firefox)
document.write('<div id="master'+this.slideshowid+'" style="position:relative;width:'+fadewidth+'px;height:'+fadeheight+'px;overflow:hidden;"><div id="'+this.canvasbase+'_0" style="position:absolute;width:'+fadewidth+'px;height:'+fadeheight+'px;top:0;left:0;filter:progid:DXImageTransform.Microsoft.alpha(opacity=10);-moz-opacity:10;-khtml-opacity:10;background-color:'+fadebgcolor+'"></div><div id="'+this.canvasbase+'_1" style="position:absolute;width:'+fadewidth+'px;height:'+fadeheight+'px;top:0;left:0;filter:progid:DXImageTransform.Microsoft.alpha(opacity=10);-moz-opacity:10;background-color:'+fadebgcolor+'"></div></div>')
else
document.write('<div><img name="defaultslide'+this.slideshowid+'" src="'+this.postimages[0].src+'"></div>')
 
if (iebrowser&&dom||dom) //if IE5+ or modern browsers such as Firefox
this.startit()
else{
this.curimageindex++
setInterval("fadearray["+this.slideshowid+"].rotateimage()", this.delay)
}
}

function fadepic(obj){
if (obj.degree<100){
obj.degree+=10
if (obj.tempobj.filters&&obj.tempobj.filters[0]){
if (typeof obj.tempobj.filters[0].opacity=="number") //if IE6+
obj.tempobj.filters[0].opacity=obj.degree
else //else if IE5.5-
obj.tempobj.style.filter="alpha(opacity="+obj.degree+")"
}
else if (obj.tempobj.style.MozOpacity)
obj.tempobj.style.MozOpacity=obj.degree/101
else if (obj.tempobj.style.KhtmlOpacity)
obj.tempobj.style.KhtmlOpacity=obj.degree/100
}
else{
clearInterval(fadeclear[obj.slideshowid])
obj.nextcanvas=(obj.curcanvas==obj.canvasbase+"_0")? obj.canvasbase+"_0" : obj.canvasbase+"_1"
obj.tempobj=iebrowser? iebrowser[obj.nextcanvas] : document.getElementById(obj.nextcanvas)
obj.populateslide(obj.tempobj, obj.nextimageindex)
obj.nextimageindex=(obj.nextimageindex<obj.postimages.length-1)? obj.nextimageindex+1 : 0
setTimeout("fadearray["+obj.slideshowid+"].rotateimage()", obj.delay)
}
}
 
fadeshow.prototype.populateslide=function(picobj, picindex){
var slideHTML=""
if (this.theimages[picindex][1]!="") //if associated link exists for image
slideHTML='<a href="'+this.theimages[picindex][1]+'" target="'+this.theimages[picindex][2]+'">'
slideHTML+='<img src="'+this.postimages[picindex].src+'" border="'+this.imageborder+'px">'
if (this.theimages[picindex][1]!="") //if associated link exists for image
slideHTML+='</a>'
picobj.innerHTML=slideHTML
}
 
 
fadeshow.prototype.rotateimage=function(){
if (this.pausecheck==1) //if pause onMouseover enabled, cache object
var cacheobj=this
if (this.mouseovercheck==1)
setTimeout(function(){cacheobj.rotateimage()}, 100)
else if (iebrowser&&dom||dom){
this.resetit()
var crossobj=this.tempobj=iebrowser? iebrowser[this.curcanvas] : document.getElementById(this.curcanvas)
crossobj.style.zIndex++
fadeclear[this.slideshowid]=setInterval("fadepic(fadearray["+this.slideshowid+"])",50)
this.curcanvas=(this.curcanvas==this.canvasbase+"_0")? this.canvasbase+"_1" : this.canvasbase+"_0"
}
else{
var ns4imgobj=document.images['defaultslide'+this.slideshowid]
ns4imgobj.src=this.postimages[this.curimageindex].src
}
this.curimageindex=(this.curimageindex<this.postimages.length-1)? this.curimageindex+1 : 0
}
 
fadeshow.prototype.resetit=function(){
this.degree=10
var crossobj=iebrowser? iebrowser[this.curcanvas] : document.getElementById(this.curcanvas)
if (crossobj.filters&&crossobj.filters[0]){
if (typeof crossobj.filters[0].opacity=="number") //if IE6+
crossobj.filters(0).opacity=this.degree
else //else if IE5.5-
crossobj.style.filter="alpha(opacity="+this.degree+")"
}
else if (crossobj.style.MozOpacity)
crossobj.style.MozOpacity=this.degree/101
else if (crossobj.style.KhtmlOpacity)
crossobj.style.KhtmlOpacity=obj.degree/100
}
 
 
fadeshow.prototype.startit=function(){
var crossobj=iebrowser? iebrowser[this.curcanvas] : document.getElementById(this.curcanvas)
this.populateslide(crossobj, this.curimageindex)
if (this.pausecheck==1){ //IF SLIDESHOW SHOULD PAUSE ONMOUSEOVER
var cacheobj=this
var crossobjcontainer=iebrowser? iebrowser["master"+this.slideshowid] : document.getElementById("master"+this.slideshowid)
crossobjcontainer.onmouseover=function(){cacheobj.mouseovercheck=1}
crossobjcontainer.onmouseout=function(){cacheobj.mouseovercheck=0}
}
this.rotateimage()
}

var VersionNav= navigator.appVersion;// le puse este pto y coma porque es raro que no lo tenga, capaz que es por algo
	var star= null;

	function AlternarImag (nombre, fuente) {
		if (((navigator.appName == "Netscape") & (VersionNav.substring(0,1) >=3)) || (VersionNav.substring (0,1) >= 4)) {
			imagen = new Object();
			imagen = nombre;
			imagen.src = fuente;
		}
	};

	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= ""

	function loadpage(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
	};

	function eme2(obj,url, containerid){
		url = url+obj.value
		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(){
							loadpage(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 eme(url, containerid){
		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(){
							loadpage(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)
	};



// Chained Selects

// Copyright Xin Yang 2004
// Web Site: www.yxScripts.com
// EMail: m_yangxin@hotmail.com
// Last Updated: 2004-08-23

// This script is free as long as the copyright notice remains intact.

var _disable_empty_list=false;
var _hide_empty_list=false;

// ------
if (typeof(disable_empty_list)=="undefined") { disable_empty_list=_disable_empty_list; }
if (typeof(hide_empty_list)=="undefined") { hide_empty_list=_hide_empty_list; }

var cs_goodContent=true, cs_M="M", cs_L="L", cs_curTop=null, cs_curSub=null;

function cs_findOBJ(obj,n) {
  for (var i=0; i<obj.length; i++) {
    if (obj[i].name==n) { return obj[i]; }
  }
  return null;
}
function cs_findContent(n) { return cs_findOBJ(cs_content,n); }

function cs_findM(m,n) {
  if (m.name==n) { return m; }

  var sm=null;
  for (var i=0; i<m.items.length; i++) {
    if (m.items[i].type==cs_M) {
      sm=cs_findM(m.items[i],n);
      if (sm!=null) { break; }
    }
  }
  return sm;
}
function cs_findMenu(n) { return (cs_curSub!=null && cs_curSub.name==n)?cs_curSub:cs_findM(cs_curTop,n); }

function cs_contentOBJ(n,obj){ this.name=n; this.menu=obj; this.lists=new Array(); this.cookie=""; }; cs_content=new Array();
function cs_topmenuOBJ(tm) { this.name=tm; this.items=new Array(); this.df=0; this.addM=cs_addM; this.addL=cs_addL; }
function cs_submenuOBJ(dis,link,sub) {
  this.name=sub;
  this.type=cs_M; this.dis=dis; this.link=link; this.df=0;

  var x=cs_findMenu(sub);
  this.items=x==null?new Array():x.items;

  this.addM=cs_addM; this.addL=cs_addL;
}
function cs_linkOBJ(dis,link) { this.type=cs_L; this.dis=dis; this.link=link; }

function cs_addM(dis,link,sub) { this.items[this.items.length]=new cs_submenuOBJ(dis,link,sub); }
function cs_addL(dis,link) { this.items[this.items.length]=new cs_linkOBJ(dis,link); }

function cs_showMsg(msg) { window.status=msg; }
function cs_badContent(n) { cs_goodContent=false; cs_showMsg("["+n+"] Not Found."); }

function cs_optionOBJ(text,value) { this.text=text; this.value=value; }
function cs_emptyList(list) { for (var i=list.options.length-1; i>=0; i--) { list.options[i]=null; } }
function cs_refreshList(list,opt,df) {
  cs_emptyList(list);

  for (var i=0; i<opt.length; i++) {
    list.options[i]=new Option(opt[i].text, opt[i].value);
  }

  if (opt.length>0) {
    list.selectedIndex=df;
  }
}
function cs_getOptions(menu) {
  var opt=new Array();
  for (var i=0; i<menu.items.length; i++) {
    opt[i]=new cs_optionOBJ(menu.items[i].dis, menu.items[i].link);
  }
  return opt;
}
function cs_updateListGroup(content,idx,sidx,mode) {
  var i=0, curItem=null, menu=content.menu;

  while (i<idx) {
    menu=menu.items[content.lists[i++].selectedIndex];
  }

  if (menu.items[sidx].type==cs_M && idx<content.lists.length-1) {
    var df=cs_getIdx(mode,content.cookie,idx+1,menu.items[sidx].df);

    cs_refreshList(content.lists[idx+1], cs_getOptions(menu.items[sidx]), df);
    if (content.cookie) {
      cs_setCookie(content.cookie+"_"+(idx+1),df);
    }

    if (idx+1<content.lists.length) {
      if (disable_empty_list) {
        content.lists[idx+1].disabled=false;
      }
      if (hide_empty_list) {
        content.lists[idx+1].style.display="";
      }

      cs_updateListGroup(content,idx+1,df,mode);
    }
  }
  else {
    for (var s=idx+1; s<content.lists.length; s++) {
      cs_emptyList(content.lists[s]);

      if (disable_empty_list) {
        content.lists[s].disabled=true;
      }
      if (hide_empty_list) {
        content.lists[s].style.display="none";
      }

      if (content.cookie) {
        cs_setCookie(content.cookie+"_"+s,"");
      }
    }
  }
}
function cs_initListGroup(content,mode) {
  var df=cs_getIdx(mode,content.cookie,0,content.menu.df);

  cs_refreshList(content.lists[0], cs_getOptions(content.menu), df);
  if (content.cookie) {
    cs_setCookie(content.cookie+"_"+0,df);
  }

  cs_updateListGroup(content,0,df,mode);
}

function cs_updateList() {
  var content=this.content;
  for (var i=0; i<content.lists.length; i++) {
    if (content.lists[i]==this) {
      if (content.cookie) {
        cs_setCookie(content.cookie+"_"+i,this.selectedIndex);
      }

      if (i<content.lists.length-1) {
        cs_updateListGroup(content,i,this.selectedIndex,"");
      }
    }
  }
}

function cs_getIdx(mode,name,idx,df) {
  if (mode) {
    var cs_idx=cs_getCookie(name+"_"+idx);
    if (cs_idx!="") {
      df=parseInt(cs_idx);
    }
  }
  return df;
}

function _setCookie(name, value) {
  document.cookie=name+"="+value;
}
function cs_setCookie(name, value) {
  setTimeout("_setCookie('"+name+"','"+value+"')",0);
}

function cs_getCookie(name) {
  var cookieRE=new RegExp(name+"=([^;]+)");
  if (document.cookie.search(cookieRE)!=-1) {
    return RegExp.$1;
  }
  else {
    return "";
  }
}

// ----
function addListGroup(n,tm) {
  if (cs_goodContent) {
    cs_curTop=new cs_topmenuOBJ(tm); cs_curSub=null;

    var c=cs_findContent(n);
    if (c==null) {
      cs_content[cs_content.length]=new cs_contentOBJ(n,cs_curTop);
    }
    else {
      delete(c.menu); c.menu=cs_curTop;
    }
  }
}

function addList(n,dis,link,sub,df) {
  if (cs_goodContent) {
    cs_curSub=cs_findMenu(n);

    if (cs_curSub!=null) {
      cs_curSub.addM(dis,link||"",sub);
      if (typeof(df)!="undefined") { cs_curSub.df=cs_curSub.items.length-1; }
    }
    else {
      cs_badContent(n);
    }
  }
}

function addOption(n,dis,link,df) {
  if (cs_goodContent) {
    cs_curSub=cs_findMenu(n);

    if (cs_curSub!=null) {
      cs_curSub.addL(dis,link||"");
      if (typeof(df)!="undefined") { cs_curSub.df=cs_curSub.items.length-1; }
    }
    else {
      cs_badContent(n);
    }
  }
}

function initListGroup(n) {
  var _content=cs_findContent(n), count=0;
  if (_content!=null) {
    content=new cs_contentOBJ("cs_"+n,_content.menu);
    cs_content[cs_content.length]=content;

    for (var i=1; i<initListGroup.arguments.length; i++) {
      if (typeof(arguments[i])=="object" && arguments[i].tagName && arguments[i].tagName=="SELECT") {
        content.lists[count]=arguments[i];

        arguments[i].onchange=cs_updateList;
        arguments[i].content=content; arguments[i].idx=count++;
      }
      else if (typeof(arguments[i])=="string" && /^[a-zA-Z_]\w*$/.test(arguments[i])) {
        content.cookie=arguments[i];
      }
    }

    if (content.lists.length>0) {
      cs_initListGroup(content,content.cookie);
    }
  }
}

function resetListGroup(n) {
  var content=cs_findContent("cs_"+n);
  if (content!=null && content.lists.length>0) {
    cs_initListGroup(content,"");
  }
}
// ------

function writeflash(o,m,w,h,p,oid) {
	if (oid!=null) {oid="id='"+oid+"'";}

	f="<object "+oid+" classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='../download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0/#version=7,0,19,0/.class' width='"+w+"' height='"+h+"'>";
	f+="<param name='movie' value='"+m+"'>";
	f+="<param name='quality' value='high'>";
	if (p!="") {f+="<param name=flashvars value='"+p+"'>";}
	f+="<param name='wmode' value='transparent'>";
	f+="<embed "+oid+" src='"+m+"' width='"+w+"' height='"+h+"' quality='high' pluginspage='../www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' wmode='transparent'";
	if (p!="") {f+=" flashvars='"+p+"'";}
	f+="></embed>";
	f+="</object>";
	document.getElementById(o).innerHTML=f
}

function ismaxlength(obj){
	var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
	if (obj.getAttribute && obj.value.length>mlength)
		obj.value=obj.value.substring(0,mlength)
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
	window.open(theURL,winName,features);
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
	eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
	if (restore)
		selObj.selectedIndex=0;
}

/** funciones para el selector de productos **/
function SubCategories_Sections_call(subid){
    var url='/Actions/action_subcategories_sections?subid=' + subid;
    makeHttpRequest(url,'SubCategories_Sections_action');
}

function SubCategories_Sections_action(data){
    var div_subsection=document.getElementById('div_subsection');
    div_subsection.innerHTML=data;
}

function SelectorAction(){
    var selector = document.getElementById("SectionID");
    var selected_option=selector.options.selectedIndex;
	
    ClientNameTextBoxAdd(selector.options[selected_option].innerHTML);
}

function CategorySelectorAction(){
    var selector = document.getElementById("SubCategory");
    SubCategories_Sections_call(selector.value);
	
//alert(selector.value);
}

//carga la url en el iframe(admin)...
function AdminContent(url,obj){
    //tpv_buscador.setAttribute("class", "buscador");
    document.getElementById("href1").setAttribute("class", "");
    document.getElementById("href2").setAttribute("class", "");
    document.getElementById("href3").setAttribute("class", "");
    document.getElementById("href4").setAttribute("class", "");
    document.getElementById("href5").setAttribute("class", "");
    document.getElementById("href6").setAttribute("class", "");
    document.getElementById("href7").setAttribute("class", "");
	document.getElementById("href8").setAttribute("class", "");
	
    document.getElementById(obj).setAttribute("class", "selected");
    var iframe = document.getElementById("iframe_admin");
    iframe.src = url;
}

// revisar, pero no funciona como debería............
function Content(url, obj){
    var iframe = document.getElementById("iframe_portal");
    iframe.src = url;
	
    var str = document.getElementById("pestanias").value;
	
    var array = str.split(" ");
    for (i=0; i < array.length; i++){
        var id = "li" + array[i];
		
        var menuelemento = document.getElementById(id);
		
        menuelemento.setAttribute("className", "");
        menuelemento.setAttribute("class", "");
    };
    var menuelementopintado = document.getElementById(obj);
    menuelementopintado.setAttribute("className", "selected");
    menuelementopintado.setAttribute("class", "selected");
}

function buscar_info_pique(url, value){
    var iframe = document.getElementById("iframe");
    var new_valu = value.split(":");
    var mes = 0;
    if (new_valu[0] == "Enero") mes = 1;
    if (new_valu[0] == "Febrero") mes = 2;
    if (new_valu[0] == "Marzo") mes = 3;
    if (new_valu[0] == "Abril") mes = 4;
    if (new_valu[0] == "Mayo") mes = 5;
    if (new_valu[0] == "Junio") mes = 6;
    if (new_valu[0] == "Julio") mes = 7;
    if (new_valu[0] == "Agosto") mes = 8;
    if (new_valu[0] == "Setiembre") mes = 9;
    if (new_valu[0] == "Octubre") mes = 10;
    if (new_valu[0] == "Noviembre") mes = 11;
    if (new_valu[0] == "Diciembre") mes = 12;
    iframe.src = url+"?mes=0"+mes+"&anio="+new_valu[1];
	
    var div_mes = document.getElementById("mes_a_cambiar");
    div_mes.innerHTML = new_valu[0];

}

function delete_producto(prod_id){
    var url='/Actions/action_delete_product?item=' + prod_id;
    if(confirm('Confirmacion de Borrado: '+prod_id) == true){
        makeHttpRequest(url);
		
        var tabla=document.getElementById('tablita');
        var fila=document.getElementById('field'+prod_id);
        tabla.removeChild(fila);
    }
}

function delete_informe(inf_id){
    var url='/Actions/action_delete_informe?item=' + inf_id;
    if(confirm('Confirmacion de Borrado: '+inf_id) == true){
        makeHttpRequest(url);
		
        var tabla=document.getElementById('tablita');
        var fila=document.getElementById('field'+inf_id);
        tabla.removeChild(fila);
    }
}

function delete_foto(ph_id){
    var url='/Actions/action_delete_foto?item=' + ph_id;
    if(confirm('Confirmacion de Borrado: '+ph_id) == true){
        makeHttpRequest(url);
		
        var tabla=document.getElementById('tablita');
        var fila=document.getElementById('field'+ph_id);
        tabla.removeChild(fila);
    }
}

function delete_img_relev(id){
    var url='/Actions/action_delete_img_rel?item=' + id;
    if(confirm('Confirmacion de Borrado: '+id) == true){
        makeHttpRequest(url);

    //self.reload();
    /*var tabla=document.getElementById('tablita');
		var fila=document.getElementById('field'+id);
		tabla.removeChild(fila);*/
    }
}

function delete_img_infor(id){
    var url='/Actions/action_delete_img_inf?item=' + id;
    if(confirm('Confirmacion de Borrado: '+id) == true){
        makeHttpRequest(url);

    //self.reload();
    /*var tabla=document.getElementById('tablita');
		var fila=document.getElementById('field'+id);
		tabla.removeChild(fila);*/
    }
}


function carga_imagenes_varias(prid){
    var url = '/NebulaMarket/front/products_images?ProductsID=' + prid;
    var popup = window.open(url, 'ventana_imagenes', 'height=400,width=600,scrollbars=yes');
    popup.focus();
    return true;
}

function edit_relev_popup(secid,resid){
    var url = '/Sky/sections/mod_content?secid='+secid+'&resid='+resid;
    var popup = window.open(url, 'ventana', 'height=600,width=600,scrollbars=yes');
    popup.focus();
    return true;
}

function edit_infor_popup(secid,resid){
    var url = '/Sky/sections/mod_content?secid='+ secid +'&resid='+ resid;
    var popup = window.open(url, 'ventana', 'height=600,width=600,scrollbars=yes');
    popup.focus();
    return true;
}

function edit_titulo_popup(secid){
    var url = '/Sky/sections/informes?secid='+secid;
    var popup = window.open(url, 'ventana', 'height=400,width=400,scrollbars=yes');
    popup.focus();
    return true;
}

function edit_foto_popup(secid){
    var url = '/Sky/sections/add_resource?secid=' + secid;
    var popup = window.open(url, 'ventana', 'height=400,width=400,scrollbars=yes');
    popup.focus();
    return true;
}

function delete_marca(manufact_id){
    var url='/Actions/action_delete_fabricante?item=' + manufact_id;
    if(confirm('Confirmacion de Borrado: '+manufact_id) == true){
        makeHttpRequest(url);
		
        var tabla=document.getElementById('tablita');
        var fila=document.getElementById('field'+manufact_id);
        var linea=document.getElementById('linea_f'+manufact_id);
        tabla.removeChild(fila);
        tabla.removeChild(linea);
    }
}

function photo_popUp(url){
    var popup = window.open(url, 'ventana', 'height=550,width=700');
    popup.focus();
    return true;
}

function pagina_con_url2(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 search_item = $('input#search_item').val();
    if(typeof search_item == 'undefined')
        search_item = '';

	init=(pg-1)*pgshow;
	location='?'+ valores +'pginit='+init+'&pgend='+pgshow+'&search='+search+'&search_item=' + search_item;
}

function print_anteriores(valores){
    var actual = document.getElementById("actual").value;
    var i = (actual - 4);
    while(i < actual){
        if (i > 0)
            document.write("<span class='texto'> ::: <a href=\"javascript:pagina_con_url2("+ i +",'"+ valores +"');\">" + i + "</a></span>");
        i++;
    }
}

function print_posteriores(valores){
    var actual = document.getElementById("actual").value;
    var total = document.getElementById("total").value;
	
    var i = actual;
    while((i <= total) && (i < (actual + 4))){
        if (i != actual)
            document.write("<span class='texto'> ::: <a href=\"javascript:pagina_con_url2("+ i +", '"+ valores +"');\">" + i + "</a></span>");
        i++;
    }
    document.write("<span class='texto'> :::</span>");
}

function resizeIframe(idIframe){
    var miIframe = document.getElementById(idIframe);
    var alturaPagina = miIframe.contentWindow.document.body.scrollHeight+100;
    miIframe.style.height = alturaPagina;
			
    miIframe.setAttribute("style", "width:600px;height:" + alturaPagina + "px;");
}

function llamar_buscador(){
    var busqueda = document.getElementById("busqueda").value;
    location='/Portal/buscador?pginit=0&pgend=5&search='+busqueda;
}

function al_apretar_enter_busca(e){
    var keynum
    var keychar
    var numcheck

    if(window.event){ // IE
        keynum = e.keyCode
    }
    else if(e.which){ // Firefox
        keynum = e.which
    }
	
    //ejecutar al presionar Enter
    if (keynum == 13){
        llamar_buscador();
    }
}

/**
 * en esta funcion van los efectos que cargan luego de los loads de ayax
 */
function jQuery_galeria_chica(){
    // fade company
    if (document.getElementById('fade_galeria')) {
        $(document).ready(function(){
            $('#fade_galeria').innerfade({
                speed: 'slow',
                timeout: 4000,
                type: 'sequence',
                containerheight: '203px'
            });
        });
    }

}

/**
formulario de agregado de usuarios para recivir noticias
*/
function jQuery_action_news_add(){
    $(document).ready(function() {
        // bind form using ajaxForm
        $('#formnews').ajaxForm({
            // target identifies the element(s) to update with the server response
            target: '#htmlExampleTarget',

            // success identifies the function to invoke when the server response
            // has been received; here we apply a fade-in effect to the new content
            success: function() {
                $('#htmlExampleTarget').fadeIn('slow');
                OcultarDiv_tras_un_tiempo("htmlExampleTarget",5000);
                $('#formnews').clearForm();
            }
        });
    });
}

function jQuery_theweather_change(init){
    var seleccionado = init;


    $('#departamentos').change(function() {
  	
        if(seleccionado == 0){
            $('#theweather_container').toggle(600);
            seleccionado = 'departamentos';
        }else{
            $('#theweather_container').toggle(600);
            $('#theweather_container').toggle(600);
        }
    
        return false;
    });
	
}

/**
 * carga por ajax los relevamientos
 */
function carga_relev(relevid){
    $(document).ready( function() {
        var url = '/Resources/relevamiento';
        $('div#relevamientos').load(url, {
            relevid:relevid
        }, function(){
            // aplico el lightBox a las cargas por ajax
            $('a[rel*=lightbox]').lightBox();
        });

    } );

}

/**
 * carga por ajax los relevamientos
 */
function carga_infor(relevid){
    $(document).ready( function() {
        var url = '/Resources/informes';
        $('div#relevamientos').load(url, {
            relevid:relevid
        }, function(){
            // aplico el lightBox a las cargas por ajax
            $('a[rel*=lightbox]').lightBox();
        });

    } );

}




//** Ajax Tabs Content script v2.0-  Dynamic Drive DHTML code library (http://www.dynamicdrive.com)
//** Updated Oct 21st, 07 to version 2.0. Contains numerous improvements

//** Updated Feb 18th, 08 to version 2.1: Adds a public "tabinstance.cycleit(dir)" method to cycle forward or backward between tabs dynamically. Only .js file changed from v2.0.

var ddajaxtabssettings={}
ddajaxtabssettings.bustcachevar=1  //bust potential caching of external pages after initial request? (1=yes, 0=no)
ddajaxtabssettings.loadstatustext="<img src='/imagenes/cargando.gif' /> Cargando contenido..." 


////NO NEED TO EDIT BELOW////////////////////////

function ddajaxtabs(tabinterfaceid, contentdivid){
	this.tabinterfaceid=tabinterfaceid //ID of Tab Menu main container
	this.tabs=document.getElementById(tabinterfaceid).getElementsByTagName("a") //Get all tab links within container
	this.enabletabpersistence=true
	this.hottabspositions=[] //Array to store position of tabs that have a "rel" attr defined, relative to all tab links, within container
	this.currentTabIndex=0 //Index of currently selected hot tab (tab with sub content) within hottabspositions[] array
	this.contentdivid=contentdivid
	this.defaultHTML=""
	this.defaultIframe='<iframe src="about:blank" marginwidth="0" marginheight="0" frameborder="0" vspace="0" hspace="0" class="tabcontentiframe" style="width:100%; height:auto; min-height: 100px"></iframe>'
	this.defaultIframe=this.defaultIframe.replace(/<iframe/i, '<iframe name="'+"_ddajaxtabsiframe-"+contentdivid+'" ')
this.revcontentids=[] //Array to store ids of arbitrary contents to expand/contact as well ("rev" attr values)
	this.selectedClassTarget="link" //keyword to indicate which target element to assign "selected" CSS class ("linkparent" or "link")
}

ddajaxtabs.connect=function(pageurl, tabinstance){
	var page_request = false
	var bustcacheparameter=""
	if (window.XMLHttpRequest) // if Mozilla, IE7, Safari etc
		page_request = new XMLHttpRequest()
	else if (window.ActiveXObject){ // if IE6 or below
		try {
		page_request = new ActiveXObject("Msxml2.XMLHTTP")
		} 
		catch (e){
			try{
			page_request = new ActiveXObject("Microsoft.XMLHTTP")
			}
			catch (e){}
		}
	}
	else
		return false
	var ajaxfriendlyurl=pageurl.replace(/^http:\/\/[^\/]+\//i, "http://"+window.location.hostname+"/") 
	page_request.onreadystatechange=function(){ddajaxtabs.loadpage(page_request, pageurl, tabinstance)}
	if (ddajaxtabssettings.bustcachevar) //if bust caching of external page
		bustcacheparameter=(ajaxfriendlyurl.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
	page_request.open('GET', ajaxfriendlyurl+bustcacheparameter, true)
	page_request.send(null)
}

ddajaxtabs.loadpage=function(page_request, pageurl, tabinstance){
	var divId=tabinstance.contentdivid
	document.getElementById(divId).innerHTML=ddajaxtabssettings.loadstatustext //Display "fetching page message"
	if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){
		document.getElementById(divId).innerHTML=page_request.responseText
		ddajaxtabs.ajaxpageloadaction(pageurl, tabinstance)
	}
}

ddajaxtabs.ajaxpageloadaction=function(pageurl, tabinstance){
	tabinstance.onajaxpageload(pageurl) //call user customized onajaxpageload() function when an ajax page is fetched/ loaded
}

ddajaxtabs.getCookie=function(Name){ 
	var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
	if (document.cookie.match(re)) //if cookie found
		return document.cookie.match(re)[0].split("=")[1] //return its value
	return ""
}

ddajaxtabs.setCookie=function(name, value){
	document.cookie = name+"="+value+";path=/" //cookie value is domain wide (path=/)
}

ddajaxtabs.prototype={

	expandit:function(tabid_or_position){ //PUBLIC function to select a tab either by its ID or position(int) within its peers
		this.cancelautorun() //stop auto cycling of tabs (if running)
		var tabref=""
		try{
			if (typeof tabid_or_position=="string" && document.getElementById(tabid_or_position).getAttribute("rel")) //if specified tab contains "rel" attr
				tabref=document.getElementById(tabid_or_position)
			else if (parseInt(tabid_or_position)!=NaN && this.tabs[tabid_or_position].getAttribute("rel")) //if specified tab contains "rel" attr
				tabref=this.tabs[tabid_or_position]
		}
		catch(err){alert("Invalid Tab ID or position entered!")}
		if (tabref!="") //if a valid tab is found based on function parameter
			this.expandtab(tabref) //expand this tab
	},

	cycleit:function(dir, autorun){ //PUBLIC function to move foward or backwards through each hot tab (tabinstance.cycleit('foward/back') )
		if (dir=="next"){
			var currentTabIndex=(this.currentTabIndex<this.hottabspositions.length-1)? this.currentTabIndex+1 : 0
		}
		else if (dir=="prev"){
			var currentTabIndex=(this.currentTabIndex>0)? this.currentTabIndex-1 : this.hottabspositions.length-1
		}
		if (typeof autorun=="undefined") //if cycleit() is being called by user, versus autorun() function
			this.cancelautorun() //stop auto cycling of tabs (if running)
		this.expandtab(this.tabs[this.hottabspositions[currentTabIndex]])
	},

	setpersist:function(bool){ //PUBLIC function to toggle persistence feature
			this.enabletabpersistence=bool
	},

	loadajaxpage:function(pageurl){ //PUBLIC function to fetch a page via Ajax and display it within the Tab Content instance's container
		ddajaxtabs.connect(pageurl, this)
	},

	loadiframepage:function(pageurl){ //PUBLIC function to fetch a page and load it into the IFRAME of the Tab Content instance's container
		this.iframedisplay(pageurl, this.contentdivid)
	},

	setselectedClassTarget:function(objstr){ //PUBLIC function to set which target element to assign "selected" CSS class ("linkparent" or "link")
		this.selectedClassTarget=objstr || "link"
	},

	getselectedClassTarget:function(tabref){ //Returns target element to assign "selected" CSS class to
		return (this.selectedClassTarget==("linkparent".toLowerCase()))? tabref.parentNode : tabref
	},

	onajaxpageload:function(pageurl){ //PUBLIC Event handler that can invoke custom code whenever an Ajax page has been fetched and displayed
		//do nothing by default
	},

	expandtab:function(tabref){
		var relattrvalue=tabref.getAttribute("rel")
		//Get "rev" attr as a string of IDs in the format ",john,george,trey,etc," to easy searching through
		var associatedrevids=(tabref.getAttribute("rev"))? ","+tabref.getAttribute("rev").replace(/\s+/, "")+"," : ""
		if (relattrvalue=="#default")
			document.getElementById(this.contentdivid).innerHTML=this.defaultHTML
		else if (relattrvalue=="#iframe")
			this.iframedisplay(tabref.getAttribute("href"), this.contentdivid)
		else
			ddajaxtabs.connect(tabref.getAttribute("href"), this)
		this.expandrevcontent(associatedrevids)
		for (var i=0; i<this.tabs.length; i++){ //Loop through all tabs, and assign only the selected tab the CSS class "selected"
			this.getselectedClassTarget(this.tabs[i]).className=(this.tabs[i].getAttribute("href")==tabref.getAttribute("href"))? "selected" : ""
		}
		if (this.enabletabpersistence) //if persistence enabled, save selected tab position(int) relative to its peers
			ddajaxtabs.setCookie(this.tabinterfaceid, tabref.tabposition)
		this.setcurrenttabindex(tabref.tabposition) //remember position of selected tab within hottabspositions[] array
	},

	iframedisplay:function(pageurl, contentdivid){
		if (typeof window.frames["_ddajaxtabsiframe-"+contentdivid]!="undefined"){
			try{delete window.frames["_ddajaxtabsiframe-"+contentdivid]} //delete iframe within Tab content container if it exists (due to bug in Firefox)
			catch(err){}
		}
		document.getElementById(contentdivid).innerHTML=this.defaultIframe
		window.frames["_ddajaxtabsiframe-"+contentdivid].location.replace(pageurl) //load desired page into iframe
	},


	expandrevcontent:function(associatedrevids){
		var allrevids=this.revcontentids
		for (var i=0; i<allrevids.length; i++){ //Loop through rev attributes for all tabs in this tab interface
			//if any values stored within associatedrevids matches one within allrevids, expand that DIV, otherwise, contract it
			document.getElementById(allrevids[i]).style.display=(associatedrevids.indexOf(","+allrevids[i]+",")!=-1)? "block" : "none"
		}
	},

	setcurrenttabindex:function(tabposition){ //store current position of tab (within hottabspositions[] array)
		for (var i=0; i<this.hottabspositions.length; i++){
			if (tabposition==this.hottabspositions[i]){
				this.currentTabIndex=i
				break
			}
		}
	},

	autorun:function(){ //function to auto cycle through and select tabs based on a set interval
		this.cycleit('next', true)
	},

	cancelautorun:function(){
		if (typeof this.autoruntimer!="undefined")
			clearInterval(this.autoruntimer)
	},

	init:function(automodeperiod){
		var persistedtab=ddajaxtabs.getCookie(this.tabinterfaceid) //get position of persisted tab (applicable if persistence is enabled)
		var persisterror=true //Bool variable to check whether persisted tab position is valid (can become invalid if user has modified tab structure)
		this.automodeperiod=automodeperiod || 0
		this.defaultHTML=document.getElementById(this.contentdivid).innerHTML
		for (var i=0; i<this.tabs.length; i++){
			this.tabs[i].tabposition=i //remember position of tab relative to its peers
			if (this.tabs[i].getAttribute("rel")){
				var tabinstance=this
				this.hottabspositions[this.hottabspositions.length]=i //store position of "hot" tab ("rel" attr defined) relative to its peers
				this.tabs[i].onclick=function(){
					tabinstance.expandtab(this)
					tabinstance.cancelautorun() //stop auto cycling of tabs (if running)
					return false
				}
				if (this.tabs[i].getAttribute("rev")){ //if "rev" attr defined, store each value within "rev" as an array element
					this.revcontentids=this.revcontentids.concat(this.tabs[i].getAttribute("rev").split(/\s*,\s*/))
				}
				if (this.enabletabpersistence && parseInt(persistedtab)==i || !this.enabletabpersistence && this.getselectedClassTarget(this.tabs[i]).className=="selected"){
					this.expandtab(this.tabs[i]) //expand current tab if it's the persisted tab, or if persist=off, carries the "selected" CSS class
					persisterror=false //Persisted tab (if applicable) was found, so set "persisterror" to false
				}
			}
		} //END for loop
		if (persisterror) //if an error has occured while trying to retrieve persisted tab (based on its position within its peers)
			this.expandtab(this.tabs[this.hottabspositions[0]]) //Just select first tab that contains a "rel" attr
		if (parseInt(this.automodeperiod)>500 && this.hottabspositions.length>1){
			this.autoruntimer=setInterval(function(){tabinstance.autorun()}, this.automodeperiod)
		}
	} //END int() function

} //END Prototype assignment

// <script>

// Copyright (C) 2005 Ilya S. Lyubinskiy. All rights reserved.
// Technical support: http://www.php-development.ru/
// This code featured on/availabe at Dynamic Drive code library: http://www.dynamicdrive.com
//
// YOU MAY NOT
// (1) Remove or modify this copyright notice.
// (2) Distribute this code, any part or any modified version of it.
//     Instead, you can link to the homepage of this code:
//     http://www.php-development.ru/javascripts/dropdown.php
//
// YOU MAY
// (1) Use this code on your website.
// (2) Use this code as a part of another product provided that
//     its main use is not creating javascript menus.
//
// NO WARRANTY
// This code is provided "as is" without warranty of any kind, either
// expressed or implied, including, but not limited to, the implied warranties
// of merchantability and fitness for a particular purpose. You expressly
// acknowledge and agree that use of this code is at your own risk.

// If you find my script useful, you can support my site in the following ways:
// 1. Vote for the script at HotScripts.com (you can do it on my site)
// 2. Link to the homepage of this script or to the homepage of my site:
//    http://www.php-development.ru/javascripts/smart-forms.php
//    http://www.php-development.ru/
//    You will get 50% commission on all orders made by your referrals.
//    More information can be found here:
//    http://www.php-development.ru/affiliates.php


// ----- Popup Control ---------------------------------------------------------

function at_display_a(x)
{
  win = window.open();
  for (var i in x) win.document.write(i+' = '+x[i]+'<br>');
}

// ----- Show Aux -----

function at_show_a_aux_a(parent_a, child_a)
{
  var p = document.getElementById(parent_a);
  var c = document.getElementById(child_a);

  var top  = (c["at_position"] == "y") ? p.offsetHeight+2 : 0;
  var left = (c["at_position"] == "x") ? p.offsetWidth +2 : 0;

  for (; p; p = p.offsetParent)
  {
    top  += p.offsetTop;
    left += p.offsetLeft;
  }

  c.style.position   = "absolute";
  c.style.top        = top +'px';
  c.style.left       = left+'px';
  c.style.visibility = "visible";
}

// ----- Show -----

function at_show_a()
{
  p = document.getElementById(this["at_parent_a"]);
  c = document.getElementById(this["at_child_a" ]);

  at_show_a_aux_a(p.id, c.id);

  clearTimeout(c["at_timeout"]);
}

// ----- Hide -----

function at_hide_a()
{
  c = document.getElementById(this["at_child_a"]);

  c["at_timeout"] = setTimeout("document.getElementById('"+c.id+"').style.visibility = 'hidden'", 333);
}

// ----- Click -----

function at_click_a()
{
  p = document.getElementById(this["at_parent_a"]);
  c = document.getElementById(this["at_child_a" ]);

  if (c.style.visibility != "visible") at_show_a_aux_a(p.id, c.id);
  else c.style.visibility = "hidden";

  return false;
}

// ----- Attach -----

// PARAMETERS:
// parent1   - id of visible html element
// child    - id of invisible html element that will be dropdowned
// showtype - "click" = you should click the parent1 to show/hide the child
//            "hover" = you should place the mouse over the parent1 to show
//                      the child
// position - "x" = the child is displayed to the right of the parent1
//            "y" = the child is displayed below the parent1
// cursor   - Omit to use default cursor or check any CSS manual for possible
//            values of this field

function at_attach_a(parent_a, child_a, showtype, position, cursor)
{
  p = document.getElementById(parent_a);
  c = document.getElementById(child_a);

  p["at_parent_a"]     = p.id;
  c["at_parent_a"]     = p.id;
  p["at_child_a"]      = c.id;
  c["at_child_a"]      = c.id;
  p["at_position"]   = position;
  c["at_position"]   = position;

  c.style.position   = "absolute";
  c.style.visibility = "hidden";

  if (cursor != undefined) p.style.cursor = cursor;

  switch (showtype)
  {
    case "click":
      p.onclick     = at_click_a;
      p.onmouseout  = at_hide_a;
      c.onmouseover = at_show_a;
      c.onmouseout  = at_hide_a;
      break;
    case "hover":
      p.onmouseover = at_show_a;
      p.onmouseout  = at_hide_a;
      c.onmouseover = at_show_a;
      c.onmouseout  = at_hide_a;
      break;
  }
}


////NO need to edit /////////////

/***********************************************
* Swiss Army Image slide show script  - © John Davenport Scheuer: http://home.comcast.net/~jscheuer1/
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full original source code
***********************************************/

function preloadctrl(im){
if (typeof im=='string'){
var imo=new Image();
imo.src=im;
}
}

if(document.images&&typeof preload_ctrl_images!='undefined'&&preload_ctrl_images){
var ctrlimgs=[previmg, stopimg, playimg, nextimg]
for (var i_tem = 0; i_tem < ctrlimgs.length; i_tem++)
if (ctrlimgs[i_tem])
preloadctrl(ctrlimgs[i_tem])
}

var iss=[]; //array to cache inter_slide instances

function inter_slide(){
if(!document.images||arguments.length==0)
return;
var imgs=arguments[0];
var width=null, height=null, delay=null;
if(arguments.length==2)
delay=arguments[1];
else if(arguments.length==3||arguments.length==4)
width=arguments[1], height=arguments[2], delay=arguments[3]? arguments[3] : null;
this.dom=(document.getElementById) //modern dom browsers
this.da=document.all
this.delay=imgs.delay? imgs.delay : delay? delay : 3000+iss.length*750;
this.nextimgidx=0;
iss[this.issid=iss.length]=this;
this.imgs=imgs;
if (imgs.random)
this.imgs.sort(function() {return 0.5 - Math.random();}) //thanks to Mike (aka Mwinter) :)
this.imgborder=imgs.border? parseInt(imgs.border) : 0;
if (!this.dom){
this.postimgs=new Array() //preload imgs
for (p=0;p<imgs.length;p++){
this.postimgs[p]=new Image()
this.postimgs[p].src=this.imgs[p][0]
}
}

if (this.dom){ //if modern browsers (ie: Firefox, IE5+)
this.faded=0;
this.loadimgidx=[];
this.fade=!imgs.nofade;
if(this.fade)
this.degree=10 //initial opacity degree (10%)
this.pausecheck=imgs.pause;
this.mouseovercheck=0
this.canvasbase="canvas"+this.issid
this.curcanvas=this.canvasbase+"_0"
this.descriptions=!imgs.no_descriptions;
this.man_start=imgs.manual_start;
this.addbr=!imgs.no_added_linebreaks;
this.no_auto=imgs.no_auto;
this.onclick=imgs.onclick;
this.specs=imgs.specs;
this.counter=imgs.counter;
this.ics=imgs.image_controls;
this.jumpto=imgs.jumpto;
this.no_c=imgs.no_controls;
this.target=imgs.target;
this.ualt=imgs.use_alt;
this.utit=imgs.use_title;
this.fadecolor=imgs.fadecolor;
this.ibut_hc=imgs.button_highlight;
this.dp=imgs.desc_prefix? imgs.desc_prefix : ' ';
this.imbcolor=imgs.border_color;
this.imbstyle=imgs.border_style;
this.width=imgs.width? imgs.width : width? width : null
this.width=this.width? this.width+this.imgborder*2 : null;
this.height=imgs.height? imgs.height : height? height : null
this.height=this.height? this.height+this.imgborder*2 : null;
var ief='', dims='';
if(this.width||this.height)
dims=this.width&&this.height? 'width:'+this.width+'px;height:'+this.height+'px;' : this.width? 'width:'+this.width+'px;' : 'height:'+this.height+'px;';
if(this.fade&&document.body&&document.body.style)
ief=document.body.filters? 'filter:progid:DXImageTransform.Microsoft.alpha(opacity=0);' : typeof document.body.style.opacity=='string'? 'opacity:0;' : 'opacity:0.10;-moz-opacity:0.10;-khtml-opacity:0.10;';
var brs=this.addbr? '' : '';
if (imgs.controls_top){
this.controls();
document.write(brs)
}
document.write('<div align="center"><div id="master'+this.issid+'" style="position:relative;'+dims+'overflow:hidden;margin:0 auto;"><div id="'+this.canvasbase+'_0" style="position:absolute;'+dims+'top:0;left:0;'+ief+'background-color:'+(imgs.fadecolor? imgs.fadecolor : 'white')+'"><\/div><div id="'+this.canvasbase+'_1" style="position:absolute;'+dims+'top:0;left:0;'+ief+'background-color:'+(imgs.fadecolor? imgs.fadecolor : 'white')+'"><\/div><\/div><\/div>')
if(this.descriptions)
document.write(brs+'<div align="left" class="galeria">'+this.dp+'<span id="imgdsc'+this.issid+'">&nbsp;<\/span></div>\n');
if(this.counter&&!this.descriptions)
document.write(brs);
if(this.counter)
this.cntrl()
if (!imgs.controls_top){
document.write(this.ics? '' : brs);
this.controls();
}
}
else
document.write('<div align="center"><img name="defaultslide'+this.issid+'" src="'+this.postimgs[0].src+'"><\/div>')


if (this.dom) //if modern browsers such as Firefox, IE5+
this.startit()
else{
this.nextimgidx++
setInterval("iss["+this.issid+"].rotateimg()", this.delay)
}
}

inter_slide.prototype.cntrl=function(){
this.cpad=this.imgs.length.toString().length;
document.write('<div align="center" class="texto">Imagen&nbsp;<b><span id="thecnt'+this.issid+'"><\/span><\/b>&nbsp;de&nbsp;<b>'+this.imgs.length+'<\/b></span><\/div>');
}

inter_slide.prototype.controls=function(){
var brs=this.addbr? '<br>' : ' &nbsp;';
if(!this.ics&&!this.no_c)
document.write('<div align="center" class="texto"><input id="prev'+this.issid+'" disabled type="button" value=" << " onclick="iss['+this.issid+'].changeimg(false, \'nav\');">\n'+
(this.no_auto? '&nbsp;&nbsp;&nbsp;' : ' <input id="gostp'+this.issid+'" type="button" value=" Stop " onclick="iss['+this.issid+'].gostop(this);">\n')+
' <input id="next'+this.issid+'" disabled type="button" value=" >> " onclick="iss['+this.issid+'].changeimg(true, \'nav\');">'+(this.jumpto? brs+'Jump to: <input disabled type="text" size="'+this.imgs.length.toString().length+'" id="goto'+this.issid+'" onkeydown="iss['+this.issid+'].jumper(event);"><input id="go'+this.issid+'" disabled type="button" onclick="iss['+this.issid+'].jumper();" value="GO">' : '')+'<\/div>')
else if(this.ics&&!this.no_c){
var op=document.body.filters? ' style="filter:alpha(opacity=100);"' : ' style="opacity:'+(this.man_start? 0.99 : 0.45)+';"';
document.write('<table align="center" cellpadding="0" cellspacing="10"><tr><td valign="middle" align="center" style="padding:2px 2px 1px 2px;"><input'+op+' onmouseover="iss['+this.issid+'].ibute(this,1);" onmouseout="iss['+this.issid+'].ibute(this,2);" onmousedown="iss['+this.issid+'].ibute(this,3);" onmouseup="iss['+this.issid+'].ibute(this,4);" type="image" title="Previous" id="prev'+this.issid+'" src="'+previmg+'" onclick="iss['+this.issid+'].changeimg(false, \'nav\');"><\/td>'+(this.no_auto? '<td>&nbsp;<\/td>' : '<td valign="middle" align="center" style="padding:2px 2px 1px 2px;"><input onmouseover="iss['+this.issid+'].ibute(this,1);" onmouseout="iss['+this.issid+'].ibute(this,2);" onmousedown="iss['+this.issid+'].ibute(this,3);" onmouseup="iss['+this.issid+'].ibute(this,4);" title="Stop" type="image" id="gostp'+this.issid+'" src="'+(this.g_fPlayMode? playimg : stopimg)+'" onclick="iss['+this.issid+'].gostop(this);"><\/td>')+'<td valign="middle" align="center" style="padding:2px 2px 1px 2px;"><input'+op+' onmouseover="iss['+this.issid+'].ibute(this,1);" onmouseout="iss['+this.issid+'].ibute(this,2);" onmousedown="iss['+this.issid+'].ibute(this,3);" onmouseup="iss['+this.issid+'].ibute(this,4);" type="image" title="Next" id="next'+this.issid+'" src="'+nextimg+'" onclick="iss['+this.issid+'].changeimg(true, \'nav\');"><\/td><\/tr><\/table>\n');
}
else
this.no_c=1;
}

inter_slide.prototype.jumper=function(e){
var key;
if(typeof e=='object')
key=e.keyCode? e.keyCode : e.which? e.which : 1;
if(key&&key!==13)
return;
var num=typeof e=='number'? e : parseInt(this.go('goto'+this.issid).value);
if(num<=this.imgs.length&&num>0){
this.nextimgidx=num-2;
this.changeimg(true, 'jump');
}
}

inter_slide.prototype.ibute=function(obj, i){
if(!obj.parentNode)
return;
if(i==1)
obj.parentNode.style.backgroundColor=this.ibut_hc? this.ibut_hc : 'yellow';
else if(i==2)
obj.parentNode.style.backgroundColor='transparent';
else if(i==3){
obj.parentNode.style.borderTop=obj.parentNode.style.borderLeft='1px solid gray';
obj.parentNode.style.paddingRight='1px';obj.parentNode.style.paddingBottom=0;
}
if (i==2||i==4){
obj.parentNode.style.borderTop=obj.parentNode.style.borderLeft='none';
obj.parentNode.style.paddingRight='2px';obj.parentNode.style.paddingBottom='1px';
}
}

inter_slide.prototype.fadepic=function(){
if (this.fade&&this.degree<100){
this.faded=0
this.degree+=10
if (this.tempobj.filters&&this.tempobj.filters[0]){
if (typeof this.tempobj.filters[0].opacity=="number") //if IE6+
this.tempobj.filters[0].opacity=this.degree
else //else if IE5.5-
this.tempobj.style.filter="alpha(opacity="+this.degree+")"
}
else if (this.tempobj.style.MozOpacity)
this.tempobj.style.MozOpacity=this.degree/101
else if (this.tempobj.style.KhtmlOpacity)
this.tempobj.style.KhtmlOpacity=this.degree/100
else if (this.tempobj.style.opacity&&!this.tempobj.filters)
this.tempobj.style.opacity=this.degree/101
}
else{
this.faded=1
clearInterval(this.fadeclear)
this.nextcanvas=(this.curcanvas==this.canvasbase+"_0")? this.canvasbase+"_0" : this.canvasbase+"_1"
this.tempobj=this.go(this.nextcanvas)
if(this.playing)
this.changeimg()
}
}

inter_slide.prototype.populateslide=function(picobj, picidx){
if(document.getElementsByTagName){
if(picobj.getElementsByTagName('a')[0]&&picobj.getElementsByTagName('a')[0].onclick)
picobj.getElementsByTagName('a')[0].onclick=null;
if(picobj.getElementsByTagName('img')[0]&&picobj.getElementsByTagName('img')[0].onload)
picobj.getElementsByTagName('img')[0].onload=null;
}
picobj.style.backgroundColor=this.imgs[picidx].fadecolor? this.imgs[picidx].fadecolor : this.fadecolor? this.fadecolor : 'white';
var slideHTML='<table border="0" cellpadding="0" cellspacing="0" width="100%" height="100%"><tr><td width="100%" height="100%" align="center" valign="middle" style="background:transparent none;">'
if (this.imgs[picidx][2]){ //if associated link exists for img
var specs=this.imgs[picidx][4]? ", '"+this.imgs[picidx][4]+"'" : this.specs? ", '"+this.specs+"'" : '';
slideHTML+='<a href="'+this.imgs[picidx][2]+'"'+(this.imgs[picidx][3]? ' target="'+this.imgs[picidx][3]+'"' : this.target? ' target="'+this.target+'"' : '')+' onclick="'+(this.onclick? this.onclick : 'window.open(this.href, (this.target? this.target : \'_self\')'+specs+');return false;')+'">'
}
slideHTML+='<img id="theimg'+picidx+'_'+this.issid+'" src="'+(this.loadimgidx[picidx]&&typeof this.loadimgidx[picidx].complete=='boolean'&&this.loadimgidx[picidx].complete? this.loadimgidx[picidx].src : this.imgs[picidx][0])+'" alt="'+(this.ualt? this.imgs[picidx][1] : 'Slide Show Image')+'" title="'+(this.utit? this.imgs[picidx][1] : '')+'" '+(this.imbcolor&&!this.imgs[picidx].noborder? 'style="border:'+this.imgborder+'px '+(this.imbstyle? this.imbstyle : 'solid')+' '+this.imbcolor+';"' : 'border="'+(this.imgs[picidx].noborder? '0' : this.imgborder)+'"')+(!this.width||!this.height? ' onload="iss['+this.issid+'].imgload(this);"' : '')+'>'
if (this.imgs[picidx][2]) //if associated link exists for img
slideHTML+='<\/a>'
slideHTML+='<\/td><\/tr><\/table>'
picobj.innerHTML=slideHTML
}

inter_slide.prototype.buttons=function(bool){
if(this.no_c)
return;
var next=this.go('next'+this.issid), prev=this.go('prev'+this.issid);
next.disabled=prev.disabled=!bool;
next.title=bool? 'next' : '';
prev.title=bool? 'previous' : '';
if(this.jumpto&&!this.ics)
this.go('go'+this.issid).disabled=this.go('goto'+this.issid).disabled=!bool;
if(this.ics){
if(!this.no_auto){
var go=this.go('gostp'+this.issid)
go.title=bool? 'Play' : 'Stop';
go.src=bool? playimg : stopimg;
}
if(prev.filters&&prev.parentNode)
prev.parentNode.style.filter=next.parentNode.style.filter='alpha(opacity='+(bool? 100 : 45)+')';
else if(prev.style.opacity&&!prev.filters)
prev.style.opacity=next.style.opacity=bool? 0.99 : 0.45;
}
}

inter_slide.prototype.imgload=function(el){
if(!el&&!this.imgel)
return;
var el=el? el : this.imgel;
if(el.width==0||el.height==0){
this.imgel=el;
var cacheobj=this;
clearTimeout(this.getdim)
this.getdim=setTimeout(function(){cacheobj.imgload()}, 300)
return;
}
var m=this.go('master'+this.issid).style, c0=this.go(this.canvasbase+'_0').style, c1=this.go(this.canvasbase+'_1').style;
if(!this.width){
this.width=el.width+this.imgborder*2;
m.width = c0.width = c1.width = this.width+'px';
}
if(!this.height){
this.height=el.height+this.imgborder*2;
m.height = c0.height = c1.height = this.height+'px';
}
}

inter_slide.prototype.changeimg=function(bool,nav){
if(this.playing){
this.buttons(false)
this.nextimgidx=(this.keeptrack()<this.imgs.length-1)? this.keeptrack()+1 : 0
this.populateslide(this.tempobj, this.nextimgidx)
if(bool)
this.rotateimg()
else{
clearTimeout(this.inprocess)
this.inprocess=setTimeout("iss["+this.issid+"].rotateimg()", this.delay)
}
}
else {
if(!this.faded){
if(nav&&nav=='nav')
return;
this.nextimgidx=this.keeptrack()+(bool? 1 : -1)
this.nextimgidx=(this.nextimgidx<this.imgs.length)? this.nextimgidx : this.nextimgidx-this.imgs.length
this.nextimgidx=(this.nextimgidx>-1)? this.nextimgidx : this.imgs.length+this.nextimgidx
return;
}
if(this.fadeclear)
clearInterval(this.fadeclear);
if(bool){
var loadidx=this.nextimgidx+2
loadidx=(loadidx<this.imgs.length)? loadidx : loadidx-this.imgs.length;
loadidx=(loadidx>-1)? loadidx : this.imgs.length+loadidx;
this.loadimgidx[loadidx]=new Image();
this.loadimgidx[loadidx].src=this.imgs[loadidx][0];
}
else{
var loadidx=this.nextimgidx-2
loadidx=(loadidx<this.imgs.length)? loadidx : loadidx-this.imgs.length
loadidx=(loadidx>-1)? loadidx : this.imgs.length+loadidx
this.loadimgidx[loadidx]=new Image();
this.loadimgidx[loadidx].src=this.imgs[loadidx][0];
}
if(nav&&nav=='jump')
this.nextimgidx++;
else
this.nextimgidx=this.keeptrack()+(bool? 1 : -1)
this.nextimgidx=(this.nextimgidx<this.imgs.length)? this.nextimgidx : this.nextimgidx-this.imgs.length
this.nextimgidx=(this.nextimgidx>-1)? this.nextimgidx : this.imgs.length+this.nextimgidx
this.populateslide(this.tempobj, this.nextimgidx)
this.rotateimg()
}
}

inter_slide.prototype.go=function(id){
return this.da? this.da[id] : document.getElementById(id);
}

inter_slide.prototype.rotateimg=function(){
if(this.dom){
var cimg=this.go('theimg'+this.nextimgidx+'_'+this.issid)? this.go('theimg'+this.nextimgidx+'_'+this.issid) : null;
if(cimg&&typeof cimg.complete=='boolean'&&!cimg.complete){
var cacheobj=this
clearTimeout(this.loading)
this.loading=setTimeout(function(){cacheobj.rotateimg()}, 300)
return;
}
if (this.mouseovercheck==1){
var cacheobj=this
clearTimeout(this.mousep)
this.mousep=setTimeout(function(){cacheobj.rotateimg()}, 100)
return;
}
if(this.fade)
this.resetit()
var crossobj=this.tempobj=this.go(this.curcanvas)
crossobj.style.zIndex++
var othercanvas=this.curcanvas==this.canvasbase+"_0"? this.go(this.canvasbase+"_1") : this.go(this.canvasbase+"_0");
othercanvas.style.zIndex=0;
if(this.descriptions)
this.go('imgdsc'+this.issid).innerHTML = this.imgs[this.keeptrack()][1];
if(this.counter){
var padit='';
for (var p=0; p<this.cpad-(this.nextimgidx+1).toString().length; p++)
padit+='<span style="visibility:hidden;">0</span>';
this.go('thecnt'+this.issid).innerHTML = padit+(this.keeptrack()<this.imgs.length? this.keeptrack()+1 : 1);
}
if (this.jumpto)
this.go('goto'+this.issid).value=this.keeptrack()<this.imgs.length? this.keeptrack()+1 : 1;
this.jumperidx=this.keeptrack()<this.imgs.length? this.keeptrack()+1 : 1;
var fadeobj=this
clearInterval(this.fadeclear)
this.fadeclear=setInterval(function(){fadeobj.fadepic()},50)
this.curcanvas=(this.curcanvas==this.canvasbase+"_0")? this.canvasbase+"_1" : this.canvasbase+"_0"
}
else{
var v4imgobj=document.images['defaultslide'+this.issid]
v4imgobj.src=this.postimgs[this.nextimgidx].src
this.nextimgidx=(this.nextimgidx<this.imgs.length-1)? this.nextimgidx+1 : 0
}
}

inter_slide.prototype.resetit=function(){
this.degree=10
var crossobj=this.go(this.curcanvas)
if (crossobj.filters&&crossobj.filters[0]){
if (typeof crossobj.filters[0].opacity=="number") //if IE6+
crossobj.filters(0).opacity=this.degree
else //else if IE5.5-
crossobj.style.filter="alpha(opacity="+this.degree+")"
}
else if (crossobj.style.MozOpacity)
crossobj.style.MozOpacity=this.degree/101
else if (crossobj.style.KhtmlOpacity)
crossobj.style.KhtmlOpacity=this.degree/100
else if (crossobj.style.opacity&&!crossobj.filters)
crossobj.style.opacity=this.degree/101
}

inter_slide.prototype.startit=function(){
this.playing=1
var crossobj=this.go(this.curcanvas)
this.populateslide(crossobj, this.nextimgidx)
if (this.pausecheck==1){ //if slideshow should pause onmouseover
var cacheobj=this
var crossobjcontainer=this.go("master"+this.issid)
crossobjcontainer.onmouseover=function(){cacheobj.mouseovercheck=1}
crossobjcontainer.onmouseout=function(){cacheobj.mouseovercheck=0}
}
this.rotateimg()
if(this.no_auto)
this.gostop();
else if(this.man_start)
this.gostop(this.go('gostp'+this.issid));
else if(this.ics&&document.body.filters){ //kludge for IE5.5 bug
this.buttons(false);
}
}

inter_slide.prototype.gostop=function(el){
if(el)
el.value=el.value==' Stop '? ' Play ' : ' Stop ';
if(this.inprocess&&this.playing){
clearTimeout(this.inprocess);
this.nextimgidx-=this.faded;
}
this.playing=!this.playing;
if(this.playing){
clearInterval(this.fadeclear)
this.faded=1
this.changeimg(true);
}
else{
var loadidx=(this.keeptrack()<this.imgs.length-1)? this.keeptrack()+1 : 0
this.loadimgidx[loadidx]=new Image();
this.loadimgidx[loadidx].src=this.imgs[loadidx][0];
this.jumper(this.jumperidx? this.jumperidx : 0)
this.buttons(true);
}
}

inter_slide.prototype.keeptrack=function(){
if(!document.getElementsByTagName)
return this.nextimgidx;
var canvases=[this.go('canvas'+this.issid+'_0'), this.go('canvas'+this.issid+'_1')]
if(canvases[0].style.zIndex>canvases[1].style.zIndex&&canvases[0].getElementsByTagName("img")[0])
return parseInt(canvases[0].getElementsByTagName('img')[0].id.replace(/theimg/, ''))
else if(canvases[1].getElementsByTagName("img")[0])
return parseInt(canvases[1].getElementsByTagName('img')[0].id.replace(/theimg/, ''))
else
return this.nextimgidx;
}

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

$(document).ready( function() {

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

    // 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)
            //$(this).append(data);
        }

    });

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

} );


