/** Generated: 3/22/2010 11:14:14 AM  **/
/*
 * jQuery 1.2.6 - 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-24 14:22:17 -0400 (Sat, 24 May 2008) $
 * $Rev: 5685 $
 */
(function(){var _jQuery=window.jQuery,_$=window.$;var jQuery=window.jQuery=window.$=function(selector,context){return new jQuery.fn.init(selector,context);};var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/,isSimple=/^.[^:#\[\.]*$/,undefined;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(selector.nodeType){this[0]=selector;this.length=1;return this;}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);return jQuery(elem);}selector=[];}}else
return jQuery(context).find(selector);}else if(jQuery.isFunction(selector))return jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(jQuery.makeArray(selector));},jquery:"1.2.6",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;return jQuery.inArray(elem&&elem.jquery?elem[0]:elem,this);},attr:function(name,value,type){var options=name;if(name.constructor==String)if(value===undefined)return this[0]&&jQuery[type||"attr"](this[0],name);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 this.pushStack(jQuery.unique(jQuery.merge(this.get(),typeof selector=='string'?jQuery(selector):jQuery.makeArray(selector))));},is:function(selector){return!!selector&&jQuery.multiFilter(selector,this).length>0;},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;}if(value.constructor==Number)value+='';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=jQuery.makeArray(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[0]?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===undefined){var data=this.triggerHandler("getData"+parts[1]+"!",[parts[0]]);if(data===undefined&&this.length)data=jQuery.data(this[0],key);return data===undefined&&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.fn.init.prototype=jQuery.fn;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);}function now(){return+new Date;}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==i){target=this;--i;}for(;i<length;i++)if((options=arguments[i])!=null)for(var name in options){var src=target[name],copy=options[name];if(target===copy)continue;if(deep&&copy&&typeof copy=="object"&&!copy.nodeType)target[name]=jQuery.extend(deep,src||(copy.length!=null?[]:{}),copy);else if(copy!==undefined)target[name]=copy;}return target;};var expando="jQuery"+now(),uuid=0,windowData={},exclude=/z-?index|font-?weight|opacity|zoom|line-?height/i,defaultView=document.defaultView||{};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&&/^[\s[]?function/.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.insertBefore(script,head.firstChild);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){var name,i=0,length=object.length;if(args){if(length==undefined){for(name in object)if(callback.apply(object[name],args)===false)break;}else
for(;i<length;)if(callback.apply(object[i++],args)===false)break;}else{if(length==undefined){for(name in object)if(callback.call(object[name],name,object[name])===false)break;}else
for(var 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,style=elem.style;function color(elem){if(!jQuery.browser.safari)return false;var ret=defaultView.getComputedStyle(elem,null);return!ret||ret.getPropertyValue("color")=="";}if(name=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(style,"opacity");return ret==""?"1":ret;}if(jQuery.browser.opera&&name=="display"){var save=style.outline;style.outline="0 solid black";style.outline=save;}if(name.match(/float/i))name=styleFloat;if(!force&&style&&style[name])ret=style[name];else if(defaultView.getComputedStyle){if(name.match(/float/i))name="float";name=name.replace(/([A-Z])/g,"-$1").toLowerCase();var computedStyle=defaultView.getComputedStyle(elem,null);if(computedStyle&&!color(elem))ret=computedStyle.getPropertyValue(name);else{var swap=[],stack=[],a=elem,i=0;for(;a&&color(a);a=a.parentNode)stack.unshift(a);for(;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":(computedStyle&&computedStyle.getPropertyValue(name))||"";for(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 left=style.left,rsLeft=elem.runtimeStyle.left;elem.runtimeStyle.left=elem.currentStyle.left;style.left=ret||0;ret=style.pixelLeft+"px";style.left=left;elem.runtimeStyle.left=rsLeft;}}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+='';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 notxml=!jQuery.isXMLDoc(elem),set=value!==undefined,msie=jQuery.browser.msie;name=notxml&&jQuery.props[name]||name;if(elem.tagName){var special=/href|src|style/.test(name);if(name=="selected"&&jQuery.browser.safari)elem.parentNode.selectedIndex;if(name in elem&&notxml&&!special){if(set){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)throw"type property can't be changed";elem[name]=value;}if(jQuery.nodeName(elem,"form")&&elem.getAttributeNode(name))return elem.getAttributeNode(name).nodeValue;return elem[name];}if(msie&&notxml&&name=="style")return jQuery.attr(elem.style,"cssText",value);if(set)elem.setAttribute(name,""+value);var attr=msie&&notxml&&special?elem.getAttribute(name,2):elem.getAttribute(name);return attr===null?undefined:attr;}if(msie&&name=="opacity"){if(set){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(value)+''=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter&&elem.filter.indexOf("opacity=")>=0?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100)+'':"";}name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});if(set)elem[name]=value;return elem[name];},trim:function(text){return(text||"").replace(/^\s+|\s+$/g,"");},makeArray:function(array){var ret=[];if(array!=null){var i=array.length;if(i==null||array.split||array.setInterval||array.call)ret[0]=array;else
while(i)ret[--i]=array[i];}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){var i=0,elem,pos=first.length;if(jQuery.browser.msie){while(elem=second[i++])if(elem.nodeType!=8)first[pos++]=elem;}else
while(elem=second[i++])first[pos++]=elem;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))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)ret[ret.length]=value;}return ret.concat.apply([],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,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing"}});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");};});function num(elem,prop){return elem[0]&&parseInt(jQuery.curCSS(elem[0],prop,true),10)||0;}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,re=quickChild,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=[],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&&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)elem=window;if(!handler.guid)handler.guid=this.guid++;if(data!=undefined){var fn=handler;handler=this.proxy(fn,function(){return fn.apply(this,arguments);});handler.data=data;}var events=jQuery.data(elem,"events")||jQuery.data(elem,"events",{}),handle=jQuery.data(elem,"handle")||jQuery.data(elem,"handle",function(){if(typeof jQuery!="undefined"&&!jQuery.event.triggered)return jQuery.event.handle.apply(arguments.callee.elem,arguments);});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({type:type,target:elem,preventDefault:function(){},stopPropagation:function(){},timeStamp:now()});data[0][expando]=true;}data[0].type=type;if(exclusive)data[0].exclusive=true;var handle=jQuery.data(elem,"handle");if(handle)val=handle.apply(elem,data);if((!fn||(jQuery.nodeName(elem,'a')&&type=="click"))&&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,ret,namespace,all,handlers;event=arguments[0]=jQuery.event.fix(event||window.event);namespace=event.type.split(".");event.type=namespace[0];namespace=namespace[1];all=!namespace&&!event.exclusive;handlers=(jQuery.data(this,"events")||{})[event.type];for(var j in handlers){var handler=handlers[j];if(all||handler.type==namespace){event.handler=handler;event.data=handler.data;ret=handler.apply(this,arguments);if(val!==false)val=ret;if(ret===false){event.preventDefault();event.stopPropagation();}}}return val;},fix:function(event){if(event[expando]==true)return event;var originalEvent=event;event={originalEvent:originalEvent};var props="altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view wheelDelta which".split(" ");for(var i=props.length;i;i--)event[props[i]]=originalEvent[props[i]];event[expando]=true;event.preventDefault=function(){if(originalEvent.preventDefault)originalEvent.preventDefault();originalEvent.returnValue=false;};event.stopPropagation=function(){if(originalEvent.stopPropagation)originalEvent.stopPropagation();originalEvent.cancelBubble=true;};event.timeStamp=event.timeStamp||now();if(!event.target)event.target=event.srcElement||document;if(event.target.nodeType==3)event.target=event.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;},proxy:function(fn,proxy){proxy.guid=fn.guid=fn.guid||proxy.guid||this.guid++;return proxy;},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;event.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;event.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){var one=jQuery.event.proxy(fn||data,function(event){jQuery(this).unbind(event,one);return(fn||data).apply(this,arguments);});return this.each(function(){jQuery.event.add(this,type,one,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){return this[0]&&jQuery.event.trigger(type,data,this[0],false,fn);},toggle:function(fn){var args=arguments,i=1;while(i<args.length)jQuery.event.proxy(fn,args[i++]);return this.click(jQuery.event.proxy(fn,function(event){this.lastToggle=(this.lastToggle||0)%i;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.call(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:jQuery.fn.load,load:function(url,params,callback){if(typeof url!='string')return this._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=now();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:{url:location.href,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){s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));var jsonp,jsre=/=\?(&|$)/g,status,data,type=s.type.toUpperCase();if(s.data&&s.processData&&typeof s.data!="string")s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(type=="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&&type=="GET"){var ts=now();var ret=s.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+ts+"$2");s.url=ret+((ret==s.url)?(s.url.match(/\?/)?"&":"?")+"_="+ts:"");}if(s.data&&type=="GET"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++)jQuery.event.trigger("ajaxStart");var remote=/^(?:\w+:)?\/\/([^\/?#]+)/;if(s.dataType=="script"&&type=="GET"&&remote.test(s.url)&&remote.exec(s.url)[1]!=location.host){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 xhr=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();if(s.username)xhr.open(type,s.url,s.async,s.username,s.password);else
xhr.open(type,s.url,s.async);try{if(s.data)xhr.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)xhr.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");xhr.setRequestHeader("Accept",s.dataType&&s.accepts[s.dataType]?s.accepts[s.dataType]+", */*":s.accepts._default);}catch(e){}if(s.beforeSend&&s.beforeSend(xhr,s)===false){s.global&&jQuery.active--;xhr.abort();return false;}if(s.global)jQuery.event.trigger("ajaxSend",[xhr,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xhr&&(xhr.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xhr)&&"error"||s.ifModified&&jQuery.httpNotModified(xhr,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xhr,s.dataType,s.dataFilter);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xhr.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes)jQuery.lastModified[s.url]=modRes;if(!jsonp)success();}else
jQuery.handleError(s,xhr,status);complete();if(s.async)xhr=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)setTimeout(function(){if(xhr){xhr.abort();if(!requestDone)onreadystatechange("timeout");}},s.timeout);}try{xhr.send(s.data);}catch(e){jQuery.handleError(s,xhr,null,e);}if(!s.async)onreadystatechange();function success(){if(s.success)s.success(data,status);if(s.global)jQuery.event.trigger("ajaxSuccess",[xhr,s]);}function complete(){if(s.complete)s.complete(xhr,status);if(s.global)jQuery.event.trigger("ajaxComplete",[xhr,s]);if(s.global&&!--jQuery.active)jQuery.event.trigger("ajaxStop");}return xhr;},handleError:function(s,xhr,status,e){if(s.error)s.error(xhr,status,e);if(s.global)jQuery.event.trigger("ajaxError",[xhr,s,e]);},active:0,httpSuccess:function(xhr){try{return!xhr.status&&location.protocol=="file:"||(xhr.status>=200&&xhr.status<300)||xhr.status==304||xhr.status==1223||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpNotModified:function(xhr,url){try{var xhrRes=xhr.getResponseHeader("Last-Modified");return xhr.status==304||xhrRes==jQuery.lastModified[url]||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpData:function(xhr,type,filter){var ct=xhr.getResponseHeader("content-type"),xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0,data=xml?xhr.responseXML:xhr.responseText;if(xml&&data.documentElement.tagName=="parsererror")throw"parsererror";if(filter)data=filter(data,type);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(jQuery.isFunction(a[j])?a[j]():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.apply(this,arguments):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),p,hidden=jQuery(this).is(":hidden"),self=this;for(p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)return opt.complete.call(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.call(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){type=type||"fx";var q=jQuery.data(elem,type+"queue");if(!q||array)q=jQuery.data(elem,type+"queue",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].call(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:jQuery.fx.speeds[opt.duration])||jQuery.fx.speeds.def;opt.old=opt.complete;opt.complete=function(){if(opt.queue!==false)jQuery(this).dequeue();if(jQuery.isFunction(opt.old))opt.old.call(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.call(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=now();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=now();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)this.options.complete.call(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.extend(jQuery.fx,{speeds:{slow:600,fast:200,def:400},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),css=jQuery.curCSS,fixed=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&&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(css(parent,"display")))add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&css(parent,"overflow")!="visible")border(parent);parent=parent.parentNode;}if((safari2&&(fixed||css(offsetChild,"position")=="absolute"))||(mozilla&&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,10)||0;top+=parseInt(t,10)||0;}return results;};jQuery.fn.extend({position:function(){var left=0,top=0,results;if(this[0]){var offsetParent=this.offsetParent(),offset=this.offset(),parentOffset=/^body|html$/i.test(offsetParent[0].tagName)?{top:0,left:0}:offsetParent.offset();offset.top-=num(this,'marginTop');offset.left-=num(this,'marginLeft');parentOffset.top+=num(offsetParent,'borderTopWidth');parentOffset.left+=num(offsetParent,'borderLeftWidth');results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};}return results;},offsetParent:function(){var offsetParent=this[0].offsetParent;while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&jQuery.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return jQuery(offsetParent);}});jQuery.each(['Left','Top'],function(i,name){var method='scroll'+name;jQuery.fn[method]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(!i?val:jQuery(window).scrollLeft(),i?val:jQuery(window).scrollTop()):this[method]=val;}):this[0]==window||this[0]==document?self[i?'pageYOffset':'pageXOffset']||jQuery.boxModel&&document.documentElement[method]||document.body[method]:this[0][method];};});jQuery.each(["Height","Width"],function(i,name){var tl=i?"Left":"Top",br=i?"Right":"Bottom";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);};});})();
/*
 * jQuery Form Plugin
 * version: 2.21 (08-FEB-2009)
 * @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
 */
;(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;
    }

    // provide opportunity to alter form data before it is serialized
    if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
        log('ajaxSubmit: submit aborted via beforeSerialize callback');
        return this;
    }    
   
    var a = this.formToArray(options.semantic);
    if (options.data) {
        options.extraData = options.data;
        for (var n in options.data) {
          if(options.data[n] instanceof Array) {
            for (var k in options.data[n])
              a.push( { name: n, value: options.data[n][k] } )
          }  
          else
             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].apply(options, [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 (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 s = jQuery.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);

        var id = 'jqFormIO' + (new Date().getTime());
        var $io = $('<iframe id="' + id + '" name="' + id + '" src="about:blank" />');
        var io = $io[0];

        $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });

        var xhr = { // mock object
            aborted: 0,
            responseText: null,
            responseXML: null,
            status: 0,
            statusText: 'n/a',
            getAllResponseHeaders: function() {},
            getResponseHeader: function() {},
            setRequestHeader: function() {},
            abort: function() { 
                this.aborted = 1; 
                $io.attr('src','about:blank'); // abort op in progress
            }
        };

        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]);

		if (s.beforeSend && s.beforeSend(xhr, s) === false) {
			s.global && jQuery.active--;
			return;
        }
        if (xhr.aborted)
            return;
        
        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');

			// update form attrs in IE friendly way
			form.setAttribute('target',id);
			if (form.getAttribute('method') != 'POST')
				form.setAttribute('method', 'POST');
			if (form.getAttribute('action') != opts.url)
				form.setAttribute('action', opts.url);
							
            // ie borks in some cases when setting encoding
            if (! options.skipEncodingOverride) {
                $form.attr({
                    encoding: 'multipart/form-data',
                    enctype:  'multipart/form-data'
                });
            }

            // 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.setAttribute('action',a);
                t ? form.setAttribute('target', t) : $form.removeAttr('target');
                $(extraInputs).remove();
            }
        }, 10);

        var nullCheckFlag = 0;
		
        function cb() {
            if (cbInvoked++) return;
            
            io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);

            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 || doc.body.innerHTML == '') && !nullCheckFlag) {
                    // in some browsers (cough, Opera 9.2.x) the iframe DOM is not always traversable when
                    // the onload callback fires, so we give them a 2nd chance
                    nullCheckFlag = 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) {
				var v = op.value;
				if (!v) // extra pain for IE...
                	v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
                if (one) return v;
                a.push(v);
            }
        }
        return a;
    }
    return el.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.selected = function(select) {
    if (select == undefined) select = true;
    return this.each(function() { 
        var t = this.type;
        if (t == 'checkbox' || t == 'radio')
            this.checked = select;
        else if (this.tagName.toLowerCase() == 'option') {
            var $sel = $(this).parent('select');
            if (select && $sel[0] && $sel[0].type == 'select-one') {
                // deselect all other options
                $sel.find('option').selected(false);
            }
            this.selected = select;
        }
    });
};

// helper fn for console logging
// 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 validation plug-in 1.4
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
 * http://docs.jquery.com/Plugins/Validation
 *
 * Copyright (c) 2006 - 2008 JÃ¶rn Zaefferer
 *
 * $Id: jquery.validate.js 5788 2008-07-13 15:04:50Z joern.zaefferer $
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

(function($) {

$.extend($.fn, {
	// http://docs.jquery.com/Plugins/Validation/validate
	validate: function( options ) {
		
		// if nothing is selected, return nothing; can't chain anyway
		if (!this.length) {
			options && options.debug && window.console && console.warn( "nothing selected, can't validate, returning nothing" );
			return;
		}
		
		// check if a validator for this form was already created
		var validator = $.data(this[0], 'validator');
		if ( validator ) {
			return validator;
		}
		
		validator = new $.validator( options, this[0] );
		$.data(this[0], 'validator', validator); 
		
		if ( validator.settings.onsubmit ) {
		
			// allow suppresing validation by adding a cancel class to the submit button
			this.find("input, button").filter(".cancel").click(function() {
				validator.cancelSubmit = true;
			});
		
			// validate the form on submit
			this.submit( function( event ) {
				if ( validator.settings.debug )
					// prevent form submit to be able to see console output
					event.preventDefault();
					
				function handle() {
					if ( validator.settings.submitHandler ) {
						validator.settings.submitHandler.call( validator, validator.currentForm );
						return false;
					}
					return true;
				}
					
				// prevent submit for invalid forms or custom submit handlers
				if ( validator.cancelSubmit ) {
					validator.cancelSubmit = false;
					return handle();
				}
				if ( validator.form() ) {
					if ( validator.pendingRequest ) {
						validator.formSubmitted = true;
						return false;
					}
					return handle();
				} else {
					validator.focusInvalid();
					return false;
				}
			});
		}
		
		return validator;
	},
	// http://docs.jquery.com/Plugins/Validation/valid
	valid: function() {
        if ( $(this[0]).is('form')) {
            return this.validate().form();
        } else {
            var valid = false;
            var validator = $(this[0].form).validate();
            this.each(function() {
				valid |= validator.element(this);
            });
            return valid;
        }
    },
	// attributes: space seperated list of attributes to retrieve and remove
	removeAttrs: function(attributes) {
		var result = {},
			$element = this;
		$.each(attributes.split(/\s/), function() {
			result[this] = $element.attr(this);
			$element.removeAttr(this);
		});
		return result;
	},
	// http://docs.jquery.com/Plugins/Validation/rules
	rules: function(command, argument) {
		var element = this[0];
		
		if (command) {
			var staticRules = $.data(element.form, 'validator').settings.rules;
			var existingRules = $.validator.staticRules(element);
			switch(command) {
			case "add":
				$.extend(existingRules, $.validator.normalizeRule(argument));
				staticRules[element.name] = existingRules;
				break;
			case "remove":
				if (!argument) {
					delete staticRules[element.name];
					return existingRules;
				}
				var filtered = {};
				$.each(argument.split(/\s/), function(index, method) {
					filtered[method] = existingRules[method];
					delete existingRules[method];
				});
				return filtered;
			}
		}
		
		var data = $.validator.normalizeRules(
		$.extend(
			{},
			$.validator.metadataRules(element),
			$.validator.classRules(element),
			$.validator.attributeRules(element),
			$.validator.staticRules(element)
		), element);
		
		// make sure required is at front
		if (data.required) {
			var param = data.required;
			delete data.required;
			data = $.extend({required: param}, data);
		}
		
		return data;
	},
	// destructive add
	push: function( t ) {
		return this.setArray( this.add(t).get() );
	}
});

// Custom selectors
$.extend($.expr[":"], {
	// http://docs.jquery.com/Plugins/Validation/blank
	blank: function(a) {return !$.trim(a.value);},
	// http://docs.jquery.com/Plugins/Validation/filled
	filled: function(a) {return !!$.trim(a.value);},
	// http://docs.jquery.com/Plugins/Validation/unchecked
	unchecked: function(a) {return !a.checked;}
});


$.format = function(source, params) {
	if ( arguments.length == 1 ) 
		return function() {
			var args = $.makeArray(arguments);
			args.unshift(source);
			return $.format.apply( this, args );
		};
	if ( arguments.length > 2 && params.constructor != Array  ) {
		params = $.makeArray(arguments).slice(1);
	}
	if ( params.constructor != Array ) {
		params = [ params ];
	}
	$.each(params, function(i, n) {
		source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
	});
	return source;
};

// constructor for validator
$.validator = function( options, form ) {
	this.settings = $.extend( {}, $.validator.defaults, options );
	this.currentForm = form;
	this.init();
};

$.extend($.validator, {

	defaults: {
		messages: {},
		groups: {},
		rules: {},
		errorClass: "error",
		errorElement: "label",
		focusInvalid: true,
		errorContainer: $( [] ),
		errorLabelContainer: $( [] ),
		onsubmit: true,
		ignore: [],
		onfocusin: function(element) {
			this.lastActive = element;
				
			// hide error label and remove error class on focus if enabled
			if ( this.settings.focusCleanup && !this.blockFocusCleanup ) {
				this.settings.unhighlight && this.settings.unhighlight.call( this, element, this.settings.errorClass );
				this.errorsFor(element).hide();
			}
		},
		onfocusout: function(element) {
			if ( !this.checkable(element) && (element.name in this.submitted || !this.optional(element)) ) {
				this.element(element);
			}
		},
		onkeyup: function(element) {
			if ( element.name in this.submitted || element == this.lastElement ) {
				this.element(element);
			}
		},
		onclick: function(element) {
			if ( element.name in this.submitted )
				this.element(element);
		},
		highlight: function( element, errorClass ) {
			$( element ).addClass( errorClass );
		},
		unhighlight: function( element, errorClass ) {
			$( element ).removeClass( errorClass );
		}
	},

	// http://docs.jquery.com/Plugins/Validation/Validator/setDefaults
	setDefaults: function(settings) {
		$.extend( $.validator.defaults, settings );
	},

	messages: {
		required: "This field is required.",
		remote: "Please fix this field.",
		email: "Please enter a valid email address.",
		url: "Please enter a valid URL.",
		date: "Please enter a valid date.",
		dateISO: "Please enter a valid date (ISO).",
		dateDE: "Bitte geben Sie ein gÃ¼ltiges Datum ein.",
		number: "Please enter a valid number.",
		numberDE: "Bitte geben Sie eine Nummer ein.",
		digits: "Please enter only digits",
		creditcard: "Please enter a valid credit card.",
		equalTo: "Please enter the same value again.",
		accept: "Please enter a value with a valid extension.",
		maxlength: $.format("Please enter no more than {0} characters."),
		minlength: $.format("Please enter at least {0} characters."),
		rangelength: $.format("Please enter a value between {0} and {1} characters long."),
		range: $.format("Please enter a value between {0} and {1}."),
		max: $.format("Please enter a value less than or equal to {0}."),
		min: $.format("Please enter a value greater than or equal to {0}.")
	},
	
	autoCreateRanges: false,
	
	prototype: {
		
		init: function() {
			this.labelContainer = $(this.settings.errorLabelContainer);
			this.errorContext = this.labelContainer.length && this.labelContainer || $(this.currentForm);
			this.containers = $(this.settings.errorContainer).add( this.settings.errorLabelContainer );
			this.submitted = {};
			this.valueCache = {};
			this.pendingRequest = 0;
			this.pending = {};
			this.invalid = {};
			this.reset();
			
			var groups = (this.groups = {});
			$.each(this.settings.groups, function(key, value) {
				$.each(value.split(/\s/), function(index, name) {
					groups[name] = key;
				});
			});
			var rules = this.settings.rules;
			$.each(rules, function(key, value) {
				rules[key] = $.validator.normalizeRule(value);
			});
			
			function delegate(event) {
				var validator = $.data(this[0].form, "validator");
				validator.settings["on" + event.type] && validator.settings["on" + event.type].call(validator, this[0] );
			}
			$(this.currentForm)
				.delegate("focusin focusout keyup", ":text, :password, :file, select, textarea", delegate)
				.delegate("click", ":radio, :checkbox", delegate);
		},

		// http://docs.jquery.com/Plugins/Validation/Validator/form
		form: function() {
			this.checkForm();
			$.extend(this.submitted, this.errorMap);
			this.invalid = $.extend({}, this.errorMap);
			if (!this.valid())
				$(this.currentForm).triggerHandler("invalid-form.validate", [this]);
			this.showErrors();
			return this.valid();
		},
		
		checkForm: function() {
			this.prepareForm();
			for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) {
				this.check( elements[i] );
			}
			return this.valid(); 
		},
		
		// http://docs.jquery.com/Plugins/Validation/Validator/element
		element: function( element ) {
			element = this.clean( element );
			this.lastElement = element;
			this.prepareElement( element );
			this.currentElements = $(element);
			var result = this.check( element );
			if ( result ) {
				delete this.invalid[element.name];
			} else {
				this.invalid[element.name] = true;
			}
			if ( !this.numberOfInvalids() ) {
				// Hide error containers on last error
				this.toHide.push( this.containers );
			}
			this.showErrors();
			return result;
		},

		// http://docs.jquery.com/Plugins/Validation/Validator/showErrors
		showErrors: function(errors) {
			if(errors) {
				// add items to error list and map
				$.extend( this.errorMap, errors );
				this.errorList = [];
				for ( var name in errors ) {
					this.errorList.push({
						message: errors[name],
						element: this.findByName(name)[0]
					});
				}
				// remove items from success list
				this.successList = $.grep( this.successList, function(element) {
					return !(element.name in errors);
				});
			}
			this.settings.showErrors
				? this.settings.showErrors.call( this, this.errorMap, this.errorList )
				: this.defaultShowErrors();
		},
		
		// http://docs.jquery.com/Plugins/Validation/Validator/resetForm
		resetForm: function() {
			if ( $.fn.resetForm )
				$( this.currentForm ).resetForm();
			this.submitted = {};
			this.prepareForm();
			this.hideErrors();
			this.elements().removeClass( this.settings.errorClass );
		},
		
		numberOfInvalids: function() {
			return this.objectLength(this.invalid);
		},
		
		objectLength: function( obj ) {
			var count = 0;
			for ( var i in obj )
				count++;
			return count;
		},
		
		hideErrors: function() {
			this.addWrapper( this.toHide ).hide();
		},
		
		valid: function() {
			return this.size() == 0;
		},
		
		size: function() {
			return this.errorList.length;
		},
		
		focusInvalid: function() {
			if( this.settings.focusInvalid ) {
				try {
					$(this.findLastActive() || this.errorList.length && this.errorList[0].element || []).filter(":visible").focus();
				} catch(e) { /* ignore IE throwing errors when focusing hidden elements */ }
			}
		},
		
		findLastActive: function() {
			var lastActive = this.lastActive;
			return lastActive && $.grep(this.errorList, function(n) {
				return n.element.name == lastActive.name;
			}).length == 1 && lastActive;
		},
		
		elements: function() {
			var validator = this,
				rulesCache = {};
			
			// select all valid inputs inside the form (no submit or reset buttons)
			// workaround $Query([]).add until http://dev.jquery.com/ticket/2114 is solved
			return $([]).add(this.currentForm.elements)
			.filter(":input")
			.not(":submit, :reset, :image, [disabled]")
			.not( this.settings.ignore )
			.filter(function() {
				!this.name && validator.settings.debug && window.console && console.error( "%o has no name assigned", this);
			
				// select only the first element for each name, and only those with rules specified
				if ( this.name in rulesCache || !validator.objectLength($(this).rules()) )
					return false;
				
				rulesCache[this.name] = true;
				return true;
			});
		},
		
		clean: function( selector ) {
			return $( selector )[0];
		},
		
		errors: function() {
			return $( this.settings.errorElement + "." + this.settings.errorClass, this.errorContext );
		},
		
		reset: function() {
			this.successList = [];
			this.errorList = [];
			this.errorMap = {};
			this.toShow = $([]);
			this.toHide = $([]);
			this.formSubmitted = false;
			this.currentElements = $([]);
		},
		
		prepareForm: function() {
			this.reset();
			this.toHide = this.errors().push( this.containers );
		},
		
		prepareElement: function( element ) {
			this.reset();
			this.toHide = this.errorsFor(element);
		},
	
		check: function( element ) {
			element = this.clean( element );
			
			// if radio/checkbox, validate first element in group instead
			if (this.checkable(element)) {
				element = this.findByName( element.name )[0];
			}
			
			var rules = $(element).rules();
			var dependencyMismatch = false;
			for( method in rules ) {
				var rule = { method: method, parameters: rules[method] };
				try {
					var result = $.validator.methods[method].call( this, $.trim(element.value), element, rule.parameters );
					
					// if a method indicates that the field is optional and therefore valid,
					// don't mark it as valid when there are no other rules
					if ( result == "dependency-mismatch" ) {
						dependencyMismatch = true;
						continue;
					}
					dependencyMismatch = false;
					
					if ( result == "pending" ) {
						this.toHide = this.toHide.not( this.errorsFor(element) );
						return;
					}
					
					if( !result ) {
						this.formatAndAdd( element, rule );
						return false;
					}
				} catch(e) {
					this.settings.debug && window.console && console.log("exception occured when checking element " + element.id
						 + ", check the '" + rule.method + "' method");
					throw e;
				}
			}
			if (dependencyMismatch)
				return;
			if ( this.objectLength(rules) )
				this.successList.push(element);
			return true;
		},
		
		// return the custom message for the given element and validation method
		// specified in the element's "messages" metadata
		customMetaMessage: function(element, method) {
			if (!$.metadata)
				return;
			
			var meta = this.settings.meta
				? $(element).metadata()[this.settings.meta]
				: $(element).metadata();
			
			return meta.messages && meta.messages[method];
		},
		
		// return the custom message for the given element name and validation method
		customMessage: function( name, method ) {
			var m = this.settings.messages[name];
			return m && (m.constructor == String
				? m
				: m[method]);
		},
		
		// return the first defined argument, allowing empty strings
		findDefined: function() {
			for(var i = 0; i < arguments.length; i++) {
				if (arguments[i] !== undefined)
					return arguments[i];
			}
			return undefined;
		},
		
		defaultMessage: function( element, method) {
			return this.findDefined(
				this.customMessage( element.name, method ),
				this.customMetaMessage( element, method ),
				// title is never undefined, so handle empty string as undefined
				element.title || undefined,
				$.validator.messages[method],
				"<strong>Warning: No message defined for " + element.name + "</strong>"
			);
		},
		
		formatAndAdd: function( element, rule ) {
			var message = this.defaultMessage( element, rule.method );
			if ( typeof message == "function" ) 
				message = message.call(this, rule.parameters, element);
			this.errorList.push({
				message: message,
				element: element
			});
			this.errorMap[element.name] = message;
			this.submitted[element.name] = message;
		},
		
		addWrapper: function(toToggle) {
			if ( this.settings.wrapper )
				toToggle.push( toToggle.parents( this.settings.wrapper ) );
			return toToggle;
		},
		
		defaultShowErrors: function() {
			for ( var i = 0; this.errorList[i]; i++ ) {
				var error = this.errorList[i];
				this.settings.highlight && this.settings.highlight.call( this, error.element, this.settings.errorClass );
				this.showLabel( error.element, error.message );
			}
			if( this.errorList.length ) {
				this.toShow.push( this.containers );
			}
			if (this.settings.success) {
				for ( var i = 0; this.successList[i]; i++ ) {
					this.showLabel( this.successList[i] );
				}
			}
			if (this.settings.unhighlight) {
				for ( var i = 0, elements = this.validElements(); elements[i]; i++ ) {
					this.settings.unhighlight.call( this, elements[i], this.settings.errorClass );
				}
			}
			this.toHide = this.toHide.not( this.toShow );
			this.hideErrors();
			this.addWrapper( this.toShow ).show();
		},
		
		validElements: function() {
			return this.currentElements.not(this.invalidElements());
		},
		
		invalidElements: function() {
			return $(this.errorList).map(function() {
				return this.element;
			});
		},
		
		showLabel: function(element, message) {
			var label = this.errorsFor( element );
			if ( label.length ) {
				// refresh error/success class
				label.removeClass().addClass( this.settings.errorClass );
			
				// check if we have a generated label, replace the message then
				label.attr("generated") && label.html(message);
			} else {
				// create label
				label = $("<" + this.settings.errorElement + "/>")
					.attr({"for":  this.idOrName(element), generated: true})
					.addClass(this.settings.errorClass)
					.html(message || "");
				if ( this.settings.wrapper ) {
					// make sure the element is visible, even in IE
					// actually showing the wrapped element is handled elsewhere
					label = label.hide().show().wrap("<" + this.settings.wrapper + ">").parent();
				}
				if ( !this.labelContainer.append(label).length )
					this.settings.errorPlacement
						? this.settings.errorPlacement(label, $(element) )
						: label.insertAfter(element);
			}
			if ( !message && this.settings.success ) {
				label.text("");
				typeof this.settings.success == "string"
					? label.addClass( this.settings.success )
					: this.settings.success( label );
			}
			this.toShow.push(label);
		},
		
		errorsFor: function(element) {
			return this.errors().filter("[@for='" + this.idOrName(element) + "']");
		},
		
		idOrName: function(element) {
			return this.groups[element.name] || (this.checkable(element) ? element.name : element.id || element.name);
		},

		checkable: function( element ) {
			return /radio|checkbox/i.test(element.type);
		},
		
		findByName: function( name ) {
			// select by name and filter by form for performance over form.find("[name=...]")
			var form = this.currentForm;
			return $(document.getElementsByName(name)).map(function(index, element) {
				return element.form == form && element.name == name && element  || null;
			});
		},
		
		getLength: function(value, element) {
			switch( element.nodeName.toLowerCase() ) {
			case 'select':
				return $("option:selected", element).length;
			case 'input':
				if( this.checkable( element) )
					return this.findByName(element.name).filter(':checked').length;
			}
			return value.length;
		},
	
		depend: function(param, element) {
			return this.dependTypes[typeof param]
				? this.dependTypes[typeof param](param, element)
				: true;
		},
	
		dependTypes: {
			"boolean": function(param, element) {
				return param;
			},
			"string": function(param, element) {
				return !!$(param, element.form).length;
			},
			"function": function(param, element) {
				return param(element);
			}
		},
		
		optional: function(element) {
			return !$.validator.methods.required.call(this, $.trim(element.value), element) && "dependency-mismatch";
		},
		
		startRequest: function(element) {
			if (!this.pending[element.name]) {
				this.pendingRequest++;
				this.pending[element.name] = true;
			}
		},
		
		stopRequest: function(element, valid) {
			this.pendingRequest--;
			// sometimes synchronization fails, make pendingRequest is never < 0
			if (this.pendingRequest < 0)
				this.pendingRequest = 0;
			delete this.pending[element.name];
			if ( valid && this.pendingRequest == 0 && this.formSubmitted && this.form() ) {
				$(this.currentForm).submit();
			}
		},
		
		previousValue: function(element) {
			return $.data(element, "previousValue") || $.data(element, "previousValue", previous = {
				old: null,
				valid: true,
				message: this.defaultMessage( element, "remote" )
			});
		}
		
	},
	
	classRuleSettings: {
		required: {required: true},
		email: {email: true},
		url: {url: true},
		date: {date: true},
		dateISO: {dateISO: true},
		dateDE: {dateDE: true},
		number: {number: true},
		numberDE: {numberDE: true},
		digits: {digits: true},
		creditcard: {creditcard: true}
	},
	
	addClassRules: function(className, rules) {
		className.constructor == String ?
			this.classRuleSettings[className] = rules :
			$.extend(this.classRuleSettings, className);
	},
	
	classRules: function(element) {
		var rules = {};
		var classes = $(element).attr('class');
		classes && $.each(classes.split(' '), function() {
			if (this in $.validator.classRuleSettings) {
				$.extend(rules, $.validator.classRuleSettings[this]);
			}
		});
		return rules;
	},
	
	attributeRules: function(element) {
		var rules = {};
		var $element = $(element);
		
		for (method in $.validator.methods) {
			var value = $element.attr(method);
			if (value) {
				rules[method] = value;
			}
		}
		
		// maxlength may be returned as -1, 2147483647 (IE) and 524288 (safari) for text inputs
		if (rules.maxlength && /-1|2147483647|524288/.test(rules.maxlength)) {
			delete rules.maxlength;
		}
		
		return rules;
	},
	
	metadataRules: function(element) {
		if (!$.metadata) return {};
		
		var meta = $.data(element.form, 'validator').settings.meta;
		return meta ?
			$(element).metadata()[meta] :
			$(element).metadata();
	},
	
	staticRules: function(element) {
		var rules = {};
		var validator = $.data(element.form, 'validator');
		if (validator.settings.rules) {
			rules = $.validator.normalizeRule(validator.settings.rules[element.name]) || {};
		}
		return rules;
	},
	
	normalizeRules: function(rules, element) {
		// handle dependency check
		$.each(rules, function(prop, val) {
			// ignore rule when param is explicitly false, eg. required:false
			if (val === false) {
				delete rules[prop];
				return;
			}
			if (val.param || val.depends) {
				var keepRule = true;
				switch (typeof val.depends) {
					case "string":
						keepRule = !!$(val.depends, element.form).length;
						break;
					case "function":
						keepRule = val.depends.call(element, element);
						break;
				}
				if (keepRule) {
					rules[prop] = val.param !== undefined ? val.param : true;
				} else {
					delete rules[prop];
				}
			}
		});
		
		// evaluate parameters
		$.each(rules, function(rule, parameter) {
			rules[rule] = $.isFunction(parameter) ? parameter(element) : parameter;
		});
		
		// clean number parameters
		$.each(['minlength', 'maxlength', 'min', 'max'], function() {
			if (rules[this]) {
				rules[this] = Number(rules[this]);
			}
		});
		$.each(['rangelength', 'range'], function() {
			if (rules[this]) {
				rules[this] = [Number(rules[this][0]), Number(rules[this][1])];
			}
		});
		
		if ($.validator.autoCreateRanges) {
			// auto-create ranges
			if (rules.min && rules.max) {
				rules.range = [rules.min, rules.max];
				delete rules.min;
				delete rules.max;
			}
			if (rules.minlength && rules.maxlength) {
				rules.rangelength = [rules.minlength, rules.maxlength];
				delete rules.minlength;
				delete rules.maxlength;
			}
		}
		
		// To support custom messages in metadata ignore rule methods titled "messages"
		if (rules.messages) {
			delete rules.messages
		}
		
		return rules;
	},
	
	// Converts a simple string to a {string: true} rule, e.g., "required" to {required:true}
	normalizeRule: function(data) {
		if( typeof data == "string" ) {
			var transformed = {};
			$.each(data.split(/\s/), function() {
				transformed[this] = true;
			});
			data = transformed;
		}
		return data;
	},
	
	// http://docs.jquery.com/Plugins/Validation/Validator/addMethod
	addMethod: function(name, method, message) {
		$.validator.methods[name] = method;
		$.validator.messages[name] = message;
		if (method.length < 3) {
			$.validator.addClassRules(name, $.validator.normalizeRule(name));
		}
	},

	methods: {

		// http://docs.jquery.com/Plugins/Validation/Methods/required
		required: function(value, element, param) {
			// check if dependency is met
			if ( !this.depend(param, element) )
				return "dependency-mismatch";
			switch( element.nodeName.toLowerCase() ) {
			case 'select':
				var options = $("option:selected", element);
				return options.length > 0 && ( element.type == "select-multiple" || ($.browser.msie && !(options[0].attributes['value'].specified) ? options[0].text : options[0].value).length > 0);
			case 'input':
				if ( this.checkable(element) )
					return this.getLength(value, element) > 0;
			default:
				return value.length > 0;
			}
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/remote
		remote: function(value, element, param) {
			if ( this.optional(element) )
				return "dependency-mismatch";
			
			var previous = this.previousValue(element);
			
			if (!this.settings.messages[element.name] )
				this.settings.messages[element.name] = {};
			this.settings.messages[element.name].remote = typeof previous.message == "function" ? previous.message(value) : previous.message;
			
			if ( previous.old !== value ) {
				previous.old = value;
				var validator = this;
				this.startRequest(element);
				var data = {};
				data[element.name] = value;
				$.ajax({
					url: param,
					mode: "abort",
					port: "validate" + element.name,
					dataType: "json",
					data: data,
					success: function(response) {
						if ( !response ) {
							var errors = {};
							errors[element.name] =  response || validator.defaultMessage( element, "remote" );
							validator.showErrors(errors);
						} else {
							var submitted = validator.formSubmitted;
							validator.prepareElement(element);
							validator.formSubmitted = submitted;
							validator.successList.push(element);
							validator.showErrors();
						}
						previous.valid = response;
						validator.stopRequest(element, response);
					}
				});
				return "pending";
			} else if( this.pending[element.name] ) {
				return "pending";
			}
			return previous.valid;
		},

		// http://docs.jquery.com/Plugins/Validation/Methods/minlength
		minlength: function(value, element, param) {
			return this.optional(element) || this.getLength(value, element) >= param;
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/maxlength
		maxlength: function(value, element, param) {
			return this.optional(element) || this.getLength(value, element) <= param;
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/rangelength
		rangelength: function(value, element, param) {
			var length = this.getLength(value, element);
			return this.optional(element) || ( length >= param[0] && length <= param[1] );
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/min
		min: function( value, element, param ) {
			return this.optional(element) || value >= param;
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/max
		max: function( value, element, param ) {
			return this.optional(element) || value <= param;
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/range
		range: function( value, element, param ) {
			return this.optional(element) || ( value >= param[0] && value <= param[1] );
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/email
		email: function(value, element) {
			// contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
			return this.optional(element) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(element.value);
		},
	
		// http://docs.jquery.com/Plugins/Validation/Methods/url
		url: function(value, element) {
			// contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
			return this.optional(element) || /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(element.value);
		},
        
		// http://docs.jquery.com/Plugins/Validation/Methods/date
		date: function(value, element) {
			return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
		},
	
		// http://docs.jquery.com/Plugins/Validation/Methods/dateISO
		dateISO: function(value, element) {
			return this.optional(element) || /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value);
		},
	
		// http://docs.jquery.com/Plugins/Validation/Methods/dateDE
		dateDE: function(value, element) {
			return this.optional(element) || /^\d\d?\.\d\d?\.\d\d\d?\d?$/.test(value);
		},
	
		// http://docs.jquery.com/Plugins/Validation/Methods/number
		number: function(value, element) {
			return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
		},
	
		// http://docs.jquery.com/Plugins/Validation/Methods/numberDE
		numberDE: function(value, element) {
			return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(value);
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/digits
		digits: function(value, element) {
			return this.optional(element) || /^\d+$/.test(value);
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/creditcard
		// based on http://en.wikipedia.org/wiki/Luhn
		creditcard: function(value, element) {
			if ( this.optional(element) )
				return "dependency-mismatch";
			// accept only digits and dashes
			if (/[^0-9-]+/.test(value))
				return false;
			var nCheck = 0,
				nDigit = 0,
				bEven = false;

			value = value.replace(/\D/g, "");

			for (n = value.length - 1; n >= 0; n--) {
				var cDigit = value.charAt(n);
				var nDigit = parseInt(cDigit, 10);
				if (bEven) {
					if ((nDigit *= 2) > 9)
						nDigit -= 9;
				}
				nCheck += nDigit;
				bEven = !bEven;
			}

			return (nCheck % 10) == 0;
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/accept
		accept: function(value, element, param) {
			param = typeof param == "string" ? param : "png|jpe?g|gif";
			return this.optional(element) || value.match(new RegExp(".(" + param + ")$", "i")); 
		},
		
		// http://docs.jquery.com/Plugins/Validation/Methods/equalTo
		equalTo: function(value, element, param) {
			return value == $(param).val();
		}
		
	}
	
});

})(jQuery);

// ajax mode: abort
// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort() 
;(function($) {
	var ajax = $.ajax;
	var pendingRequests = {};
	$.ajax = function(settings) {
		// create settings for compatibility with ajaxSetup
		settings = $.extend(settings, $.extend({}, $.ajaxSettings, settings));
		var port = settings.port;
		if (settings.mode == "abort") {
			if ( pendingRequests[port] ) {
				pendingRequests[port].abort();
			}
			return (pendingRequests[port] = ajax.apply(this, arguments));
		}
		return ajax.apply(this, arguments);
	};
})(jQuery);

// provides cross-browser focusin and focusout events
// IE has native support, in other browsers, use event caputuring (neither bubbles)

// provides delegate(type: String, delegate: Selector, handler: Callback) plugin for easier event delegation
// handler is only called when $(event.target).is(delegate), in the scope of the jquery-object for event.target 

// provides triggerEvent(type: String, target: Element) to trigger delegated events
;(function($) {
	$.each({
		focus: 'focusin',
		blur: 'focusout'	
	}, function( original, fix ){
		$.event.special[fix] = {
			setup:function() {
				if ( $.browser.msie ) return false;
				this.addEventListener( original, $.event.special[fix].handler, true );
			},
			teardown:function() {
				if ( $.browser.msie ) return false;
				this.removeEventListener( original,
				$.event.special[fix].handler, true );
			},
			handler: function(e) {
				arguments[0] = $.event.fix(e);
				arguments[0].type = fix;
				return $.event.handle.apply(this, arguments);
			}
		};
	});
	$.extend($.fn, {
		delegate: function(type, delegate, handler) {
			return this.bind(type, function(event) {
				var target = $(event.target);
				if (target.is(delegate)) {
					return handler.apply(target, arguments);
				}
			});
		},
		triggerEvent: function(type, target) {
			return this.triggerHandler(type, [$.event.fix({ type: type, target: target })]);
		}
	})
})(jQuery);
/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-06-20 03:23:36 +0200 (Mi, 20 Jun 2007) $
 * $Rev: 2110 $
 *
 * Version 2.1
 */

(function($){

/**
 * The bgiframe is chainable and applies the iframe hack to get 
 * around zIndex issues in IE6. It will only apply itself in IE 
 * and adds a class to the iframe called 'bgiframe'. The iframe
 * is appeneded as the first child of the matched element(s) 
 * with a tabIndex and zIndex of -1.
 * 
 * By default the plugin will take borders, sized with pixel units,
 * into account. If a different unit is used for the border's width,
 * then you will need to use the top and left settings as explained below.
 *
 * NOTICE: This plugin has been reported to cause perfromance problems
 * when used on elements that change properties (like width, height and
 * opacity) a lot in IE6. Most of these problems have been caused by 
 * the expressions used to calculate the elements width, height and 
 * borders. Some have reported it is due to the opacity filter. All 
 * these settings can be changed if needed as explained below.
 *
 * @example $('div').bgiframe();
 * @before <div><p>Paragraph</p></div>
 * @result <div><iframe class="bgiframe".../><p>Paragraph</p></div>
 *
 * @param Map settings Optional settings to configure the iframe.
 * @option String|Number top The iframe must be offset to the top
 * 		by the width of the top border. This should be a negative 
 *      number representing the border-top-width. If a number is 
 * 		is used here, pixels will be assumed. Otherwise, be sure
 *		to specify a unit. An expression could also be used. 
 * 		By default the value is "auto" which will use an expression 
 * 		to get the border-top-width if it is in pixels.
 * @option String|Number left The iframe must be offset to the left
 * 		by the width of the left border. This should be a negative 
 *      number representing the border-left-width. If a number is 
 * 		is used here, pixels will be assumed. Otherwise, be sure
 *		to specify a unit. An expression could also be used. 
 * 		By default the value is "auto" which will use an expression 
 * 		to get the border-left-width if it is in pixels.
 * @option String|Number width This is the width of the iframe. If
 *		a number is used here, pixels will be assume. Otherwise, be sure
 * 		to specify a unit. An experssion could also be used.
 *		By default the value is "auto" which will use an experssion
 * 		to get the offsetWidth.
 * @option String|Number height This is the height of the iframe. If
 *		a number is used here, pixels will be assume. Otherwise, be sure
 * 		to specify a unit. An experssion could also be used.
 *		By default the value is "auto" which will use an experssion
 * 		to get the offsetHeight.
 * @option Boolean opacity This is a boolean representing whether or not
 * 		to use opacity. If set to true, the opacity of 0 is applied. If
 *		set to false, the opacity filter is not applied. Default: true.
 * @option String src This setting is provided so that one could change 
 *		the src of the iframe to whatever they need.
 *		Default: "javascript:false;"
 *
 * @name bgiframe
 * @type jQuery
 * @cat Plugins/bgiframe
 * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 */
$.fn.bgIframe = $.fn.bgiframe = function(s) {
	// This is only for IE6
	if ( $.browser.msie && parseInt($.browser.version) <= 6 ) {
		s = $.extend({
			top     : 'auto', // auto == .currentStyle.borderTopWidth
			left    : 'auto', // auto == .currentStyle.borderLeftWidth
			width   : 'auto', // auto == offsetWidth
			height  : 'auto', // auto == offsetHeight
			opacity : true,
			src     : 'javascript:false;'
		}, s || {});
		var prop = function(n){return n&&n.constructor==Number?n+'px':n;},
		    html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
		               'style="display:block;position:absolute;z-index:-1;'+
			               (s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+
					       'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+
					       'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+
					       'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+
					       'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+
					'"/>';
		return this.each(function() {
			if ( $('> iframe.bgiframe', this).length == 0 )
				this.insertBefore( document.createElement(html), this.firstChild );
		});
	}
	return this;
};

// Add browser.version if it doesn't exist
if (!$.browser.version)
	$.browser.version = navigator.userAgent.toLowerCase().match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)[1];

})(jQuery);/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-06-22 04:38:37 +0200 (Fr, 22 Jun 2007) $
 * $Rev: 2141 $
 *
 * Version: 1.0b2
 */

(function($){

// store a copy of the core height and width methods
var height = $.fn.height,
    width  = $.fn.width;

$.fn.extend({
	/**
	 * If used on document, returns the document's height (innerHeight)
	 * If used on window, returns the viewport's (window) height
	 * See core docs on height() to see what happens when used on an element.
	 *
	 * @example $("#testdiv").height()
	 * @result 200
	 *
	 * @example $(document).height()
	 * @result 800
	 *
	 * @example $(window).height()
	 * @result 400
	 *
	 * @name height
	 * @type Object
	 * @cat Plugins/Dimensions
	 */
	height: function() {
		if ( this[0] == window )
			return self.innerHeight ||
				$.boxModel && document.documentElement.clientHeight || 
				document.body.clientHeight;
		
		if ( this[0] == document )
			return Math.max( document.body.scrollHeight, document.body.offsetHeight );
		
		return height.apply(this, arguments);
	},
	
	/**
	 * If used on document, returns the document's width (innerWidth)
	 * If used on window, returns the viewport's (window) width
	 * See core docs on height() to see what happens when used on an element.
	 *
	 * @example $("#testdiv").width()
	 * @result 200
	 *
	 * @example $(document).width()
	 * @result 800
	 *
	 * @example $(window).width()
	 * @result 400
	 *
	 * @name width
	 * @type Object
	 * @cat Plugins/Dimensions
	 */
	width: function() {
		if ( this[0] == window )
			return self.innerWidth ||
				$.boxModel && document.documentElement.clientWidth ||
				document.body.clientWidth;

		if ( this[0] == document )
			return Math.max( document.body.scrollWidth, document.body.offsetWidth );

		return width.apply(this, arguments);
	},
	
	/**
	 * Returns the inner height value (without border) for the first matched element.
	 * If used on document, returns the document's height (innerHeight)
	 * If used on window, returns the viewport's (window) height
	 *
	 * @example $("#testdiv").innerHeight()
	 * @result 800
	 *
	 * @name innerHeight
	 * @type Number
	 * @cat Plugins/Dimensions
	 */
	innerHeight: function() {
		return this[0] == window || this[0] == document ?
			this.height() :
			this.is(':visible') ?
				this[0].offsetHeight - num(this, 'borderTopWidth') - num(this, 'borderBottomWidth') :
				this.height() + num(this, 'paddingTop') + num(this, 'paddingBottom');
	},
	
	/**
	 * Returns the inner width value (without border) for the first matched element.
	 * If used on document, returns the document's Width (innerWidth)
	 * If used on window, returns the viewport's (window) width
	 *
	 * @example $("#testdiv").innerWidth()
	 * @result 1000
	 *
	 * @name innerWidth
	 * @type Number
	 * @cat Plugins/Dimensions
	 */
	innerWidth: function() {
		return this[0] == window || this[0] == document ?
			this.width() :
			this.is(':visible') ?
				this[0].offsetWidth - num(this, 'borderLeftWidth') - num(this, 'borderRightWidth') :
				this.width() + num(this, 'paddingLeft') + num(this, 'paddingRight');
	},
	
	/**
	 * Returns the outer height value (including border) for the first matched element.
	 * Cannot be used on document or window.
	 *
	 * @example $("#testdiv").outerHeight()
	 * @result 1000
	 *
	 * @name outerHeight
	 * @type Number
	 * @cat Plugins/Dimensions
	 */
	outerHeight: function() {
		return this[0] == window || this[0] == document ?
			this.height() :
			this.is(':visible') ?
				this[0].offsetHeight :
				this.height() + num(this,'borderTopWidth') + num(this, 'borderBottomWidth') + num(this, 'paddingTop') + num(this, 'paddingBottom');
	},
	
	/**
	 * Returns the outer width value (including border) for the first matched element.
	 * Cannot be used on document or window.
	 *
	 * @example $("#testdiv").outerHeight()
	 * @result 1000
	 *
	 * @name outerHeight
	 * @type Number
	 * @cat Plugins/Dimensions
	 */
	outerWidth: function() {
		return this[0] == window || this[0] == document ?
			this.width() :
			this.is(':visible') ?
				this[0].offsetWidth :
				this.width() + num(this, 'borderLeftWidth') + num(this, 'borderRightWidth') + num(this, 'paddingLeft') + num(this, 'paddingRight');
	},
	
	/**
	 * Returns how many pixels the user has scrolled to the right (scrollLeft).
	 * Works on containers with overflow: auto and window/document.
	 *
	 * @example $("#testdiv").scrollLeft()
	 * @result 100
	 *
	 * @name scrollLeft
	 * @type Number
	 * @cat Plugins/Dimensions
	 */
	/**
	 * Sets the scrollLeft property and continues the chain.
	 * Works on containers with overflow: auto and window/document.
	 *
	 * @example $("#testdiv").scrollLeft(10).scrollLeft()
	 * @result 10
	 *
	 * @name scrollLeft
	 * @param Number value A positive number representing the desired scrollLeft.
	 * @type jQuery
	 * @cat Plugins/Dimensions
	 */
	scrollLeft: function(val) {
		if ( val != undefined )
			// set the scroll left
			return this.each(function() {
				if (this == window || this == document)
					window.scrollTo( val, $(window).scrollTop() );
				else
					this.scrollLeft = val;
			});
		
		// return the scroll left offest in pixels
		if ( this[0] == window || this[0] == document )
			return self.pageXOffset ||
				$.boxModel && document.documentElement.scrollLeft ||
				document.body.scrollLeft;
				
		return this[0].scrollLeft;
	},
	
	/**
	 * Returns how many pixels the user has scrolled to the bottom (scrollTop).
	 * Works on containers with overflow: auto and window/document.
	 *
	 * @example $("#testdiv").scrollTop()
	 * @result 100
	 *
	 * @name scrollTop
	 * @type Number
	 * @cat Plugins/Dimensions
	 */
	/**
	 * Sets the scrollTop property and continues the chain.
	 * Works on containers with overflow: auto and window/document.
	 *
	 * @example $("#testdiv").scrollTop(10).scrollTop()
	 * @result 10
	 *
	 * @name scrollTop
	 * @param Number value A positive number representing the desired scrollTop.
	 * @type jQuery
	 * @cat Plugins/Dimensions
	 */
	scrollTop: function(val) {
		if ( val != undefined )
			// set the scroll top
			return this.each(function() {
				if (this == window || this == document)
					window.scrollTo( $(window).scrollLeft(), val );
				else
					this.scrollTop = val;
			});
		
		// return the scroll top offset in pixels
		if ( this[0] == window || this[0] == document )
			return self.pageYOffset ||
				$.boxModel && document.documentElement.scrollTop ||
				document.body.scrollTop;

		return this[0].scrollTop;
	},
	
	/** 
	 * Returns the top and left positioned offset in pixels.
	 * The positioned offset is the offset between a positioned
	 * parent and the element itself.
	 *
	 * @example $("#testdiv").position()
	 * @result { top: 100, left: 100 }
	 * 
	 * @name position
	 * @param Map options Optional settings to configure the way the offset is calculated.
	 * @option Boolean margin Should the margin of the element be included in the calculations? False by default.
	 * @option Boolean border Should the border of the element be included in the calculations? False by default.
	 * @option Boolean padding Should the padding of the element be included in the calculations? False by default.
	 * @param Object returnObject An object to store the return value in, so as not to break the chain. If passed in the
	 *                            chain will not be broken and the result will be assigned to this object.
	 * @type Object
	 * @cat Plugins/Dimensions
	 */
	position: function(options, returnObject) {
		var elem = this[0], parent = elem.parentNode, op = elem.offsetParent,
		    options = $.extend({ margin: false, border: false, padding: false, scroll: false }, options || {}),
			x = elem.offsetLeft,
			y = elem.offsetTop, 
			sl = elem.scrollLeft, 
			st = elem.scrollTop;
			
		// Mozilla and IE do not add the border
		if ($.browser.mozilla || $.browser.msie) {
			// add borders to offset
			x += num(elem, 'borderLeftWidth');
			y += num(elem, 'borderTopWidth');
		}

		if ($.browser.mozilla) {
			do {
				// Mozilla does not add the border for a parent that has overflow set to anything but visible
				if ($.browser.mozilla && parent != elem && $.css(parent, 'overflow') != 'visible') {
					x += num(parent, 'borderLeftWidth');
					y += num(parent, 'borderTopWidth');
				}

				if (parent == op) break; // break if we are already at the offestParent
			} while ((parent = parent.parentNode) && (parent.tagName.toLowerCase() != 'body' || parent.tagName.toLowerCase() != 'html'));
		}
		
		var returnValue = handleOffsetReturn(elem, options, x, y, sl, st);
		
		if (returnObject) { $.extend(returnObject, returnValue); return this; }
		else              { return returnValue; }
	},
	
	/**
	 * Returns the location of the element in pixels from the top left corner of the viewport.
	 *
	 * For accurate readings make sure to use pixel values for margins, borders and padding.
	 * 
	 * Known issues:
	 *  - Issue: A div positioned relative or static without any content before it and its parent will report an offsetTop of 0 in Safari
	 *    Workaround: Place content before the relative div ... and set height and width to 0 and overflow to hidden
	 *
	 * @example $("#testdiv").offset()
	 * @result { top: 100, left: 100, scrollTop: 10, scrollLeft: 10 }
	 *
	 * @example $("#testdiv").offset({ scroll: false })
	 * @result { top: 90, left: 90 }
	 *
	 * @example var offset = {}
	 * $("#testdiv").offset({ scroll: false }, offset)
	 * @result offset = { top: 90, left: 90 }
	 *
	 * @name offset
	 * @param Map options Optional settings to configure the way the offset is calculated.
	 * @option Boolean margin Should the margin of the element be included in the calculations? True by default.
	 * @option Boolean border Should the border of the element be included in the calculations? False by default.
	 * @option Boolean padding Should the padding of the element be included in the calculations? False by default.
	 * @option Boolean scroll Should the scroll offsets of the parent elements be included in the calculations? True by default.
	 *                        When true it adds the totla scroll offets of all parents to the total offset and also adds two properties
	 *                        to the returned object, scrollTop and scrollLeft. 
	 * @options Boolean lite Will use offsetLite instead of offset when set to true. False by default.
	 * @param Object returnObject An object to store the return value in, so as not to break the chain. If passed in the
	 *                            chain will not be broken and the result will be assigned to this object.
	 * @type Object
	 * @cat Plugins/Dimensions
	 */
	offset: function(options, returnObject) {
		var x = 0, y = 0, sl = 0, st = 0,
		    elem = this[0], parent = this[0], op, parPos, elemPos = $.css(elem, 'position'),
		    mo = $.browser.mozilla, ie = $.browser.msie, sf = $.browser.safari, oa = $.browser.opera,
		    absparent = false, relparent = false, 
		    options = $.extend({ margin: true, border: false, padding: false, scroll: true, lite: false }, options || {});
		
		// Use offsetLite if lite option is true
		if (options.lite) return this.offsetLite(options, returnObject);
		
		if (elem.tagName.toLowerCase() == 'body') {
			// Safari is the only one to get offsetLeft and offsetTop properties of the body "correct"
			// Except they all mess up when the body is positioned absolute or relative
			x = elem.offsetLeft;
			y = elem.offsetTop;
			// Mozilla ignores margin and subtracts border from body element
			if (mo) {
				x += num(elem, 'marginLeft') + (num(elem, 'borderLeftWidth')*2);
				y += num(elem, 'marginTop')  + (num(elem, 'borderTopWidth') *2);
			} else
			// Opera ignores margin
			if (oa) {
				x += num(elem, 'marginLeft');
				y += num(elem, 'marginTop');
			} else
			// IE does not add the border in Standards Mode
			if (ie && jQuery.boxModel) {
				x += num(elem, 'borderLeftWidth');
				y += num(elem, 'borderTopWidth');
			}
		} else {
			do {
				parPos = $.css(parent, 'position');
			
				x += parent.offsetLeft;
				y += parent.offsetTop;

				// Mozilla and IE do not add the border
				if (mo || ie) {
					// add borders to offset
					x += num(parent, 'borderLeftWidth');
					y += num(parent, 'borderTopWidth');

					// Mozilla does not include the border on body if an element isn't positioned absolute and is without an absolute parent
					if (mo && parPos == 'absolute') absparent = true;
					// IE does not include the border on the body if an element is position static and without an absolute or relative parent
					if (ie && parPos == 'relative') relparent = true;
				}

				op = parent.offsetParent;
				if (options.scroll || mo) {
					do {
						if (options.scroll) {
							// get scroll offsets
							sl += parent.scrollLeft;
							st += parent.scrollTop;
						}
				
						// Mozilla does not add the border for a parent that has overflow set to anything but visible
						if (mo && parent != elem && $.css(parent, 'overflow') != 'visible') {
							x += num(parent, 'borderLeftWidth');
							y += num(parent, 'borderTopWidth');
						}
				
						parent = parent.parentNode;
					} while (parent != op);
				}
				parent = op;

				if (parent.tagName.toLowerCase() == 'body' || parent.tagName.toLowerCase() == 'html') {
					// Safari and IE Standards Mode doesn't add the body margin for elments positioned with static or relative
					if ((sf || (ie && $.boxModel)) && elemPos != 'absolute' && elemPos != 'fixed') {
						x += num(parent, 'marginLeft');
						y += num(parent, 'marginTop');
					}
					// Mozilla does not include the border on body if an element isn't positioned absolute and is without an absolute parent
					// IE does not include the border on the body if an element is positioned static and without an absolute or relative parent
					if ( (mo && !absparent && elemPos != 'fixed') || 
					     (ie && elemPos == 'static' && !relparent) ) {
						x += num(parent, 'borderLeftWidth');
						y += num(parent, 'borderTopWidth');
					}
					break; // Exit the loop
				}
			} while (parent);
		}

		var returnValue = handleOffsetReturn(elem, options, x, y, sl, st);

		if (returnObject) { $.extend(returnObject, returnValue); return this; }
		else              { return returnValue; }
	},
	
	/**
	 * Returns the location of the element in pixels from the top left corner of the viewport.
	 * This method is much faster than offset but not as accurate. This method can be invoked
	 * by setting the lite option to true in the offset method.
	 *
	 * @name offsetLite
	 * @param Map options Optional settings to configure the way the offset is calculated.
	 * @option Boolean margin Should the margin of the element be included in the calculations? True by default.
	 * @option Boolean border Should the border of the element be included in the calculations? False by default.
	 * @option Boolean padding Should the padding of the element be included in the calculations? False by default.
	 * @option Boolean scroll Should the scroll offsets of the parent elements be included in the calculations? True by default.
	 *                        When true it adds the totla scroll offets of all parents to the total offset and also adds two properties
	 *                        to the returned object, scrollTop and scrollLeft. 
	 * @param Object returnObject An object to store the return value in, so as not to break the chain. If passed in the
	 *                            chain will not be broken and the result will be assigned to this object.
	 * @type Object
	 * @cat Plugins/Dimensions
	 */
	offsetLite: function(options, returnObject) {
		var x = 0, y = 0, sl = 0, st = 0, parent = this[0], op, 
		    options = $.extend({ margin: true, border: false, padding: false, scroll: true }, options || {});
				
		do {
			x += parent.offsetLeft;
			y += parent.offsetTop;

			op = parent.offsetParent;
			if (options.scroll) {
				// get scroll offsets
				do {
					sl += parent.scrollLeft;
					st += parent.scrollTop;
					parent = parent.parentNode;
				} while(parent != op);
			}
			parent = op;
		} while (parent && parent.tagName.toLowerCase() != 'body' && parent.tagName.toLowerCase() != 'html');

		var returnValue = handleOffsetReturn(this[0], options, x, y, sl, st);

		if (returnObject) { $.extend(returnObject, returnValue); return this; }
		else              { return returnValue; }
	}
});

/**
 * Handles converting a CSS Style into an Integer.
 * @private
 */
var num = function(el, prop) {
	return parseInt($.css(el.jquery?el[0]:el,prop))||0;
};

/**
 * Handles the return value of the offset and offsetLite methods.
 * @private
 */
var handleOffsetReturn = function(elem, options, x, y, sl, st) {
	if ( !options.margin ) {
		x -= num(elem, 'marginLeft');
		y -= num(elem, 'marginTop');
	}

	// Safari and Opera do not add the border for the element
	if ( options.border && ($.browser.safari || $.browser.opera) ) {
		x += num(elem, 'borderLeftWidth');
		y += num(elem, 'borderTopWidth');
	} else if ( !options.border && !($.browser.safari || $.browser.opera) ) {
		x -= num(elem, 'borderLeftWidth');
		y -= num(elem, 'borderTopWidth');
	}

	if ( options.padding ) {
		x += num(elem, 'paddingLeft');
		y += num(elem, 'paddingTop');
	}
	
	// do not include scroll offset on the element
	if ( options.scroll ) {
		sl -= elem.scrollLeft;
		st -= elem.scrollTop;
	}

	return options.scroll ? { top: y - st, left: x - sl, scrollTop:  st, scrollLeft: sl }
	                      : { top: y, left: x };
};

})(jQuery);/*
 * jQuery delegate plug-in v1.0
 *
 * Copyright (c) 2007 JÃ¶rn Zaefferer
 *
 * $Id: jquery.delegate.js 4786 2008-02-19 20:02:34Z joern.zaefferer $
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

// provides cross-browser focusin and focusout events
// IE has native support, in other browsers, use event caputuring (neither bubbles)

// provides delegate(type: String, delegate: Selector, handler: Callback) plugin for easier event delegation
// handler is only called when $(event.target).is(delegate), in the scope of the jQuery-object for event.target 

// provides triggerEvent(type: String, target: Element) to trigger delegated events
;(function($) {
	$.each({
		focus: 'focusin',
		blur: 'focusout'	
	}, function( original, fix ){
		$.event.special[fix] = {
			setup:function() {
				if ( $.browser.msie ) return false;
				this.addEventListener( original, $.event.special[fix].handler, true );
			},
			teardown:function() {
				if ( $.browser.msie ) return false;
				this.removeEventListener( original,
				$.event.special[fix].handler, true );
			},
			handler: function(e) {
				arguments[0] = $.event.fix(e);
				arguments[0].type = fix;
				return $.event.handle.apply(this, arguments);
			}
		};
	});

	$.extend($.fn, {
		delegate: function(type, delegate, handler) {
			return this.bind(type, function(event) {
				var target = $(event.target);
				if (target.is(delegate)) {
					return handler.apply(target, arguments);
				}
			});
		},
		triggerEvent: function(type, target) {
			return this.triggerHandler(type, [jQuery.event.fix({ type: type, target: target })]);
		}
	})
})(jQuery);
/*
 * jQuery Tooltip plugin 1.3
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
 * http://docs.jquery.com/Plugins/Tooltip
 *
 * Copyright (c) 2006 - 2008 JÃ¶rn Zaefferer
 *
 * $Id: jquery.tooltip.js 5741 2008-06-21 15:22:16Z joern.zaefferer $
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
 
;(function($) {
	
		// the tooltip element
	var helper = {},
		// the current tooltipped element
		current,
		// the title of the current element, used for restoring
		title,
		// timeout id for delayed tooltips
		tID,
		// IE 5.5 or 6
		IE = $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent),
		// flag for mouse tracking
		track = false;
	
	$.tooltip = {
		blocked: false,
		defaults: {
			delay: 200,
			fade: false,
			showURL: true,
			extraClass: "",
			top: 15,
			left: 15,
			id: "tooltip"
		},
		block: function() {
			$.tooltip.blocked = !$.tooltip.blocked;
		}
	};
	
	$.fn.extend({
		tooltip: function(settings) {
			settings = $.extend({}, $.tooltip.defaults, settings);
			createHelper(settings);
			return this.each(function() {
					$.data(this, "tooltip", settings);
					this.tOpacity = helper.parent.css("opacity");
					// copy tooltip into its own expando and remove the title
					this.tooltipText = this.title;
					$(this).removeAttr("title");
					// also remove alt attribute to prevent default tooltip in IE
					this.alt = "";
				})
				.mouseover(save)
				.mouseout(hide)
				.click(hide);
		},
		fixPNG: IE ? function() {
			return this.each(function () {
				var image = $(this).css('backgroundImage');
				if (image.match(/^url\(["']?(.*\.png)["']?\)$/i)) {
					image = RegExp.$1;
					$(this).css({
						'backgroundImage': 'none',
						'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')"
					}).each(function () {
						var position = $(this).css('position');
						if (position != 'absolute' && position != 'relative')
							$(this).css('position', 'relative');
					});
				}
			});
		} : function() { return this; },
		unfixPNG: IE ? function() {
			return this.each(function () {
				$(this).css({'filter': '', backgroundImage: ''});
			});
		} : function() { return this; },
		hideWhenEmpty: function() {
			return this.each(function() {
				$(this)[ $(this).html() ? "show" : "hide" ]();
			});
		},
		url: function() {
			return this.attr('href') || this.attr('src');
		}
	});
	
	function createHelper(settings) {
		// there can be only one tooltip helper
		if( helper.parent )
			return;
		// create the helper, h3 for title, div for url
		helper.parent = $('<div id="' + settings.id + '"><h3></h3><div class="body"></div><div class="url"></div></div>')
			// add to document
			.appendTo(document.body)
			// hide it at first
			.hide();
			
		// apply bgiframe if available
		if ( $.fn.bgiframe )
			helper.parent.bgiframe();
		
		// save references to title and url elements
		helper.title = $('h3', helper.parent);
		helper.body = $('div.body', helper.parent);
		helper.url = $('div.url', helper.parent);
	}
	
	function settings(element) {
		return $.data(element, "tooltip");
	}
	
	// main event handler to start showing tooltips
	function handle(event) {
		// show helper, either with timeout or on instant
		if( settings(this).delay )
			tID = setTimeout(show, settings(this).delay);
		else
			show();
		
		// if selected, update the helper position when the mouse moves
		track = !!settings(this).track;
		$(document.body).bind('mousemove', update);
			
		// update at least once
		update(event);
	}
	
	// save elements title before the tooltip is displayed
	function save() {
		// if this is the current source, or it has no title (occurs with click event), stop
		if ( $.tooltip.blocked || this == current || (!this.tooltipText && !settings(this).bodyHandler) )
			return;

		// save current
		current = this;
		title = this.tooltipText;
		
		if ( settings(this).bodyHandler ) {
			helper.title.hide();
			var bodyContent = settings(this).bodyHandler.call(this);
			if (bodyContent.nodeType || bodyContent.jquery) {
				helper.body.empty().append(bodyContent)
			} else {
				helper.body.html( bodyContent );
			}
			helper.body.show();
		} else if ( settings(this).showBody ) {
			var parts = title.split(settings(this).showBody);
			helper.title.html(parts.shift()).show();
			helper.body.empty();
			for(var i = 0, part; (part = parts[i]); i++) {
				if(i > 0)
					helper.body.append("<br/>");
				helper.body.append(part);
			}
			helper.body.hideWhenEmpty();
		} else {
			helper.title.html(title).show();
			helper.body.hide();
		}
		
		// if element has href or src, add and show it, otherwise hide it
		if( settings(this).showURL && $(this).url() )
			helper.url.html( $(this).url().replace('http://', '') ).show();
		else 
			helper.url.hide();
		
		// add an optional class for this tip
		helper.parent.addClass(settings(this).extraClass);

		// fix PNG background for IE
		if (settings(this).fixPNG )
			helper.parent.fixPNG();
			
		handle.apply(this, arguments);
	}
	
	// delete timeout and show helper
	function show() {
		tID = null;
		if ((!IE || !$.fn.bgiframe) && settings(current).fade) {
			if (helper.parent.is(":animated"))
				helper.parent.stop().show().fadeTo(settings(current).fade, current.tOpacity);
			else
				helper.parent.is(':visible') ? helper.parent.fadeTo(settings(current).fade, current.tOpacity) : helper.parent.fadeIn(settings(current).fade);
		} else {
			helper.parent.show();
		}
		update();
	}
	
	/**
	 * callback for mousemove
	 * updates the helper position
	 * removes itself when no current element
	 */
	function update(event)	{
		if($.tooltip.blocked)
			return;
		
		if (event && event.target.tagName == "OPTION") {
			return;
		}
		
		// stop updating when tracking is disabled and the tooltip is visible
		if ( !track && helper.parent.is(":visible")) {
			$(document.body).unbind('mousemove', update)
		}
		
		// if no current element is available, remove this listener
		if( current == null ) {
			$(document.body).unbind('mousemove', update);
			return;	
		}
		
		// remove position helper classes
		helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");
		
		var left = helper.parent[0].offsetLeft;
		var top = helper.parent[0].offsetTop;
		if (event) {
			// position the helper 15 pixel to bottom right, starting from mouse position
			left = event.pageX + settings(current).left;
			top = event.pageY + settings(current).top;
			var right='auto';
			if (settings(current).positionLeft) {
				right = $(window).width() - left;
				left = 'auto';
			}
			helper.parent.css({
				left: left,
				right: right,
				top: top
			});
		}
		
		var v = viewport(),
			h = helper.parent[0];
		// check horizontal position
		if (v.x + v.cx < h.offsetLeft + h.offsetWidth) {
			left -= h.offsetWidth + 20 + settings(current).left;
			helper.parent.css({left: left + 'px'}).addClass("viewport-right");
		}
		// check vertical position
		if (v.y + v.cy < h.offsetTop + h.offsetHeight) {
			top -= h.offsetHeight + 20 + settings(current).top;
			helper.parent.css({top: top + 'px'}).addClass("viewport-bottom");
		}
	}
	
	function viewport() {
		return {
			x: $(window).scrollLeft(),
			y: $(window).scrollTop(),
			cx: $(window).width(),
			cy: $(window).height()
		};
	}
	
	// hide helper and restore added classes and the title
	function hide(event) {
		if($.tooltip.blocked)
			return;
		// clear timeout if possible
		if(tID)
			clearTimeout(tID);
		// no more current element
		current = null;
		
		var tsettings = settings(this);
		function complete() {
			helper.parent.removeClass( tsettings.extraClass ).hide().css("opacity", "");
		}
		if ((!IE || !$.fn.bgiframe) && tsettings.fade) {
			if (helper.parent.is(':animated'))
				helper.parent.stop().fadeTo(tsettings.fade, 0, complete);
			else
				helper.parent.stop().fadeOut(tsettings.fade, complete);
		} else
			complete();
		
		if( settings(this).fixPNG )
			helper.parent.unfixPNG();
	}
	
})(jQuery);
/**
 * WYSIWYG - jQuery plugin 0.4
 *
 * Copyright (c) 2008 Juan M Martinez
 * http://plugins.jquery.com/project/jWYSIWYG
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * $Id: $
 */
(function($) {
    $.fn.document = function() {
        var element = this[0];

        if (element.nodeName.toLowerCase() == 'iframe')
            return element.contentWindow.document;
        /*
        return ( $.browser.msie )
        ? document.frames[element.id].document
        : element.contentWindow.document // contentDocument;
        */
        else
            return $(this);
    };

    $.fn.documentSelection = function() {
        var element = this[0];

        if (element.contentWindow.document.selection)
            return element.contentWindow.document.selection.createRange().text;
        else
            return element.contentWindow.getSelection().toString();
    };

    $.fn.wysiwyg = function(options) {
        if (arguments.length > 0 && arguments[0].constructor == String) {
            var action = arguments[0].toString();
            var params = [];

            for (var i = 1; i < arguments.length; i++)
                params[i - 1] = arguments[i];

            if (action in Wysiwyg) {
                return this.each(function() {
                    $.data(this, 'wysiwyg')
                     .designMode();

                    Wysiwyg[action].apply(this, params);
                });
            }
            else return this;
        }

        var controls = {};

        /**
        * If the user set custom controls, we catch it, and merge with the
        * defaults controls later.
        */
        if (options && options.controls) {
            var controls = options.controls;
            delete options.controls;
        }

        var options = $.extend({
            html: '<' + '?xml version="1.0" encoding="UTF-8"?' + '><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">STYLE_SHEET</head><body>INITIAL_CONTENT</body></html>',
            css: {},

            debug: false,

            autoSave: true,  // http://code.google.com/p/jwysiwyg/issues/detail?id=11
            rmUnwantedBr: true,  // http://code.google.com/p/jwysiwyg/issues/detail?id=15
            brIE: true,

            controls: {},
            messages: {}
        }, options);

        $.extend(options.messages, Wysiwyg.MSGS_EN);
        $.extend(options.controls, Wysiwyg.TOOLBAR);

        for (var control in controls) {
            if (control in options.controls)
                $.extend(options.controls[control], controls[control]);
            else
                options.controls[control] = controls[control];
        }

        // not break the chain
        return this.each(function() {
            Wysiwyg(this, options);
        });
    };

    function Wysiwyg(element, options) {
        return this instanceof Wysiwyg
            ? this.init(element, options)
            : new Wysiwyg(element, options);
    }

    $.extend(Wysiwyg, {
        insertImage: function(szURL, attributes) {
            var self = $.data(this, 'wysiwyg');

            if (self.constructor == Wysiwyg && szURL && szURL.length > 0) {
                if (attributes) {
                    self.editorDoc.execCommand('insertImage', false, '#jwysiwyg#');
                    var img = self.getElementByAttributeValue('img', 'src', '#jwysiwyg#');

                    if (img) {
                        img.src = szURL;

                        for (var attribute in attributes) {
                            img.setAttribute(attribute, attributes[attribute]);
                        }
                    }
                }
                else {
                    self.editorDoc.execCommand('insertImage', false, szURL);
                }
            }
        },

        createLink: function(szURL) {
            var self = $.data(this, 'wysiwyg');

            if (self.constructor == Wysiwyg && szURL && szURL.length > 0) {
                var selection = $(self.editor).documentSelection();

                if (selection.length > 0) {
                    self.editorDoc.execCommand('unlink', false, []);
                    self.editorDoc.execCommand('createLink', false, szURL);
                }
                else if (self.options.messages.nonSelection)
                    alert(self.options.messages.nonSelection);
            }
        },

        clear: function() {
            var self = $.data(this, 'wysiwyg');
            self.setContent('');
            self.saveContent();
        },

        MSGS_EN: {
            nonSelection: 'select the text you wish to link'
        },

        TOOLBAR: {
            bold: { visible: true, tags: ['b', 'strong'], css: { fontWeight: 'bold'} },
            italic: { visible: true, tags: ['i', 'em'], css: { fontStyle: 'italic'} },
            strikeThrough: { visible: false, tags: ['s', 'strike'], css: { textDecoration: 'line-through'} },
            underline: { visible: false, tags: ['u'], css: { textDecoration: 'underline'} },

            separator00: { visible: false, separator: true },

            justifyLeft: { visible: false, css: { textAlign: 'left'} },
            justifyCenter: { visible: false, tags: ['center'], css: { textAlign: 'center'} },
            justifyRight: { visible: false, css: { textAlign: 'right'} },
            justifyFull: { visible: false, css: { textAlign: 'justify'} },

            separator01: { visible: false, separator: true },

            indent: { visible: false },
            outdent: { visible: false },

            separator02: { visible: false, separator: true },

            subscript: { visible: false, tags: ['sub'] },
            superscript: { visible: false, tags: ['sup'] },

            separator03: { visible: false, separator: true },

            undo: { visible: false },
            redo: { visible: false },

            separator04: { visible: false, separator: true },

            insertOrderedList: { visible: false, tags: ['ol'] },
            insertUnorderedList: { visible: false, tags: ['ul'] },
            insertHorizontalRule: { visible: false, tags: ['hr'] },

            separator05: { separator: true },

            createLink: {
                visible: true,
                exec: function() {
                    var selection = $(this.editor).documentSelection();

                    if (selection.length > 0) {
                        var table = $(this.editor).parent();

                        if (table != null) {
                            table = table.parent();
                            if (table != null) {
                                table = table.parent();
                                if (table != null) {
                                    table = table.parent();
                                }
                            }
                        }

                        var filetable = $(table).find('.datatable')
                        var szURL = null;

                        if (filetable) {
                            var checkedRadio = filetable.find('td > input[type=radio]:checked')

                            if (checkedRadio && checkedRadio.length > 0)
                                szURL = checkedRadio.attr('value');
                            else {
                                if ($.browser.msie) {
                                    this.editorDoc.execCommand('createLink', true, null);
                                    return;
                                }
                                else
                                    szURL = prompt('URL', 'http://');
                            }
                        }
                        else {
                            if ($.browser.msie) {
                                this.editorDoc.execCommand('createLink', true, null);
                                return;
                            }
                            else
                                szURL = prompt('URL', 'http://');
                        }

                        if (szURL && szURL.length > 0) {
                            this.editorDoc.execCommand('unlink', false, []);
                            this.editorDoc.execCommand('createLink', false, szURL);

                        }
                    }
                    else if (this.options.messages.nonSelection)
                        alert(this.options.messages.nonSelection);
                },

                tags: ['a']
            },

            insertImage: {
                visible: true,
                exec: function() {

                    var table = $(this.editor).parent();

                    if (table != null) {
                        table = table.parent();
                        if (table != null) {
                            table = table.parent();
                            if (table != null) {
                                table = table.parent();
                            }
                        }
                    }

                    var filetable = $(table).find('.datatable')
                    var szURL = null;

                    if (filetable) {
                        var checkedRadio = filetable.find('td > input[type=radio]:checked')

                        if (checkedRadio && checkedRadio.length > 0) {
                            szURL = checkedRadio.attr('value');
                        }
                        else {
                            if ($.browser.msie) {
                                this.editorDoc.execCommand('insertImage', true, null);
                                return;
                            }
                            else
                                szURL = prompt('URL', 'http://');
                        }
                    }
                    else {
                        if ($.browser.msie) {
                            this.editorDoc.execCommand('insertImage', true, null);
                            return;
                        }
                        else
                            szURL = prompt('URL', 'http://');
                    }

                    if (szURL && szURL.length > 0)
                        this.editorDoc.execCommand('insertImage', false, szURL);

                },

                tags: ['img']
            },

            separator06: { separator: true },

            h1mozilla: { visible: true && $.browser.mozilla, className: 'h1', command: 'heading', arguments: ['h1'], tags: ['h1'] },
            h2mozilla: { visible: true && $.browser.mozilla, className: 'h2', command: 'heading', arguments: ['h2'], tags: ['h2'] },
            h3mozilla: { visible: true && $.browser.mozilla, className: 'h3', command: 'heading', arguments: ['h3'], tags: ['h3'] },

            h1: { visible: true && !($.browser.mozilla), className: 'h1', command: 'formatBlock', arguments: ['Heading 1'], tags: ['h1'] },
            h2: { visible: true && !($.browser.mozilla), className: 'h2', command: 'formatBlock', arguments: ['Heading 2'], tags: ['h2'] },
            h3: { visible: true && !($.browser.mozilla), className: 'h3', command: 'formatBlock', arguments: ['Heading 3'], tags: ['h3'] },

            separator07: { visible: false, separator: true },

            cut: { visible: false },
            copy: { visible: false },
            paste: { visible: false },

            separator08: { separator: true && !($.browser.msie) },

            increaseFontSize: { visible: true && !($.browser.msie), tags: ['big'] },
            decreaseFontSize: { visible: true && !($.browser.msie), tags: ['small'] },

            separator09: { separator: true },

            html: {
                visible: false,
                exec: function() {
                    if (this.viewHTML) {
                        this.setContent($(this.original).val());
                        $(this.original).hide();
                    }
                    else {
                        this.saveContent();
                        $(this.original).show();
                    }

                    this.viewHTML = !(this.viewHTML);
                }
            },

            removeFormat: {
                visible: true,
                exec: function() {
                    this.editorDoc.execCommand('removeFormat', false, []);
                    this.editorDoc.execCommand('unlink', false, []);
                }
            }
        }
    });

    $.extend(Wysiwyg.prototype,
    {
        original: null,
        options: {},

        element: null,
        editor: null,

        init: function(element, options) {
            var self = this;

            this.editor = element;
            this.options = options || {};

            $.data(element, 'wysiwyg', this);

            var newX = element.width || element.clientWidth;
            var newY = element.height || element.clientHeight;

            if (element.nodeName.toLowerCase() == 'textarea') {
                this.original = element;

                if (newX == 0 && element.cols)
                    newX = (element.cols * 8) + 21;

                if (newY == 0 && element.rows)
                    newY = (element.rows * 16) + 16;

                var editor = this.editor = $('<iframe></iframe>').css({
                    minHeight: (newY - 6).toString() + 'px',
                    width: (newX - 8).toString() + 'px'
                }).attr('id', $(element).attr('id') + 'IFrame');

                if ($.browser.msie) {
                    this.editor
                        .css('height', (newY).toString() + 'px');

                    /**
                    var editor = $('<span></span>').css({
                    width     : ( newX - 6 ).toString() + 'px',
                    height    : ( newY - 8 ).toString() + 'px'
                    }).attr('id', $(element).attr('id') + 'IFrame');

                    editor.outerHTML = this.editor.outerHTML;
                    */
                }
            }

            var panel = this.panel = $('<ul></ul>').addClass('panel');

            this.appendControls();
            this.element = $('<div></div>').css({
                width: (newX > 0) ? (newX).toString() + 'px' : '100%'
            }).addClass('wysiwyg')
              .append(panel)
              .append($('<div><!-- --></div>').css({ clear: 'both' }))
              .append(editor);

            $(element)
            // .css('display', 'none')
            .hide()
            .before(this.element);

            this.viewHTML = false;

            this.initialHeight = newY - 8;
            this.initialContent = $(element).text();

            this.initFrame();

            if (this.initialContent.length == 0)
                this.setContent('');

            if (this.options.autoSave)
                $('form').submit(function() { self.saveContent(); });
        },

        initFrame: function() {
            var self = this;
            var style = '';

            /**
            * @link http://code.google.com/p/jwysiwyg/issues/detail?id=14
            */
            if (this.options.css && this.options.css.constructor == String)
                style = '<link rel="stylesheet" type="text/css" media="screen" href="' + this.options.css + '" />';

            this.editorDoc = $(this.editor).document();
            this.editorDoc_designMode = false;

            try {
                this.editorDoc.designMode = 'on';
                this.editorDoc_designMode = true;
            } catch (e) {
                // Will fail on Gecko if the editor is placed in an hidden container element
                // The design mode will be set ones the editor is focused

                $(this.editorDoc).focus(function() {
                    self.designMode();
                });
            }

            this.editorDoc.open();
            this.editorDoc.write(
                this.options.html
                    .replace(/INITIAL_CONTENT/, this.initialContent)
                    .replace(/STYLE_SHEET/, style)
            );
            this.editorDoc.close();
            this.editorDoc.contentEditable = 'true';

            if ($.browser.msie) {
                /**
                * Remove the horrible border it has on IE.
                */
                setTimeout(function() { $(self.editorDoc.body).css('border', 'none'); }, 0);
            }

            $(this.editorDoc).click(function(event) {
                self.checkTargets(event.target ? event.target : event.srcElement);
            });

            /**
            * @link http://code.google.com/p/jwysiwyg/issues/detail?id=20
            */
            $(this.original).focus(function() {
                $(self.editorDoc.body).focus();
            });

            if (this.options.autoSave) {
                /**
                * @link http://code.google.com/p/jwysiwyg/issues/detail?id=11
                */
                $(this.editorDoc).keydown(function() { self.saveContent(); })
                                 .mousedown(function() { self.saveContent(); });
            }

            if (this.options.css) {
                setTimeout(function() {
                    if (self.options.css.constructor == String) {
                        /**
                        * $(self.editorDoc)
                        * .find('head')
                        * .append(
                        *     $('<link rel="stylesheet" type="text/css" media="screen" />')
                        *     .attr('href', self.options.css)
                        * );
                        */
                    }
                    else
                        $(self.editorDoc).find('body').css(self.options.css);
                }, 0);
            }

            $(this.editorDoc).keydown(function(event) {
                if ($.browser.msie && self.options.brIE && event.keyCode == 13) {
                    var rng = self.getRange();
                    rng.pasteHTML('<br />');
                    rng.collapse(false);
                    rng.select();

                    return false;
                }
            });
        },

        designMode: function() {
            if (!(this.editorDoc_designMode)) {
                try {
                    this.editorDoc.designMode = 'on';
                    this.editorDoc_designMode = true;
                } catch (e) { }
            }
        },

        getSelection: function() {
            return (window.getSelection) ? window.getSelection() : document.selection;
        },

        getRange: function() {
            var selection = this.getSelection();

            if (!(selection))
                return null;

            return (selection.rangeCount > 0) ? selection.getRangeAt(0) : selection.createRange();
        },

        getContent: function() {
            return $($(this.editor).document()).find('body').html();
        },

        setContent: function(newContent) {
            $($(this.editor).document()).find('body').html(newContent);
        },

        saveContent: function() {
            if (this.original) {
                var content = this.getContent();

                if (this.options.rmUnwantedBr)
                    content = (content.substr(-4) == '<br>') ? content.substr(0, content.length - 4) : content;

                $(this.original).val(content);
            }
        },

        appendMenu: function(cmd, args, className, fn) {
            var self = this;
            var args = args || [];

            $('<li></li>').append(
                $('<a><!-- --></a>').addClass(className || cmd)
            ).mousedown(function() {
                if (fn) fn.apply(self); else self.editorDoc.execCommand(cmd, false, args);
                if (self.options.autoSave) self.saveContent();
            }).appendTo(this.panel);
        },

        appendMenuSeparator: function() {
            $('<li class="separator"></li>').appendTo(this.panel);
        },

        appendControls: function() {
            for (var name in this.options.controls) {
                var control = this.options.controls[name];

                if (control.separator) {
                    if (control.visible !== false)
                        this.appendMenuSeparator();
                }
                else if (control.visible) {
                    this.appendMenu(
                        control.command || name, control.arguments || [],
                        control.className || control.command || name || 'empty', control.exec
                    );
                }
            }
        },

        checkTargets: function(element) {
            for (var name in this.options.controls) {
                var control = this.options.controls[name];
                var className = control.className || control.command || name || 'empty';

                $('.' + className, this.panel).removeClass('active');

                if (control.tags) {
                    var elm = element;

                    do {
                        if (elm.nodeType != 1)
                            break;

                        if ($.inArray(elm.tagName.toLowerCase(), control.tags) != -1)
                            $('.' + className, this.panel).addClass('active');
                    } while (elm = elm.parentNode);
                }

                if (control.css) {
                    var elm = $(element);

                    do {
                        if (elm[0].nodeType != 1)
                            break;

                        for (var cssProperty in control.css)
                            if (elm.css(cssProperty).toString().toLowerCase() == control.css[cssProperty])
                            $('.' + className, this.panel).addClass('active');
                    } while (elm = elm.parent());
                }
            }
        },

        getElementByAttributeValue: function(tagName, attributeName, attributeValue) {
            var elements = this.editorDoc.getElementsByTagName(tagName);

            for (var i = 0; i < elements.length; i++) {
                var value = elements[i].getAttribute(attributeName);

                if ($.browser.msie) {
                    /** IE add full path, so I check by the last chars. */
                    value = value.substr(value.length - attributeValue.length);
                }

                if (value == attributeValue)
                    return elements[i];
            }

            return false;
        }
    });
})(jQuery);/**
 * Tabs - jQuery plugin for accessible, unobtrusive tabs
 * @requires jQuery v1.1.1
 *
 * http://stilbuero.de/tabs/
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Version: 2.7.4
 */

(function($) { // block scope

$.extend({
    tabs: {
        remoteCount: 0 // TODO in Tabs 3 this is going to be more cleanly in one single namespace
    }
});

/**
 * Create an accessible, unobtrusive tab interface based on a particular HTML structure.
 *
 * The underlying HTML has to look like this:
 *
 * <div id="container">
 *     <ul>
 *         <li><a href="#fragment-1">Section 1</a></li>
 *         <li><a href="#fragment-2">Section 2</a></li>
 *         <li><a href="#fragment-3">Section 3</a></li>
 *     </ul>
 *     <div id="fragment-1">
 *
 *     </div>
 *     <div id="fragment-2">
 *
 *     </div>
 *     <div id="fragment-3">
 *
 *     </div>
 * </div>
 *
 * Each anchor in the unordered list points directly to a section below represented by one of the
 * divs (the URI in the anchor's href attribute refers to the fragment with the corresponding id).
 * Because such HTML structure is fully functional on its own, e.g. without JavaScript, the tab
 * interface is accessible and unobtrusive.
 *
 * A tab is also bookmarkable via hash in the URL. Use the History/Remote plugin (Tabs will
 * auto-detect its presence) to fix the back (and forward) button.
 *
 * @example $('#container').tabs();
 * @desc Create a basic tab interface.
 * @example $('#container').tabs(2);
 * @desc Create a basic tab interface with the second tab initially activated.
 * @example $('#container').tabs({disabled: [3, 4]});
 * @desc Create a tab interface with the third and fourth tab being disabled.
 * @example $('#container').tabs({fxSlide: true});
 * @desc Create a tab interface that uses slide down/up animations for showing/hiding tab
 *       content upon tab switching.
 *
 * @param Number initial An integer specifying the position of the tab (no zero-based index) that
 *                       gets activated at first (on page load). Two alternative ways to specify
 *                       the active tab will overrule this argument. First a li element
 *                       (representing one single tab) belonging to the selected tab class, e.g.
 *                       set the selected tab class (default: "tabs-selected", see option
 *                       selectedClass) for one of the unordered li elements in the HTML source.
 *                       In addition if a fragment identifier/hash in the URL of the page refers
 *                       to the id of a tab container of a tab interface the corresponding tab will
 *                       be activated and both the initial argument as well as an eventually
 *                       declared class attribute will be overruled. Defaults to 1 if omitted.
 * @param Object settings An object literal containing key/value pairs to provide optional settings.
 * @option Array<Number> disabled An array containing the position of the tabs (no zero-based index)
 *                                that should be disabled on initialization. Default value: null.
 *                                A tab can also be disabled by simply adding the disabling class
 *                                (default: "tabs-disabled", see option disabledClass) to the li
 *                                element representing that particular tab.
 * @option Boolean bookmarkable Boolean flag indicating if support for bookmarking and history (via
 *                              changing hash in the URL of the browser) is enabled. Default value:
 *                              false, unless the History/Remote plugin is included. In that case the
 *                              default value becomes true. @see $.ajaxHistory.initialize
 * @option Boolean remote Boolean flag indicating that tab content has to be loaded remotely from
 *                        the url given in the href attribute of the tab menu anchor elements.
 * @option String spinner The content of this string is shown in a tab while remote content is loading.
 *                        Insert plain text as well as an img here. To turn off this notification
 *                        pass an empty string or null. Default: "Loading&#8230;".
 * @option String hashPrefix A String that is used for constructing the hash the link's href attribute
 *                           of a remote tab gets altered to, such as "#remote-1".
 *                           Default value: "remote-tab-".
 * @option Boolean fxFade Boolean flag indicating whether fade in/out animations are used for tab
 *                        switching. Can be combined with fxSlide. Will overrule fxShow/fxHide.
 *                        Default value: false.
 * @option Boolean fxSlide Boolean flag indicating whether slide down/up animations are used for tab
 *                         switching. Can be combined with fxFade. Will overrule fxShow/fxHide.
 *                         Default value: false.
 * @option String|Number fxSpeed A string representing one of the three predefined speeds ("slow",
 *                               "normal", or "fast") or the number of milliseconds (e.g. 1000) to
 *                               run an animation. Default value: "normal".
 * @option Object fxShow An object literal of the form jQuery's animate function expects for making
 *                       your own, custom animation to reveal a tab upon tab switch. Unlike fxFade
 *                       or fxSlide this animation is independent from an optional hide animation.
 *                       Default value: null. @see animate
 * @option Object fxHide An object literal of the form jQuery's animate function expects for making
 *                       your own, custom animation to hide a tab upon tab switch. Unlike fxFade
 *                       or fxSlide this animation is independent from an optional show animation.
 *                       Default value: null. @see animate
 * @option String|Number fxShowSpeed A string representing one of the three predefined speeds
 *                                   ("slow", "normal", or "fast") or the number of milliseconds
 *                                   (e.g. 1000) to run the animation specified in fxShow.
 *                                   Default value: fxSpeed.
 * @option String|Number fxHideSpeed A string representing one of the three predefined speeds
 *                                   ("slow", "normal", or "fast") or the number of milliseconds
 *                                   (e.g. 1000) to run the animation specified in fxHide.
 *                                   Default value: fxSpeed.
 * @option Boolean fxAutoHeight Boolean flag that if set to true causes all tab heights
 *                              to be constant (being the height of the tallest tab).
 *                              Default value: false.
 * @option Function onClick A function to be invoked upon tab switch, immediatly after a tab has
 *                          been clicked, e.g. before the other's tab content gets hidden. The
 *                          function gets passed three arguments: the first one is the clicked
 *                          tab (e.g. an anchor element), the second one is the DOM element
 *                          containing the content of the clicked tab (e.g. the div), the third
 *                          argument is the one of the tab that gets hidden. If this callback
 *                          returns false, the tab switch is canceled (use to disallow tab
 *                          switching for the reason of a failed form validation for example).
 *                          Default value: null.
 * @option Function onHide A function to be invoked upon tab switch, immediatly after one tab's
 *                         content got hidden (with or without an animation) and right before the
 *                         next tab is revealed. The function gets passed three arguments: the
 *                         first one is the clicked tab (e.g. an anchor element), the second one
 *                         is the DOM element containing the content of the clicked tab, (e.g. the
 *                         div), the third argument is the one of the tab that gets hidden.
 *                         Default value: null.
 * @option Function onShow A function to be invoked upon tab switch. This function is invoked
 *                         after the new tab has been revealed, e.g. after the switch is completed.
 *                         The function gets passed three arguments: the first one is the clicked
 *                         tab (e.g. an anchor element), the second one is the DOM element
 *                         containing the content of the clicked tab, (e.g. the div), the third
 *                         argument is the one of the tab that gets hidden. Default value: null.
 * @option String navClass A CSS class that is used to identify the tabs unordered list by class if
 *                         the required HTML structure differs from the default one.
 *                         Default value: "tabs-nav".
 * @option String selectedClass The CSS class attached to the li element representing the
 *                              currently selected (active) tab. Default value: "tabs-selected".
 * @option String disabledClass The CSS class attached to the li element representing a disabled
 *                              tab. Default value: "tabs-disabled".
 * @option String containerClass A CSS class that is used to identify tab containers by class if
 *                               the required HTML structure differs from the default one.
 *                               Default value: "tabs-container".
 * @option String hideClass The CSS class used for hiding inactive tabs. A class is used instead
 *                          of "display: none" in the style attribute to maintain control over
 *                          visibility in other media types than screen, most notably print.
 *                          Default value: "tabs-hide".
 * @option String loadingClass The CSS class used for indicating that an Ajax tab is currently
 *                             loading, for example by showing a spinner.
 *                             Default value: "tabs-loading".
 * @option String tabStruct @deprecated A CSS selector or basic XPath expression reflecting a
 *                          nested HTML structure that is different from the default single div
 *                          structure (one div with an id inside the overall container holds one
 *                          tab's content). If for instance an additional div is required to wrap
 *                          up the several tab containers such a structure is expressed by "div>div".
 *                          Default value: "div".
 * @type jQuery
 *
 * @name tabs
 * @cat Plugins/Tabs
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
$.fn.tabs = function(initial, settings) {

    // settings
    if (typeof initial == 'object') settings = initial; // no initial tab given but a settings object
    settings = $.extend({
        initial: (initial && typeof initial == 'number' && initial > 0) ? --initial : 0,
        disabled: null,
        bookmarkable: $.ajaxHistory ? true : false,
        remote: false,
        spinner: 'Loading&#8230;',
        hashPrefix: 'remote-tab-',
        fxFade: null,
        fxSlide: null,
        fxShow: null,
        fxHide: null,
        fxSpeed: 'normal',
        fxShowSpeed: null,
        fxHideSpeed: null,
        fxAutoHeight: false,
        onClick: null,
        onHide: null,
        onShow: null,
        navClass: 'tabs-nav',
        selectedClass: 'tabs-selected',
        disabledClass: 'tabs-disabled',
        containerClass: 'tabs-container',
        hideClass: 'tabs-hide',
        loadingClass: 'tabs-loading',
        tabStruct: 'div'
    }, settings || {});

    $.browser.msie6 = $.browser.msie && ($.browser.version && $.browser.version < 7 || /MSIE 6.0/.test(navigator.userAgent)); // do not check for 6.0 alone, userAgent in Windows Vista has "Windows NT 6.0"

    // helper to prevent scroll to fragment
    function unFocus() {
        scrollTo(0, 0);
    }

    // initialize tabs
    return this.each(function() {

        // remember wrapper for later
        var container = this;

        // setup nav
        var nav = $('ul.' + settings.navClass, container);
        nav = nav.size() && nav || $('>ul:eq(0)', container); // fallback to default structure
        var tabs = $('a', nav);

        // prepare remote tabs
        if (settings.remote) {
            tabs.each(function() {
                var id = settings.hashPrefix + (++$.tabs.remoteCount), hash = '#' + id, url = this.href;
                this.href = hash;
                $('<div id="' + id + '" class="' + settings.containerClass + '"></div>').appendTo(container);

                $(this).bind('loadRemoteTab', function(e, callback) {
                    var $$ = $(this).addClass(settings.loadingClass), span = $('span', this)[0], tabTitle = span.innerHTML;
                    if (settings.spinner) {
                        // TODO if spinner is image
                        span.innerHTML = '<em>' + settings.spinner + '</em>'; // WARNING: html(...) crashes Safari with jQuery 1.1.2
                    }
                    setTimeout(function() { // Timeout is again required in IE, "wait" for id being restored
                        $(hash).load(url, function() {
                            if (settings.spinner) {
                                span.innerHTML = tabTitle; // WARNING: html(...) crashes Safari with jQuery 1.1.2
                            }
                            $$.removeClass(settings.loadingClass);
                            callback && callback();
                        });
                    }, 0);
                });

            });
        }

        // set up containers
        var containers = $('div.' + settings.containerClass, container);
        containers = containers.size() && containers || $('>' + settings.tabStruct, container); // fallback to default structure

        // attach classes for styling if not present
        nav.is('.' + settings.navClass) || nav.addClass(settings.navClass);
        containers.each(function() {
            var $$ = $(this);
            $$.is('.' + settings.containerClass) || $$.addClass(settings.containerClass);
        });

        // try to retrieve active tab from class in HTML
        var hasSelectedClass = $('li', nav).index( $('li.' + settings.selectedClass, nav)[0] );
        if (hasSelectedClass >= 0) {
           settings.initial = hasSelectedClass;
        }

        // try to retrieve active tab from hash in url, will override class in HTML
        if (location.hash) {
            tabs.each(function(i) {
                if (this.hash == location.hash) {
                    settings.initial = i;
                    // prevent page scroll to fragment
                    if (($.browser.msie || $.browser.opera) && !settings.remote) {
                        var toShow = $(location.hash);
                        var toShowId = toShow.attr('id');
                        toShow.attr('id', '');
                        setTimeout(function() {
                            toShow.attr('id', toShowId); // restore id
                        }, 500);
                    }
                    unFocus();
                    return false; // break
                }
            });
        }
        if ($.browser.msie) {
            unFocus(); // fix IE focussing bottom of the page for some unknown reason
        }

        // highlight tab accordingly
        containers.filter(':eq(' + settings.initial + ')').show().end().not(':eq(' + settings.initial + ')').addClass(settings.hideClass);
        $('li', nav).removeClass(settings.selectedClass).eq(settings.initial).addClass(settings.selectedClass); // we need to remove classes eventually if hash takes precedence over class
        // trigger load of initial tab
        tabs.eq(settings.initial).trigger('loadRemoteTab').end();

        // setup auto height
        if (settings.fxAutoHeight) {
            // helper
            var _setAutoHeight = function(reset) {
                // get tab heights in top to bottom ordered array
                var heights = $.map(containers.get(), function(el) {
                    var h, jq = $(el);
                    if (reset) {
                        if ($.browser.msie6) {
                            el.style.removeExpression('behaviour');
                            el.style.height = '';
                            el.minHeight = null;
                        }
                        h = jq.css({'min-height': ''}).height(); // use jQuery's height() to get hidden element values
                    } else {
                        h = jq.height(); // use jQuery's height() to get hidden element values
                    }
                    return h;
                }).sort(function(a, b) {
                    return b - a;
                });
                if ($.browser.msie6) {
                    containers.each(function() {
                        this.minHeight = heights[0] + 'px';
                        this.style.setExpression('behaviour', 'this.style.height = this.minHeight ? this.minHeight : "1px"'); // using an expression to not make print styles useless
                    });
                } else {
                    containers.css({'min-height': heights[0] + 'px'});
                }
            };
            // call once for initialization
            _setAutoHeight();
            // trigger auto height adjustment if needed
            var cachedWidth = container.offsetWidth;
            var cachedHeight = container.offsetHeight;
            var watchFontSize = $('#tabs-watch-font-size').get(0) || $('<span id="tabs-watch-font-size">M</span>').css({display: 'block', position: 'absolute', visibility: 'hidden'}).appendTo(document.body).get(0);
            var cachedFontSize = watchFontSize.offsetHeight;
            setInterval(function() {
                var currentWidth = container.offsetWidth;
                var currentHeight = container.offsetHeight;
                var currentFontSize = watchFontSize.offsetHeight;
                if (currentHeight > cachedHeight || currentWidth != cachedWidth || currentFontSize != cachedFontSize) {
                    _setAutoHeight((currentWidth > cachedWidth || currentFontSize < cachedFontSize)); // if heights gets smaller reset min-height
                    cachedWidth = currentWidth;
                    cachedHeight = currentHeight;
                    cachedFontSize = currentFontSize;
                }
            }, 50);
        }

        // setup animations
        var showAnim = {}, hideAnim = {}, showSpeed = settings.fxShowSpeed || settings.fxSpeed, hideSpeed = settings.fxHideSpeed || settings.fxSpeed;
        if (settings.fxSlide || settings.fxFade) {
            if (settings.fxSlide) {
                showAnim['height'] = 'show';
                hideAnim['height'] = 'hide';
            }
            if (settings.fxFade) {
                showAnim['opacity'] = 'show';
                hideAnim['opacity'] = 'hide';
            }
        } else {
            if (settings.fxShow) {
                showAnim = settings.fxShow;
            } else { // use some kind of animation to prevent browser scrolling to the tab
                showAnim['min-width'] = 0; // avoid opacity, causes flicker in Firefox
                showSpeed = 1; // as little as 1 is sufficient
            }
            if (settings.fxHide) {
                hideAnim = settings.fxHide;
            } else { // use some kind of animation to prevent browser scrolling to the tab
                hideAnim['min-width'] = 0; // avoid opacity, causes flicker in Firefox
                hideSpeed = 1; // as little as 1 is sufficient
            }
        }

        // callbacks
        var onClick = settings.onClick, onHide = settings.onHide, onShow = settings.onShow;

        // attach activateTab event, required for activating a tab programmatically
        tabs.bind('triggerTab', function() {

            // if the tab is already selected or disabled or animation is still running stop here
            var li = $(this).parents('li:eq(0)');
            if (container.locked || li.is('.' + settings.selectedClass) || li.is('.' + settings.disabledClass)) {
                return false;
            }

            var hash = this.hash;

            if ($.browser.msie) {

                $(this).trigger('click');
                if (settings.bookmarkable) {
                    $.ajaxHistory.update(hash);
                    location.hash = hash.replace('#', '');
                }

            } else if ($.browser.safari) {

                // Simply setting location.hash puts Safari into the eternal load state... ugh! Submit a form instead.
                var tempForm = $('<form action="' + hash + '"><div><input type="submit" value="h" /></div></form>').get(0); // no need to append it to the body
                tempForm.submit(); // does not trigger the form's submit event...
                $(this).trigger('click'); // ...thus do stuff here
                if (settings.bookmarkable) {
                    $.ajaxHistory.update(hash);
                }

            } else {

                if (settings.bookmarkable) {
                    location.hash = hash.replace('#', '');
                } else {
                    $(this).trigger('click');
                }

            }

        });

        // attach disable event, required for disabling a tab
        tabs.bind('disableTab', function() {
            var li = $(this).parents('li:eq(0)');
            if ($.browser.safari) { /* fix opacity of tab after disabling in Safari... */
                li.animate({ opacity: 0 }, 1, function() {
                   li.css({opacity: ''});
                });
            }
            li.addClass(settings.disabledClass);

        });

        // disabled from settings
        if (settings.disabled && settings.disabled.length) {
            for (var i = 0, k = settings.disabled.length; i < k; i++) {
                tabs.eq(--settings.disabled[i]).trigger('disableTab').end();
            }
        };

        // attach enable event, required for reenabling a tab
        tabs.bind('enableTab', function() {
            var li = $(this).parents('li:eq(0)');
            li.removeClass(settings.disabledClass);
            if ($.browser.safari) { /* fix disappearing tab after enabling in Safari... */
                li.animate({ opacity: 1 }, 1, function() {
                    li.css({opacity: ''});
                });
            }
        });

        // attach click event
        tabs.bind('click', function(e) {

            var trueClick = e.clientX; // add to history only if true click occured, not a triggered click
            var clicked = this, li = $(this).parents('li:eq(0)'), toShow = $(this.hash), toHide = containers.filter(':visible');

            // if animation is still running, tab is selected or disabled or onClick callback returns false stop here
            // check if onClick returns false last so that it is not executed for a disabled tab
            if (container['locked'] || li.is('.' + settings.selectedClass) || li.is('.' + settings.disabledClass) || typeof onClick == 'function' && onClick(this, toShow[0], toHide[0]) === false) {
                this.blur();
                return false;
            }

            container['locked'] = true;

            // show new tab
            if (toShow.size()) {

                // prevent scrollbar scrolling to 0 and than back in IE7, happens only if bookmarking/history is enabled
                if ($.browser.msie && settings.bookmarkable) {
                    var toShowId = this.hash.replace('#', '');
                    toShow.attr('id', '');
                    setTimeout(function() {
                        toShow.attr('id', toShowId); // restore id
                    }, 0);
                }

                var resetCSS = { display: '', overflow: '', height: '' };
                if (!$.browser.msie) { // not in IE to prevent ClearType font issue
                    resetCSS['opacity'] = '';
                }
                
                // switch tab, animation prevents browser scrolling to the fragment
                function switchTab() {
                    if (settings.bookmarkable && trueClick) { // add to history only if true click occured, not a triggered click
                        $.ajaxHistory.update(clicked.hash);
                    }
                    toHide.animate(hideAnim, hideSpeed, function() { //
                        $(clicked).parents('li:eq(0)').addClass(settings.selectedClass).siblings().removeClass(settings.selectedClass);
                        toHide.addClass(settings.hideClass).css(resetCSS); // maintain flexible height and accessibility in print etc.                        
                        if (typeof onHide == 'function') {
                            onHide(clicked, toShow[0], toHide[0]);
                        }
                        if (!(settings.fxSlide || settings.fxFade || settings.fxShow)) {
                            toShow.css('display', 'block'); // prevent occasionally occuring flicker in Firefox cause by gap between showing and hiding the tab containers
                        }
                        toShow.animate(showAnim, showSpeed, function() {
                            toShow.removeClass(settings.hideClass).css(resetCSS); // maintain flexible height and accessibility in print etc.
                            if ($.browser.msie) {
                                toHide[0].style.filter = '';
                                toShow[0].style.filter = '';
                            }
                            if (typeof onShow == 'function') {
                                onShow(clicked, toShow[0], toHide[0]);
                            }
                            container['locked'] = null;
                        });
                    });
                }

                if (!settings.remote) {
                    switchTab();
                } else {
                    $(clicked).trigger('loadRemoteTab', [switchTab]);
                }

            } else {
                alert('There is no such container.');
            }

            // Set scrollbar to saved position - need to use timeout with 0 to prevent browser scroll to target of hash
            var scrollX = window.pageXOffset || document.documentElement && document.documentElement.scrollLeft || document.body.scrollLeft || 0;
            var scrollY = window.pageYOffset || document.documentElement && document.documentElement.scrollTop || document.body.scrollTop || 0;
            setTimeout(function() {
                window.scrollTo(scrollX, scrollY);
            }, 0);

            this.blur(); // prevent IE from keeping other link focussed when using the back button

            return settings.bookmarkable && !!trueClick; // convert undefined to Boolean for IE

        });

        // enable history support if bookmarking and history is turned on
        if (settings.bookmarkable) {
            $.ajaxHistory.initialize(function() {
                tabs.eq(settings.initial).trigger('click').end();
            });
        }

    });

};

/**
 * Activate a tab programmatically with the given position (no zero-based index)
 * or its id, e.g. the URL's fragment identifier/hash representing a tab, as if the tab
 * itself were clicked.
 *
 * @example $('#container').triggerTab(2);
 * @desc Activate the second tab of the tab interface contained in <div id="container">.
 * @example $('#container').triggerTab(1);
 * @desc Activate the first tab of the tab interface contained in <div id="container">.
 * @example $('#container').triggerTab();
 * @desc Activate the first tab of the tab interface contained in <div id="container">.
 * @example $('#container').triggerTab('fragment-2');
 * @desc Activate a tab via its URL fragment identifier representation.
 *
 * @param String|Number tab Either a string that matches the id of the tab (the URL's
 *                          fragment identifier/hash representing a tab) or an integer
 *                          specifying the position of the tab (no zero-based index) to
 *                          be activated. If this parameter is omitted, the first tab
 *                          will be activated.
 * @type jQuery
 *
 * @name triggerTab
 * @cat Plugins/Tabs
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Disable a tab, so that clicking it has no effect.
 *
 * @example $('#container').disableTab(2);
 * @desc Disable the second tab of the tab interface contained in <div id="container">.
 *
 * @param String|Number tab Either a string that matches the id of the tab (the URL's
 *                          fragment identifier/hash representing a tab) or an integer
 *                          specifying the position of the tab (no zero-based index) to
 *                          be disabled. If this parameter is omitted, the first tab
 *                          will be disabled.
 * @type jQuery
 *
 * @name disableTab
 * @cat Plugins/Tabs
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Enable a tab that has been disabled.
 *
 * @example $('#container').enableTab(2);
 * @desc Enable the second tab of the tab interface contained in <div id="container">.
 *
 * @param String|Number tab Either a string that matches the id of the tab (the URL's
 *                          fragment identifier/hash representing a tab) or an integer
 *                          specifying the position of the tab (no zero-based index) to
 *                          be enabled. If this parameter is omitted, the first tab
 *                          will be enabled.
 * @type jQuery
 *
 * @name enableTab
 * @cat Plugins/Tabs
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

var tabEvents = ['triggerTab', 'disableTab', 'enableTab'];
for (var i = 0; i < tabEvents.length; i++) {
    $.fn[tabEvents[i]] = (function(tabEvent) {
        return function(tab) {
            return this.each(function() {
                var nav = $('ul.tabs-nav' , this);
                nav = nav.size() && nav || $('>ul:eq(0)', this); // fallback to default structure
                var a;
                if (!tab || typeof tab == 'number') {
                    a = $('li a', nav).eq((tab && tab > 0 && tab - 1 || 0)); // fall back to 0
                } else if (typeof tab == 'string') {
                    a = $('li a[@href$="#' + tab + '"]', nav);
                }
                a.trigger(tabEvent);
            });
        };
    })(tabEvents[i]);
}

/**
 * Get the position of the currently selected tab (no zero-based index).
 *
 * @example $('#container').activeTab();
 * @desc Get the position of the currently selected tab of an interface
 * contained in <div id="container">.
 *
 * @type Number
 *
 * @name activeTab
 * @cat Plugins/Tabs
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

$.fn.activeTab = function() {
    var selectedTabs = [];
    this.each(function() {
        var nav = $('ul.tabs-nav' , this);
        nav = nav.size() && nav || $('>ul:eq(0)', this); //fallback to default structure
        var lis = $('li', nav);
        selectedTabs.push(lis.index( lis.filter('.tabs-selected')[0] ) + 1);
    });
    return selectedTabs[0];
};

})(jQuery);/*
 * jQuery UI @VERSION
 *
 * Copyright (c) 2008 Paul Bakaus (ui.jquery.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
;(function($) {

/** jQuery core modifications and additions **/

var _remove = $.fn.remove;
$.fn.remove = function() {
	$("*", this).add(this).triggerHandler("remove");
	return _remove.apply(this, arguments );
};

function isVisible(element) {
	function checkStyles(element) {
		var style = element.style;
		return (style.display != 'none' && style.visibility != 'hidden');
	}
	
	var visible = checkStyles(element);
	
	(visible && $.each($.dir(element, 'parentNode'), function() {
		return (visible = checkStyles(this));
	}));
	
	return visible;
}

$.extend($.expr[':'], {
	data: function(a, i, m) {
		return $.data(a, m[3]);
	},
	
	// TODO: add support for object, area
	tabbable: function(a, i, m) {
		var nodeName = a.nodeName.toLowerCase();
		
		return (
			// in tab order
			a.tabIndex >= 0 &&
			
			( // filter node types that participate in the tab order
				
				// anchor tag
				('a' == nodeName && a.href) ||
				
				// enabled form element
				(/input|select|textarea|button/.test(nodeName) &&
					'hidden' != a.type && !a.disabled)
			) &&
			
			// visible on page
			isVisible(a)
		);
	}
});

$.keyCode = {
	BACKSPACE: 8,
	CAPS_LOCK: 20,
	COMMA: 188,
	CONTROL: 17,
	DELETE: 46,
	DOWN: 40,
	END: 35,
	ENTER: 13,
	ESCAPE: 27,
	HOME: 36,
	INSERT: 45,
	LEFT: 37,
	NUMPAD_ADD: 107,
	NUMPAD_DECIMAL: 110,
	NUMPAD_DIVIDE: 111,
	NUMPAD_ENTER: 108,
	NUMPAD_MULTIPLY: 106,
	NUMPAD_SUBTRACT: 109,
	PAGE_DOWN: 34,
	PAGE_UP: 33,
	PERIOD: 190,
	RIGHT: 39,
	SHIFT: 16,
	SPACE: 32,
	TAB: 9,
	UP: 38
};

// $.widget is a factory to create jQuery plugins
// taking some boilerplate code out of the plugin code
// created by Scott GonzÃ¡lez and JÃ¶rn Zaefferer
function getter(namespace, plugin, method, args) {
	function getMethods(type) {
		var methods = $[namespace][plugin][type] || [];
		return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods);
	}
	
	var methods = getMethods('getter');
	if (args.length == 1 && typeof args[0] == 'string') {
		methods = methods.concat(getMethods('getterSetter'));
	}
	return ($.inArray(method, methods) != -1);
}

$.widget = function(name, prototype) {
	var namespace = name.split(".")[0];
	name = name.split(".")[1];
	
	// create plugin method
	$.fn[name] = function(options) {
		var isMethodCall = (typeof options == 'string'),
			args = Array.prototype.slice.call(arguments, 1);
		
		// prevent calls to internal methods
		if (isMethodCall && options.substring(0, 1) == '_') {
			return this;
		}
		
		// handle getter methods
		if (isMethodCall && getter(namespace, name, options, args)) {
			var instance = $.data(this[0], name);
			return (instance ? instance[options].apply(instance, args)
				: undefined);
		}
		
		// handle initialization and non-getter methods
		return this.each(function() {
			var instance = $.data(this, name);
			
			// constructor
			(!instance && !isMethodCall &&
				$.data(this, name, new $[namespace][name](this, options)));
			
			// method call
			(instance && isMethodCall && $.isFunction(instance[options]) &&
				instance[options].apply(instance, args));
		});
	};
	
	// create widget constructor
	$[namespace][name] = function(element, options) {
		var self = this;
		
		this.widgetName = name;
		this.widgetEventPrefix = $[namespace][name].eventPrefix || name;
		this.widgetBaseClass = namespace + '-' + name;
		
		this.options = $.extend({},
			$.widget.defaults,
			$[namespace][name].defaults,
			$.metadata && $.metadata.get(element)[name],
			options);
		
		this.element = $(element)
			.bind('setData.' + name, function(e, key, value) {
				return self._setData(key, value);
			})
			.bind('getData.' + name, function(e, key) {
				return self._getData(key);
			})
			.bind('remove', function() {
				return self.destroy();
			});
		
		this._init();
	};
	
	// add widget prototype
	$[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);
	
	// TODO: merge getter and getterSetter properties from widget prototype
	// and plugin prototype
	$[namespace][name].getterSetter = 'option';
};

$.widget.prototype = {
	_init: function() {},
	destroy: function() {
		this.element.removeData(this.widgetName);
	},
	
	option: function(key, value) {
		var options = key,
			self = this;
		
		if (typeof key == "string") {
			if (value === undefined) {
				return this._getData(key);
			}
			options = {};
			options[key] = value;
		}
		
		$.each(options, function(key, value) {
			self._setData(key, value);
		});
	},
	_getData: function(key) {
		return this.options[key];
	},
	_setData: function(key, value) {
		this.options[key] = value;
		
		if (key == 'disabled') {
			this.element[value ? 'addClass' : 'removeClass'](
				this.widgetBaseClass + '-disabled');
		}
	},
	
	enable: function() {
		this._setData('disabled', false);
	},
	disable: function() {
		this._setData('disabled', true);
	},
	
	_trigger: function(type, e, data) {
		var eventName = (type == this.widgetEventPrefix
			? type : this.widgetEventPrefix + type);
		e = e  || $.event.fix({ type: eventName, target: this.element[0] });
		return this.element.triggerHandler(eventName, [e, data], this.options[type]);
	}
};

$.widget.defaults = {
	disabled: false
};


/** jQuery UI core **/

$.ui = {
	plugin: {
		add: function(module, option, set) {
			var proto = $.ui[module].prototype;
			for(var i in set) {
				proto.plugins[i] = proto.plugins[i] || [];
				proto.plugins[i].push([option, set[i]]);
			}
		},
		call: function(instance, name, args) {
			var set = instance.plugins[name];
			if(!set) { return; }
			
			for (var i = 0; i < set.length; i++) {
				if (instance.options[set[i][0]]) {
					set[i][1].apply(instance.element, args);
				}
			}
		}	
	},
	cssCache: {},
	css: function(name) {
		if ($.ui.cssCache[name]) { return $.ui.cssCache[name]; }
		var tmp = $('<div class="ui-gen">').addClass(name).css({position:'absolute', top:'-5000px', left:'-5000px', display:'block'}).appendTo('body');
		
		//if (!$.browser.safari)
			//tmp.appendTo('body'); 
		
		//Opera and Safari set width and height to 0px instead of auto
		//Safari returns rgba(0,0,0,0) when bgcolor is not set
		$.ui.cssCache[name] = !!(
			(!(/auto|default/).test(tmp.css('cursor')) || (/^[1-9]/).test(tmp.css('height')) || (/^[1-9]/).test(tmp.css('width')) || 
			!(/none/).test(tmp.css('backgroundImage')) || !(/transparent|rgba\(0, 0, 0, 0\)/).test(tmp.css('backgroundColor')))
		);
		try { $('body').get(0).removeChild(tmp.get(0));	} catch(e){}
		return $.ui.cssCache[name];
	},
	disableSelection: function(el) {
		return $(el)
			.attr('unselectable', 'on')
			.css('MozUserSelect', 'none')
			.bind('selectstart.ui', function() { return false; });
	},
	enableSelection: function(el) {
		return $(el)
			.attr('unselectable', 'off')
			.css('MozUserSelect', '')
			.unbind('selectstart.ui');
	},
	hasScroll: function(e, a) {
		
		//If overflow is hidden, the element might have extra content, but the user wants to hide it
		if ($(e).css('overflow') == 'hidden') { return false; }
		
		var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop',
			has = false;
		
		if (e[scroll] > 0) { return true; }
		
		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		e[scroll] = 1;
		has = (e[scroll] > 0);
		e[scroll] = 0;
		return has;
	}
};


/** Mouse Interaction Plugin **/

$.ui.mouse = {
	_mouseInit: function() {
		var self = this;
	
		this.element.bind('mousedown.'+this.widgetName, function(e) {
			return self._mouseDown(e);
		});
		
		// Prevent text selection in IE
		if ($.browser.msie) {
			this._mouseUnselectable = this.element.attr('unselectable');
			this.element.attr('unselectable', 'on');
		}
		
		this.started = false;
	},
	
	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.unbind('.'+this.widgetName);
		
		// Restore text selection in IE
		($.browser.msie
			&& this.element.attr('unselectable', this._mouseUnselectable));
	},
	
	_mouseDown: function(e) {
		// we may have missed mouseup (out of window)
		(this._mouseStarted && this._mouseUp(e));
		
		this._mouseDownEvent = e;
		
		var self = this,
			btnIsLeft = (e.which == 1),
			elIsCancel = (typeof this.options.cancel == "string" ? $(e.target).parents().add(e.target).filter(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this._mouseCapture(e)) {
			return true;
		}
		
		this.mouseDelayMet = !this.options.delay;
		if (!this.mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				self.mouseDelayMet = true;
			}, this.options.delay);
		}
		
		if (this._mouseDistanceMet(e) && this._mouseDelayMet(e)) {
			this._mouseStarted = (this._mouseStart(e) !== false);
			if (!this._mouseStarted) {
				e.preventDefault();
				return true;
			}
		}
		
		// these delegates are required to keep context
		this._mouseMoveDelegate = function(e) {
			return self._mouseMove(e);
		};
		this._mouseUpDelegate = function(e) {
			return self._mouseUp(e);
		};
		$(document)
			.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);
		
		return false;
	},
	
	_mouseMove: function(e) {
		// IE mouseup check - mouseup happened when mouse was out of window
		if ($.browser.msie && !e.button) {
			return this._mouseUp(e);
		}
		
		if (this._mouseStarted) {
			this._mouseDrag(e);
			return false;
		}
		
		if (this._mouseDistanceMet(e) && this._mouseDelayMet(e)) {
			this._mouseStarted =
				(this._mouseStart(this._mouseDownEvent, e) !== false);
			(this._mouseStarted ? this._mouseDrag(e) : this._mouseUp(e));
		}
		
		return !this._mouseStarted;
	},
	
	_mouseUp: function(e) {
		$(document)
			.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);
		
		if (this._mouseStarted) {
			this._mouseStarted = false;
			this._mouseStop(e);
		}
		
		return false;
	},
	
	_mouseDistanceMet: function(e) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - e.pageX),
				Math.abs(this._mouseDownEvent.pageY - e.pageY)
			) >= this.options.distance
		);
	},
	
	_mouseDelayMet: function(e) {
		return this.mouseDelayMet;
	},
	
	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function(e) {},
	_mouseDrag: function(e) {},
	_mouseStop: function(e) {},
	_mouseCapture: function(e) { return true; }
};

$.ui.mouse.defaults = {
	cancel: null,
	distance: 1,
	delay: 0
};

})(jQuery);
/*
 * jQuery UI Sortable @VERSION
 *
 * Copyright (c) 2008 Paul Bakaus
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 * 
 * http://docs.jquery.com/UI/Sortables
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

function contains(a, b) { 
    var safari2 = $.browser.safari && $.browser.version < 522; 
    if (a.contains && !safari2) { 
        return a.contains(b); 
    } 
    if (a.compareDocumentPosition) 
        return !!(a.compareDocumentPosition(b) & 16); 
    while (b = b.parentNode) 
          if (b == a) return true; 
    return false; 
};

$.widget("ui.sortable", $.extend({}, $.ui.mouse, {
	_init: function() {

		var o = this.options;
		this.containerCache = {};
		this.element.addClass("ui-sortable");
	
		//Get the items
		this.refresh();

		//Let's determine if the items are floating
		this.floating = this.items.length ? (/left|right/).test(this.items[0].item.css('float')) : false;
		
		//Let's determine the parent's offset
		this.offset = this.element.offset();

		//Initialize mouse events for interaction
		this._mouseInit();
		
	},
	plugins: {},
	ui: function(inst) {
		return {
			helper: (inst || this)["helper"],
			placeholder: (inst || this)["placeholder"] || $([]),
			position: (inst || this)["position"],
			absolutePosition: (inst || this)["positionAbs"],
			options: this.options,
			element: this.element,
			item: (inst || this)["currentItem"],
			sender: inst ? inst.element : null
		};		
	},
	
	_propagate: function(n,e,inst, noPropagation) {
		$.ui.plugin.call(this, n, [e, this.ui(inst)]);
		if(!noPropagation) this.element.triggerHandler(n == "sort" ? n : "sort"+n, [e, this.ui(inst)], this.options[n]);
	},
	
	serialize: function(o) {

		var items = this._getItemsAsjQuery(o && o.connected);
		var str = []; o = o || {};
		
		$(items).each(function() {
			var res = ($(this.item || this).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/));
			if(res) str.push((o.key || res[1]+'[]')+'='+(o.key && o.expression ? res[1] : res[2]));
		});
		
		return str.join('&');
		
	},
	
	toArray: function(o) {
		
		var items = this._getItemsAsjQuery(o && o.connected);
		var ret = [];

		items.each(function() { ret.push($(this).attr(o.attr || 'id')); });
		return ret;
		
	},
	
	/* Be careful with the following core functions */
	_intersectsWith: function(item) {
		var x1 = this.positionAbs.left, x2 = x1 + this.helperProportions.width,
		y1 = this.positionAbs.top, y2 = y1 + this.helperProportions.height;
		var l = item.left, r = l + item.width, 
		t = item.top, b = t + item.height;
		
		var dyClick = this.offset.click.top, dxClick = this.offset.click.left;
		var isOverElement = (y1 + dyClick) > t && (y1 + dyClick) < b && (x1 + dxClick) > l && (x1 + dxClick) < r;
		
		if(this.options.tolerance == "pointer" || this.options.forcePointerForContainers || (this.options.tolerance == "guess" && this.helperProportions[this.floating ? 'width' : 'height'] > item[this.floating ? 'width' : 'height'])) {
			return isOverElement;
		} else {
		
			return (l < x1 + (this.helperProportions.width / 2) // Right Half
				&& x2 - (this.helperProportions.width / 2) < r // Left Half
				&& t < y1 + (this.helperProportions.height / 2) // Bottom Half
				&& y2 - (this.helperProportions.height / 2) < b ); // Top Half
		
		}
	},
	
	_intersectsWithEdge: function(item) {	
		var x1 = this.positionAbs.left, x2 = x1 + this.helperProportions.width,
			y1 = this.positionAbs.top, y2 = y1 + this.helperProportions.height;
		
		var l = item.left, r = l + item.width, 
			t = item.top, b = t + item.height;
		
		var dyClick = this.offset.click.top, dxClick = this.offset.click.left;
		var isOverElement = (y1 + dyClick) > t && (y1 + dyClick) < b && (x1 + dxClick) > l && (x1 + dxClick) < r;
		
		if(this.options.tolerance == "pointer" || (this.options.tolerance == "guess" && this.helperProportions[this.floating ? 'width' : 'height'] > item[this.floating ? 'width' : 'height'])) {
			if(!isOverElement) return false;

			if(this.floating) {
				if ((x1 + dxClick) > l && (x1 + dxClick) < l + item.width/2) return 2;
				if ((x1 + dxClick) > l + item.width/2 && (x1 + dxClick) < r) return 1;
			} else {
				var height = item.height;
				var direction = y1 - this.updateOriginalPosition.top < 0 ? 2 : 1; // 2 = up
				
				if (direction == 1 && (y1 + dyClick) < t + height/2) { return 2; } // up
				else if (direction == 2 && (y1 + dyClick) > t + height/2) { return 1; } // down
			}

		} else {
			if (!(l < x1 + (this.helperProportions.width / 2) // Right Half
				&& x2 - (this.helperProportions.width / 2) < r // Left Half
				&& t < y1 + (this.helperProportions.height / 2) // Bottom Half
				&& y2 - (this.helperProportions.height / 2) < b )) return false; // Top Half
			
			if(this.floating) {
				if(x2 > l && x1 < l) return 2; //Crosses left edge
				if(x1 < r && x2 > r) return 1; //Crosses right edge
			} else {
				if(y2 > t && y1 < t) return 1; //Crosses top edge
				if(y1 < b && y2 > b) return 2; //Crosses bottom edge
			}
		}
		
		return false;
		
	},
	
	refresh: function() {
		this._refreshItems();
		this.refreshPositions();
	},
	
	_getItemsAsjQuery: function(connected) {
		
		var self = this;
		var items = [];
		var queries = [];
	
		if(this.options.connectWith && connected) {
			for (var i = this.options.connectWith.length - 1; i >= 0; i--){
				var cur = $(this.options.connectWith[i]);
				for (var j = cur.length - 1; j >= 0; j--){
					var inst = $.data(cur[j], 'sortable');
					if(inst && inst != this && !inst.options.disabled) {
						queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper"), inst]);
					}
				};
			};
		}
		
		queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper"), this]);

		for (var i = queries.length - 1; i >= 0; i--){
			queries[i][0].each(function() {
				items.push(this);
			});
		};
		
		return $(items);
		
	},
	
	_removeCurrentsFromItems: function() {
			
		var list = this.currentItem.find(":data(sortable-item)");	
	
		for (var i=0; i < this.items.length; i++) {
			
			for (var j=0; j < list.length; j++) {
				if(list[j] == this.items[i].item[0])
					this.items.splice(i,1);
			};
		
		};
		
	},
	
	_refreshItems: function() {
		
		this.items = [];
		this.containers = [this];
		var items = this.items;
		var self = this;
		var queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element), this]];
	
		if(this.options.connectWith) {
			for (var i = this.options.connectWith.length - 1; i >= 0; i--){
				var cur = $(this.options.connectWith[i]);
				for (var j = cur.length - 1; j >= 0; j--){
					var inst = $.data(cur[j], 'sortable');
					if(inst && inst != this && !inst.options.disabled) {
						queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element), inst]);
						this.containers.push(inst);
					}
				};
			};
		}

		for (var i = queries.length - 1; i >= 0; i--){
			queries[i][0].each(function() {
				$.data(this, 'sortable-item', queries[i][1]); // Data for target checking (mouse manager)
				items.push({
					item: $(this),
					instance: queries[i][1],
					width: 0, height: 0,
					left: 0, top: 0
				});
			});
		};

	},
	
	refreshPositions: function(fast) {

		//This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change
		if(this.offsetParent) {
			var po = this.offsetParent.offset();
			this.offset.parent = { top: po.top + this.offsetParentBorders.top, left: po.left + this.offsetParentBorders.left };
		}

		for (var i = this.items.length - 1; i >= 0; i--){		
			
			//We ignore calculating positions of all connected containers when we're not over them
			if(this.items[i].instance != this.currentContainer && this.currentContainer && this.items[i].item[0] != this.currentItem[0])
				continue;
				
			var t = this.options.toleranceElement ? $(this.options.toleranceElement, this.items[i].item) : this.items[i].item;
			
			if(!fast) {
				this.items[i].width = t[0].offsetWidth;
				this.items[i].height = t[0].offsetHeight;
			}
			
			var p = t.offset();
			this.items[i].left = p.left;
			this.items[i].top = p.top;
			
		};

		if(this.options.custom && this.options.custom.refreshContainers) {
			this.options.custom.refreshContainers.call(this);
		} else {
			for (var i = this.containers.length - 1; i >= 0; i--){
				var p =this.containers[i].element.offset();
				this.containers[i].containerCache.left = p.left;
				this.containers[i].containerCache.top = p.top;
				this.containers[i].containerCache.width	= this.containers[i].element.outerWidth();
				this.containers[i].containerCache.height = this.containers[i].element.outerHeight();
			};
		}

	},
	
	destroy: function() {
		this.element
			.removeClass("ui-sortable ui-sortable-disabled")
			.removeData("sortable")
			.unbind(".sortable");
		this._mouseDestroy();
		
		for ( var i = this.items.length - 1; i >= 0; i-- )
			this.items[i].item.removeData("sortable-item");
	},
	
	_createPlaceholder: function(that) {
		
		var self = that || this, o = self.options;

		if(!o.placeholder || o.placeholder.constructor == String) {
			var className = o.placeholder;
			o.placeholder = {
				element: function() {
					var el = $(document.createElement(self.currentItem[0].nodeName)).addClass(className || "ui-sortable-placeholder")[0];

					if(!className) {
						el.style.visibility = "hidden";
						document.body.appendChild(el);
						el.innerHTML = self.currentItem[0].innerHTML;
						document.body.removeChild(el);
					};

					return el;
				},
				update: function(container, p) {
					if(className && !o.forcePlaceholderSize) return;
					if(!p.height()) { p.height(self.currentItem.innerHeight() - parseInt(self.currentItem.css('paddingTop')||0, 10) - parseInt(self.currentItem.css('paddingBottom')||0, 10)); };
					if(!p.width()) { p.width(self.currentItem.innerWidth() - parseInt(self.currentItem.css('paddingLeft')||0, 10) - parseInt(self.currentItem.css('paddingRight')||0, 10)); };
				}
			};
		}
		
		self.placeholder = $(o.placeholder.element.call(self.element, self.currentItem))
		self.currentItem.parent()[0].appendChild(self.placeholder[0]);
		self.placeholder[0].parentNode.insertBefore(self.placeholder[0], self.currentItem[0]);
		o.placeholder.update(self, self.placeholder);
	},
	
	_contactContainers: function(e) {
		for (var i = this.containers.length - 1; i >= 0; i--){

			if(this._intersectsWith(this.containers[i].containerCache)) {
				if(!this.containers[i].containerCache.over) {
					

					if(this.currentContainer != this.containers[i]) {
						
						//When entering a new container, we will find the item with the least distance and append our item near it
						var dist = 10000; var itemWithLeastDistance = null; var base = this.positionAbs[this.containers[i].floating ? 'left' : 'top'];
						for (var j = this.items.length - 1; j >= 0; j--) {
							if(!contains(this.containers[i].element[0], this.items[j].item[0])) continue;
							var cur = this.items[j][this.containers[i].floating ? 'left' : 'top'];
							if(Math.abs(cur - base) < dist) {
								dist = Math.abs(cur - base); itemWithLeastDistance = this.items[j];
							}
						}
						
						if(!itemWithLeastDistance && !this.options.dropOnEmpty) //Check if dropOnEmpty is enabled
							continue;
						
						this.currentContainer = this.containers[i];
						itemWithLeastDistance ? this.options.sortIndicator.call(this, e, itemWithLeastDistance, null, true) : this.options.sortIndicator.call(this, e, null, this.containers[i].element, true);
						this._propagate("change", e); //Call plugins and callbacks
						this.containers[i]._propagate("change", e, this); //Call plugins and callbacks
						
						//Update the placeholder
						this.options.placeholder.update(this.currentContainer, this.placeholder);

					}
					
					this.containers[i]._propagate("over", e, this);
					this.containers[i].containerCache.over = 1;
				}
			} else {
				if(this.containers[i].containerCache.over) {
					this.containers[i]._propagate("out", e, this);
					this.containers[i].containerCache.over = 0;
				}
			}
			
		};			
	},
	
	_mouseCapture: function(e, overrideHandle) {

		if(this.options.disabled || this.options.type == 'static') return false;

		//We have to refresh the items data once first
		this._refreshItems();

		//Find out if the clicked node (or one of its parents) is a actual item in this.items
		var currentItem = null, self = this, nodes = $(e.target).parents().each(function() {	
			if($.data(this, 'sortable-item') == self) {
				currentItem = $(this);
				return false;
			}
		});
		if($.data(e.target, 'sortable-item') == self) currentItem = $(e.target);

		if(!currentItem) return false;
		if(this.options.handle && !overrideHandle) {
			var validHandle = false;
			
			$(this.options.handle, currentItem).find("*").andSelf().each(function() { if(this == e.target) validHandle = true; });
			if(!validHandle) return false;
		}
			
		this.currentItem = currentItem;
		this._removeCurrentsFromItems();
		return true;	
			
	},
	
	createHelper: function(e) {
		
		var o = this.options;
		var helper = typeof o.helper == 'function' ? $(o.helper.apply(this.element[0], [e, this.currentItem])) : (o.helper == "original" ? this.currentItem :  this.currentItem.clone());
		
		if (!helper.parents('body').length)
			$(o.appendTo != 'parent' ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]); //Add the helper to the DOM if that didn't happen already
			
		return helper;

	},
	
	_mouseStart: function(e, overrideHandle, noActivation) {

		var o = this.options;
		this.currentContainer = this;

		//We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture
		this.refreshPositions();

		//Create and append the visible helper	
		this.helper = this.createHelper(e);		

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		this.margins = {																				//Cache the margins
			left: (parseInt(this.currentItem.css("marginLeft"),10) || 0),
			top: (parseInt(this.currentItem.css("marginTop"),10) || 0)
		};		
	
		this.offset = this.currentItem.offset();														//The element's absolute position on the page
		this.offset = {																					//Substract the margins from the element's absolute offset
			top: this.offset.top - this.margins.top,
			left: this.offset.left - this.margins.left
		};
		
		this.offset.click = {																			//Where the click happened, relative to the element
			left: e.pageX - this.offset.left,
			top: e.pageY - this.offset.top
		};
		
		this.offsetParent = this.helper.offsetParent();													//Get the offsetParent and cache its position
		var po = this.offsetParent.offset();			

		this.offsetParentBorders = {
			top: (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
			left: (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
		};
		
		this.offset.parent = {																			//Store its position plus border
			top: po.top + this.offsetParentBorders.top,
			left: po.left + this.offsetParentBorders.left
		};
	
		this.updateOriginalPosition = this.originalPosition = this._generatePosition(e);				//Generate the original position
		this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] };  //Cache the former DOM position
		
		//If o.placeholder is used, create a new element at the given position with the class
		this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() };//Cache the helper size


		if(o.helper == "original") {
			this._storedCSS = { position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left"), clear: this.currentItem.css("clear") };
		} else {
			this.currentItem.hide(); //Hide the original, won't cause anything bad this way
		}

		//Position it absolutely and add a helper class
		this.helper
			.css({ position: 'absolute', clear: 'both' })
			.addClass('ui-sortable-helper');
		
		//Create the placeholder	
		this._createPlaceholder();

		//Call plugins and callbacks
		this._propagate("start", e);
		
		//Recache the helper size
		if(!this._preserveHelperProportions)
			this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() };
		
		if(o.cursorAt) {
			if(o.cursorAt.left != undefined) this.offset.click.left = o.cursorAt.left;
			if(o.cursorAt.right != undefined) this.offset.click.left = this.helperProportions.width - o.cursorAt.right;
			if(o.cursorAt.top != undefined) this.offset.click.top = o.cursorAt.top;
			if(o.cursorAt.bottom != undefined) this.offset.click.top = this.helperProportions.height - o.cursorAt.bottom;
		}

		/*
		 * - Position constraining -
		 * Here we prepare position constraining like grid and containment.
		 */	
		
		if(o.containment) {
			if(o.containment == 'parent') o.containment = this.helper[0].parentNode;
			if(o.containment == 'document' || o.containment == 'window') this.containment = [
				0 - this.offset.parent.left,
				0 - this.offset.parent.top,
				$(o.containment == 'document' ? document : window).width() - this.offset.parent.left - this.helperProportions.width - this.margins.left - (parseInt(this.element.css("marginRight"),10) || 0),
				($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.offset.parent.top - this.helperProportions.height - this.margins.top - (parseInt(this.element.css("marginBottom"),10) || 0)
			];

			if(!(/^(document|window|parent)$/).test(o.containment)) {
				var ce = $(o.containment)[0];
				var co = $(o.containment).offset();
				var over = ($(ce).css("overflow") != 'hidden');
				
				this.containment = [
					co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) - this.offset.parent.left,
					co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) - this.offset.parent.top,
					co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - this.offset.parent.left - this.helperProportions.width - this.margins.left - (parseInt(this.currentItem.css("marginRight"),10) || 0),
					co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - this.offset.parent.top - this.helperProportions.height - this.margins.top - (parseInt(this.currentItem.css("marginBottom"),10) || 0)
				];
			}
		}
		
		//Post 'activate' events to possible containers
		if(!noActivation) {
			 for (var i = this.containers.length - 1; i >= 0; i--) { this.containers[i]._propagate("activate", e, this); }
		}
		
		//Prepare possible droppables
		if($.ui.ddmanager)
			$.ui.ddmanager.current = this;
		
		if ($.ui.ddmanager && !o.dropBehaviour)
			$.ui.ddmanager.prepareOffsets(this, e);

		this.dragging = true;

		this._mouseDrag(e); //Execute the drag once - this causes the helper not to be visible before getting its correct position
		return true;


	},
	
	_convertPositionTo: function(d, pos) {
		if(!pos) pos = this.position;
		var mod = d == "absolute" ? 1 : -1;
		return {
			top: (
				pos.top																	// the calculated relative position
				+ this.offset.parent.top * mod											// The offsetParent's offset without borders (offset + border)
				- (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop) * mod	// The offsetParent's scroll position
				+ this.margins.top * mod												//Add the margin (you don't want the margin counting in intersection methods)
			),
			left: (
				pos.left																// the calculated relative position
				+ this.offset.parent.left * mod											// The offsetParent's offset without borders (offset + border)
				- (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft) * mod	// The offsetParent's scroll position
				+ this.margins.left * mod												//Add the margin (you don't want the margin counting in intersection methods)
			)
		};
	},
	
	_generatePosition: function(e) {
		
		var o = this.options;
		var position = {
			top: (
				e.pageY																	// The absolute mouse position
				- this.offset.click.top													// Click offset (relative to the element)
				- this.offset.parent.top												// The offsetParent's offset without borders (offset + border)
				+ (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop)	// The offsetParent's scroll position, not if the element is fixed
			),
			left: (
				e.pageX																	// The absolute mouse position
				- this.offset.click.left												// Click offset (relative to the element)
				- this.offset.parent.left												// The offsetParent's offset without borders (offset + border)
				+ (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft)	// The offsetParent's scroll position, not if the element is fixed
			)
		};
		
		if(!this.originalPosition) return position;										//If we are not dragging yet, we won't check for options
		
		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */
		if(this.containment) {
			if(position.left < this.containment[0]) position.left = this.containment[0];
			if(position.top < this.containment[1]) position.top = this.containment[1];
			if(position.left > this.containment[2]) position.left = this.containment[2];
			if(position.top > this.containment[3]) position.top = this.containment[3];
		}
		
		if(o.grid) {
			var top = this.originalPosition.top + Math.round((position.top - this.originalPosition.top) / o.grid[1]) * o.grid[1];
			position.top = this.containment ? (!(top < this.containment[1] || top > this.containment[3]) ? top : (!(top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
			
			var left = this.originalPosition.left + Math.round((position.left - this.originalPosition.left) / o.grid[0]) * o.grid[0];
			position.left = this.containment ? (!(left < this.containment[0] || left > this.containment[2]) ? left : (!(left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
		}
		
		return position;
	},
	
	_mouseDrag: function(e) {

		//Compute the helpers position
		this.position = this._generatePosition(e);
		this.positionAbs = this._convertPositionTo("absolute");

		//Call the internal plugins
		$.ui.plugin.call(this, "sort", [e, this.ui()]);
		
		//Regenerate the absolute position used for position checks
		this.positionAbs = this._convertPositionTo("absolute");
		
		//Set the helper's position
		this.helper[0].style.left = this.position.left+'px';
		this.helper[0].style.top = this.position.top+'px';

		//Rearrange
		for (var i = this.items.length - 1; i >= 0; i--) {
			var intersection = this._intersectsWithEdge(this.items[i]);
			if(!intersection) continue;
			
			if(this.items[i].item[0] != this.currentItem[0] //cannot intersect with itself
				&&	this.placeholder[intersection == 1 ? "next" : "prev"]()[0] != this.items[i].item[0] //no useless actions that have been done before
				&&	!contains(this.placeholder[0], this.items[i].item[0]) //no action if the item moved is the parent of the item checked
				&& (this.options.type == 'semi-dynamic' ? !contains(this.element[0], this.items[i].item[0]) : true)
			) {
				
				this.updateOriginalPosition = this._generatePosition(e);
				
				this.direction = intersection == 1 ? "down" : "up";
				this.options.sortIndicator.call(this, e, this.items[i]);
				this._propagate("change", e); //Call plugins and callbacks
				break;
			}
		}
		
		//Post events to containers
		this._contactContainers(e);
		
		//Interconnect with droppables
		if($.ui.ddmanager) $.ui.ddmanager.drag(this, e);

		//Call callbacks
		this.element.triggerHandler("sort", [e, this.ui()], this.options["sort"]);

		return false;
		
	},
	
	_rearrange: function(e, i, a, hardRefresh) {

		a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction == 'down' ? i.item[0] : i.item[0].nextSibling));
		
		//Various things done here to improve the performance:
		// 1. we create a setTimeout, that calls refreshPositions
		// 2. on the instance, we have a counter variable, that get's higher after every append
		// 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
		// 4. this lets only the last addition to the timeout stack through
		this.counter = this.counter ? ++this.counter : 1;
		var self = this, counter = this.counter;

		window.setTimeout(function() {
			if(counter == self.counter) self.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
		},0);

	},
	
	_mouseStop: function(e, noPropagation) {

		//If we are using droppables, inform the manager about the drop
		if ($.ui.ddmanager && !this.options.dropBehaviour)
			$.ui.ddmanager.drop(this, e);
			
		if(this.options.revert) {
			var self = this;
			var cur = self.placeholder.offset();

			$(this.helper).animate({
				left: cur.left - this.offset.parent.left - self.margins.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft),
				top: cur.top - this.offset.parent.top - self.margins.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop)
			}, parseInt(this.options.revert, 10) || 500, function() {
				self._clear(e);
			});
		} else {
			this._clear(e, noPropagation);
		}

		return false;
		
	},
	
	_clear: function(e, noPropagation) {

		//We first have to update the dom position of the actual currentItem
		if(!this._noFinalSort) this.placeholder.before(this.currentItem);
		this._noFinalSort = null;

		if(this.options.helper == "original")
			this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
		else
			this.currentItem.show();

		if(this.domPosition.prev != this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent != this.currentItem.parent()[0]) this._propagate("update", e, null, noPropagation); //Trigger update callback if the DOM position has changed
		if(!contains(this.element[0], this.currentItem[0])) { //Node was moved out of the current element
			this._propagate("remove", e, null, noPropagation);
			for (var i = this.containers.length - 1; i >= 0; i--){
				if(contains(this.containers[i].element[0], this.currentItem[0])) {
					this.containers[i]._propagate("update", e, this, noPropagation);
					this.containers[i]._propagate("receive", e, this, noPropagation);
				}
			};
		};
		
		//Post events to containers
		for (var i = this.containers.length - 1; i >= 0; i--){
			this.containers[i]._propagate("deactivate", e, this, noPropagation);
			if(this.containers[i].containerCache.over) {
				this.containers[i]._propagate("out", e, this);
				this.containers[i].containerCache.over = 0;
			}
		}
		
		this.dragging = false;
		if(this.cancelHelperRemoval) {
			this._propagate("beforeStop", e, null, noPropagation);
			this._propagate("stop", e, null, noPropagation);
			return false;
		}
		
		this._propagate("beforeStop", e, null, noPropagation);
		
		this.placeholder.remove();
		if(this.options.helper != "original") this.helper.remove(); this.helper = null;
		this._propagate("stop", e, null, noPropagation);
		
		return true;
		
	}
}));

$.extend($.ui.sortable, {
	getter: "serialize toArray",
	defaults: {
		helper: "original",
		tolerance: "guess",
		distance: 1,
		delay: 0,
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		cancel: ":input",
		items: '> *',
		zIndex: 1000,
		dropOnEmpty: true,
		appendTo: "parent",
		sortIndicator: $.ui.sortable.prototype._rearrange,
		scope: "default",
		forcePlaceholderSize: false
	}
});

/*
 * Sortable Extensions
 */

$.ui.plugin.add("sortable", "cursor", {
	start: function(e, ui) {
		var t = $('body');
		if (t.css("cursor")) ui.options._cursor = t.css("cursor");
		t.css("cursor", ui.options.cursor);
	},
	beforeStop: function(e, ui) {
		if (ui.options._cursor) $('body').css("cursor", ui.options._cursor);
	}
});

$.ui.plugin.add("sortable", "zIndex", {
	start: function(e, ui) {
		var t = ui.helper;
		if(t.css("zIndex")) ui.options._zIndex = t.css("zIndex");
		t.css('zIndex', ui.options.zIndex);
	},
	beforeStop: function(e, ui) {
		if(ui.options._zIndex) $(ui.helper).css('zIndex', ui.options._zIndex);
	}
});

$.ui.plugin.add("sortable", "opacity", {
	start: function(e, ui) {
		var t = ui.helper;
		if(t.css("opacity")) ui.options._opacity = t.css("opacity");
		t.css('opacity', ui.options.opacity);
	},
	beforeStop: function(e, ui) {
		if(ui.options._opacity) $(ui.helper).css('opacity', ui.options._opacity);
	}
});

$.ui.plugin.add("sortable", "scroll", {
	start: function(e, ui) {
		var o = ui.options;
		var i = $(this).data("sortable");
	
		i.overflowY = function(el) {
			do { if(/auto|scroll/.test(el.css('overflow')) || (/auto|scroll/).test(el.css('overflow-y'))) return el; el = el.parent(); } while (el[0].parentNode);
			return $(document);
		}(i.currentItem);
		i.overflowX = function(el) {
			do { if(/auto|scroll/.test(el.css('overflow')) || (/auto|scroll/).test(el.css('overflow-x'))) return el; el = el.parent(); } while (el[0].parentNode);
			return $(document);
		}(i.currentItem);
		
		if(i.overflowY[0] != document && i.overflowY[0].tagName != 'HTML') i.overflowYOffset = i.overflowY.offset();
		if(i.overflowX[0] != document && i.overflowX[0].tagName != 'HTML') i.overflowXOffset = i.overflowX.offset();
		
	},
	sort: function(e, ui) {
		
		var o = ui.options;
		var i = $(this).data("sortable");
		
		if(i.overflowY[0] != document && i.overflowY[0].tagName != 'HTML') {
			if((i.overflowYOffset.top + i.overflowY[0].offsetHeight) - e.pageY < o.scrollSensitivity)
				i.overflowY[0].scrollTop = i.overflowY[0].scrollTop + o.scrollSpeed;
			if(e.pageY - i.overflowYOffset.top < o.scrollSensitivity)
				i.overflowY[0].scrollTop = i.overflowY[0].scrollTop - o.scrollSpeed;
		} else {
			if(e.pageY - $(document).scrollTop() < o.scrollSensitivity)
				$(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
			if($(window).height() - (e.pageY - $(document).scrollTop()) < o.scrollSensitivity)
				$(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
		}
		
		if(i.overflowX[0] != document && i.overflowX[0].tagName != 'HTML') {
			if((i.overflowXOffset.left + i.overflowX[0].offsetWidth) - e.pageX < o.scrollSensitivity)
				i.overflowX[0].scrollLeft = i.overflowX[0].scrollLeft + o.scrollSpeed;
			if(e.pageX - i.overflowXOffset.left < o.scrollSensitivity)
				i.overflowX[0].scrollLeft = i.overflowX[0].scrollLeft - o.scrollSpeed;
		} else {
			if(e.pageX - $(document).scrollLeft() < o.scrollSensitivity)
				$(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
			if($(window).width() - (e.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
				$(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
		}
		
	}
});

$.ui.plugin.add("sortable", "axis", {
	sort: function(e, ui) {
		
		var i = $(this).data("sortable");
		
		if(ui.options.axis == "y") i.position.left = i.originalPosition.left;
		if(ui.options.axis == "x") i.position.top = i.originalPosition.top;
		
	}
});

})(jQuery);
// This file contains all global methods and functions

var ActicsValidator = {
    IsValidEmail: function(email)
    {
        if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) return true;
        return false;
    },
    IsLessThanOrEqualStringLength: function(strValue, length)
    {
        if(!strValue || length <= 0)
            return true;
            
        return strValue.length <= length;
    }
}
   

/* 
Actics Plugins
*/
jQuery.extend({
    // u : url,
    // dt : datatype
    // d : data
    // e : element to wait on
    // cb : callback    
    actjax: function(u, dt, d, e, cb) {

        var elm = e;
        if (elm != null && elm.length == 1) {
            var pos = elm.position();

            $('<div id="ajaxloader"><div class=\"img\"/></div>')
                .prependTo(elm)
                .css({
                    left: pos.x,
                    top: pos.y,
                    width: elm.width(),
                    height: elm.height()
                })
                .click(function(evt) {
                    evt.stopPropagation();
                    return false;
                })
                .ajaxStart(function() {
                    $(this).show();
                })
                .ajaxStop(function() {
                    $('#ajaxloader').fadeOut('fast').remove();
                })
            //                .ajaxError(function(request, settings) {
            //                    $('#ajaxloader').remove();
            //                    alert('AjaxError [' + settings.status + '] ' + settings.responseText);
            //                }
            //);

            elm.show();
        }

        if (u.indexOf('?') < 0) {
            u += '?';
        }

        u += 'r=' + Math.random().toString();

        if (actics.externalclient) {
            u += "&externalclient=" + actics.externalclient;
        }

        $.ajax({
            url: u,
            type: 'POST',
            dataType: dt,
            data: d,
            success: cb
        });
    },

    validateEmail: function(email) {
        try {
            var regExp = new RegExp('^([0-9a-zA-Z]+[-._+&amp;])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$');
            return (regExp.test(email));
        } catch (ex) { }
        return false;
    },

    openPopup: function(url, name, width, height, scroll) {
        var x = parseInt(screen.width / 2.0 - width / 2.0);
        var y = parseInt(screen.height / 2.0 - height / 2.0);
        var scr = scroll ? 'yes' : 'no';
        var win = window.open(url, name, 'status=no,top=' + y + ',left=' + x + ',scrollbars=' + scr + ',dialog=no,minimizable=no,modal=yes,width=' + width + ',height=' + height + ',resizable=no');
    },

    toggleList: function(moreDiv, showLink, hideLink) {
        if ($(moreDiv).is(':visible')) {
            $(moreDiv).hide();
        } else {
            $(moreDiv).show();
        }
        $(showLink).show();
        $(hideLink).hide();
        return false;
    },

    refresh: function(url, options) {
        if (url == null || url == '') {
            url = document.location.href;
            if (url.indexOf('#') > 0) {
                url = url.substring(0, url.indexOf('#'));
            }
        }
        if (options != null) {
            var args = null;
            $.each(options, function(arg, val) {
                if (args == null) {
                    args = '?';
                } else {
                    args += "&";
                }
                args += arg + "=" + val;
            });
            url += args;
        }
        document.location.href = url;
    }
});

jQuery.fn.extend(
{
    showRequestPopup: function(title, requestType, option) {

        if ($(this).attr('id') != 'requestpopup')
            throw 'Invalid request popup type';

        var valuename = valueManager.getEntityFromURL(valueManager.selectedValue.find('h3 a').attr('href'));

        $(this).find('#title').text(title);
        $(this).find('input[name=option]').attr('value', option);
        $(this).find('input[name=selectedvalue]').attr('value', valuename);
        $(this).find('input[name=requesttype]').attr('value', requestType);
        $(this).find('input[type=checkbox]').attr('checked', false);
        $(this).showLayer();
    },
    showLayer: function() {
        if ($(this).length != 1) return $(this);

        if (!$(this).hasClass('layer')) {
            throw 'element is not classed as a layer';
        }

        if ($('#layeroverlay').length == 0) {
            $('<div id="layeroverlay"></div>').appendTo('#page').css({ opacity: '0.65' });
        }

        $('#layeroverlay').show();

        $("#columnleft").sortable('disable');
        $("#columnright").sortable('disable');

        var layer = $(this);

        if (layer.find('.layerClose').length == 0) {
            $('<div class="layerClose" title="Close layer [Press Esc] "><a href="#"></a></div>').prependTo(layer);

            if (actics.externalclient) {
                layer.css({ top: 120, marginLeft: -parseInt($(this).width() / 2.0) });
            } else {
                layer.css({ marginLeft: -parseInt($(this).width() / 2.0), marginTop: -parseInt($(this).height() / 2.0) });
            }
        }

        layer.find('.layerClose a').click(function() {
            layer.hideLayer();
            $("#columnleft").sortable('enable');
            $("#columnright").sortable('enable');
            return false;
        });

        function keyDown(e) {
            if (e.keyCode == 27) {
                layer.hideLayer();
                $("#columnleft").sortable('enable');
                $("#columnright").sortable('enable');
            }
        }

        $(window).unbind('keydown', keyDown).keydown(keyDown);
        $(document.body).unbind('keydown', keyDown).keydown(keyDown);

        // $('#tooltip').hide();

        layer.show().find('.focus').focus();

        return layer;
    },

    hideLayer: function() {
        $('#layeroverlay').hide();
        $(this).trigger('onHideLayer');
        return $(this).hide();
    },

    iff: function(condition, then, otherwise) {
        if (condition) {
            if (then != null && typeof (then) == 'function') {
                this.fnc = then;
            }
        } else {
            if (otherwise != null && typeof (otherwise) == 'function') {
                this.fnc = otherwise;
            }
        }
        if (this.fnc != null) {
            this.fnc();
        }
        return this;
    },

    sortChildren: function(fnc) {
        var a = $.makeArray($(this).children().clone(true));
        a = a.sort(fnc);

        $(this).empty().append(a);
    },

    requireBind: function(eventName, a, func) {
        var args = a;
        var fnc = func;

        $(this).bind(eventName, function(evt) {
            var passed = true;

            if (!actics.isselfprofile && !actics.isloggedin && passed & args.login) {

                if (actics.externalclient)
                    parent.window.location = actics.partnerloginpage;
                else
                    $('#layerLogin').showLayer();

                passed = false;
            }

            if (!actics.isselfprofile && !actics.isvalid && passed & args.login) {
                alert('You havent verified your email yet');

                passed = false;
            }

            if (!actics.isselfprofile && !actics.ismemberofgroup && passed && args.group) {
                $('#layerJoinGroup').showLayer();

                passed = false;
            }

            if (!actics.isselfprofile && !actics.isproximity && passed && args.proximity) {
                $('#layerProximity').showLayer();

                passed = false;
            }

            if (passed && fnc != null && jQuery.isFunction(fnc)) {
                this.fnc = fnc;
                this.fnc();
            }
            return false;
        });

        return this;
    },

    autoComplete: function(redrawFunction) {
        if (redrawFunction == null) {
            var f = this.data('ac_func');
            if ($.isFunction(f)) {
                f();
            }
            return this;
        }

        if ($.isFunction(redrawFunction)) {
            this.data('ac_func', redrawFunction);

            $(this).keydown(function(e) {
                switch (e.keyCode) {
                    //                    case 13:          
                    //			        case 9:          
                    //                        e.preventDefault();          
                    //				        break;          
                    default:
                        var timeout = $(this).data('ac_timeout');
                        if (timeout) clearTimeout(timeout);
                        var obj = this;
                        obj.fnc = $(this).data('ac_func');
                        timeout = setTimeout(function() { obj.fnc(); }, 400);
                        $(this).data('ac_timeout', timeout);
                        break;
                }
            });
        } else {

        }
        return this;
    }
});

// Global Setup
$(document).ready(function() {

    $.ajaxSetup({
        // url: "/xmlhttp/",
        global: true,
        type: "POST",
        cache: false
    });

    if (actics.externalclient) {
        $('form[name!=aspnetForm]').append('<input type="hidden" name="externalclient" value="' + actics.externalclient + '"/>');
    }

    $('<div id="ajaxBusy">Loading...</div>')
        .ajaxStart(function() { $('#ajaxBusy').show(); })
        .ajaxStop(function() { $('#ajaxBusy').fadeOut('slow'); })
        .ajaxError(function(request, settings) {
            $('#ajaxBusy').hide();
            alert('AjaxError [' + settings.status + '] ' + settings.responseText);
        })
        .appendTo('#page');


    if (typeof actics == 'undefined') {
        throw 'missing actics setup';
    }

    // remove the safari textarea resize
    $('textarea').css('resize', 'none');

    // Form focus box
    $('.formfield :input').focus(function() {
        $(this).parents('.regfield').addClass('active');
    });

    $('.formfield :input').blur(function() {
        $(this).parents('.regfield').removeClass('active');
    });

    // focus on the input's with focus
    $('.formfield .focus').focus();

    // Setup the login
    //$('#userinfo .login').requireBind('click', { login: true });

    //$('#userinfo .join').requireBind('click', { login: true });

    $('.joingroup').requireBind('click', { login: true, group: true });

    $('.leavegroup').requireBind('click', { login: true, group: true }, function() {
        if (!confirm('Are you sure you want to leave group?')) return false;
        var pnl = $(this).parents('.panel');
        $.actjax(actics.api + 'agents/leavegroup',
                'json',
                { groupname: actics.groupname },
                pnl,
                function(data) { $.refresh(); }
        );
        return false;
    });


    $('#layerJoinGroup form').ajaxForm({
        dataType: 'JSON',
        success: function(data) {
            actics.ismemberofgroup = true;
            $('#layerJoinGroup').hideLayer();
            $.refresh();
        }
        //        ,
        //        error : function(data) {
        //            alert(data.responseText);
        //        }    
    });

    // proximity
    $('#layerProximity form').ajaxForm({
        dataType: 'JSON',
        success: function(data) {
            actics.isproximity = true;
            $('#layerProximity').hideLayer();

            if (actics.proximitymessage)
                alert(actics.proximitymessage);
            else
                alert('Done');
        }
    });

    $('#requestpopup form').ajaxForm({
        dataType: 'JSON',
        beforeSubmit: function() {
            var checkedBoxes = $('#requestpopup').find('input[type=checkbox][checked]');

            if (checkedBoxes == null || checkedBoxes == "" || checkedBoxes.length == 0) {
                alert('You haven\'t select the connections that you want to request.');
                return false;
            }
            return true;
        },
        success: function(data) {
            $('#requestpopup').hideLayer();
        }
    });

    // dropdown to change group
    $('#grouplist form select').change(function(v) {

        $('#grouplist form').attr('action', $('#grouplist form').attr('action') + $(this).find(':selected').val())
        $('#grouplist form select').remove();
        $('#grouplist form').submit();
        return false;
    });

    $('.datatable.rowclick tbody tr a').click(function() { $(this).parents('tr').click(); return false; });

    $('.proxylist a').click(function() {
        var cb = $(this).parent('li').find('input[type=checkbox]');
        cb.attr('checked', !cb.attr('checked'));
        return false;
    });

    $('.proxylist input[type=checkbox]').click(function() {
        $(this).parent('li').find('ul input[type=checkbox]').attr('checked', $(this).attr('checked'));
    });


});

var valueManager =
{
    ratingClasses: ['Outstanding', 'Good', 'Neutral', 'Insufficient', 'Unacceptable!'],
    initialized: false,
    manager: null,
    values: null,
    descriptions: null,
    selectedValue: null,
    selectedDescription: null,

    getEntityFromURL: function(str) {
        if (str == null) return null;
        var value = str.split('/');
        value = value.length == 0 ? value[0] : value[value.length - 1];
        value = value.split('=');
        return value.length == 0 ? value[0] : value[value.length - 1];
    },
    
    setSelectedValue: function(valuename, showsuggesionpopup) {
        valueManager.values.find('.value h3 a[title=' + valuename + ']').parent().parent().trigger('mousedown');
       
        if(showsuggesionpopup)
            $('.valueDescription.selected').find('.button.addwish').click();
    },

    init: function() {
        var found = 0;

        this.manager = $('#valueManager');
        if (this.manager == null || this.manager.length != 1) return;
        this.values = valueManager.manager.find('.valueList');
        this.descriptions = valueManager.manager.find('.valueDescriptionList');

        if (this.values.height() > this.descriptions.height()) {
            this.manager.height(this.values.height());
            this.descriptions.height(this.values.height());
        }

        valueManager.values
                .find('.rate')
                    .requireBind('click', { login: true, group: true, proximity: true }, valueManager.rate)
                    .end()
                .find('.value')
                    .each(function(i) {
                        $(this).find('h3 a').click(function(e) { e.preventDefault(); return false; });
                        $(this).mousedown(valueManager.selectValue);

                        var value = valueManager.getEntityFromURL($(this).find('h3 a').attr('href'));
                        var readonly = $(this).hasClass('readonly');

                        if (!actics.isselfprofile && !actics.isgroup && found < 0 && value != '#') {
                            found = i;
                        }

                        if ($(this).find('.bar').length == 1) {
                            var bar = $(this).find('.bar');

                            if (value != '#') {
                                bar.show();
                            }

                            var max = parseInt(bar.width());
                            var rate = parseInt(bar.find('.rating .val').html());
                            bar.find('.rating .info').html(valueManager.getRatingClass(rate));

                            var avr = parseInt(bar.find('.averagebar span').html());
                            var w = avr / 100.0 * (max - 6);
                            if (w < 0) w = 0;
                            bar.find('.averagebar').width(w);

                            var customBar = $('<div class="custombar"></div>').appendTo(bar).css('left', rate / 100.0 * max);

                            if (actics.isselfprofile || actics.isgroup) {

                            } else if (readonly) {
                                customBar.show().animate({ opacity: '0.20' }, 1000, null);
                            }
                            else {
                                customBar
                                    .show()
                                    .mousedown(function(e) {
                                        var offsetX = e.pageX;
                                        var x = parseInt($(this).css('left'));
                                        var elm = $(this);
                                        bar.addClass('drag');

                                        function drag(e) {
                                            bar.addClass('dragged');
                                            var newx = x + e.pageX - offsetX;
                                            if (newx < 0) newx = 0;
                                            if (newx > max) newx = max;
                                            elm.css('left', newx);

                                            var rate = parseInt(newx / max * 100.0);

                                            if (bar.data('rate') == null) {
                                                bar.data('rate', rate);
                                            }

                                            bar.find('.rating .val').html(rate + '%');
                                            bar.find('.rating .info').html(valueManager.getRatingClass(rate));
                                        }

                                        function endDrag(e) {
                                            $(document.body).unbind('mouseup', endDrag);
                                            $(document.body).unbind('mousemove', drag);
                                            bar.removeClass('drag');
                                        }

                                        $(document.body).mousemove(drag);
                                        $(document.body).mouseup(endDrag);
                                    });
                            }
                        };
                    })
                    .iff(found >= 0, function() {
                        $(this).eq(found).trigger('mousedown');
                    }, function() {
                        $(this).eq(0).trigger('mousedown');
                    });


        valueManager.setupLayerValues();
        valueManager.setupLayerActions();
        valueManager.setupLayerWishes();

        valueManager.setStatus();

        valueManager.initialized = true;
    },

    setupLayerValues: function() {
        // Value Layer Setup
        if ($('#layerValues').length != 1) {
            return;
        }

        $('#layerValues .layerBar')
            .find('input[name=cancel]')
                .click(function() {

                    $('#layerValues')
                        .find('.col2a,.col2b,.col2c')
                            .hide()
                            .end();
                    // Nominated Agent should have the same functionalities as normal agent
                    //if (actics.isnominee) {
                    //   valueManager.setValueLayerButtons();
                    //} else {
                    valueManager.setValueLayerButtons({ newvalue: true });
                    //}
                })
                .end()
            .find('input[name=newvalue]')
                .click(function() {
                    // Nominated Agent should have the same functionalities as normal agent
                    //if (actics.isnominee) {
                    //    throw new 'Cant create values for nominations';
                    //}

                    $('.useraddeddef').remove();
                    valueManager.setValueLayerButtons({ usenewvaluewithdefinition: true, cancel: true });

                    $('#layerValues')
                        .find('.col1 .tagcloud .selected')
                            .removeClass('selected')
                            .end()
                        .find('.col2a,.col2b')
                            .hide()
                            .end()
                        .find('.col2c')
                            .show()
                            .find('textarea')
                                .val('')
                                .end()
                            .find('input[type=text]')
                                .val('')
                                .focus()
                                .end();

                    return false;

                    return false;
                })
                .end()
            .find('input[name=newdefinition]')
                .click(function() {
                    // Nominated Agent should have the same functionalities as normal agent
                    //if (actics.isnominee) {
                    //    throw new 'Cant create value definitions for nominations';
                    //}

                    valueManager.setValueLayerButtons({ usevaluewithdefinition: true, cancel: true });

                    var value = $('#layerValues .tagcloud .selected').clone();
                    value.find('span').remove('span');

                    var valueName = value.html();
                    var valueURL = value.attr('href');
                    var valueEntityName = valueManager.getEntityFromURL(valueURL);

                    $('#layerValues')
                        .find('.col2a,.col2c')
                            .hide()
                            .end()
                        .find('.col2b')
                            .find('.selectedValueName')
                                .attr('href', valueEntityName)
                                .html(valueName)
                                .end()
                            .show()
                            .find('textarea')
                                .val('')
                                .focus()
                                .end();

                })
                .end()
            .find('input[name=usevalue]')
                .click(function() {
                    var valueEntityName = valueManager.getEntityFromURL($('#layerValues .tagcloud .selected').attr('href'));
                    var priority = parseInt($('#valueManager .valueList .selected .priority').html());
                    var definitionid = $('#layerValues .valuedefinitionlist .selected').attr('id');

                    if (isNaN(priority)) {
                        alert('unexpected error');
                        return false;
                    }

                    $.actjax(actics.api + 'agents/usevalue',
                        'json',
                        { groupname: actics.groupname,
                            agentname: actics.agentname,
                            valuename: valueEntityName,
                            priority: priority,
                            definitionid: definitionid
                        },
                         $('#valueManager .valueDescriptionList'),
                        function(data) { valueManager.renderValue(data); }
                    );

                    $('#layerValues').hideLayer();
                })
                .end()
            .find('input[name=usevaluewithdefinition]')
                .click(function() {
                    var valueEntityName = valueManager.getEntityFromURL($('#layerValues .tagcloud .selected').attr('href'));
                    var priority = parseInt($('#valueManager .valueList .selected .priority').html());
                    var newdefinition = $('#layerValues .col2b [name=newdescription]').val();

                    if (isNaN(priority)) {
                        alert('unexpected error');
                        return false;
                    }

                    if (newdefinition.length < 10) {
                        alert('Your Value definition is too short');
                        $('#layerValues .col2c [name=newvaluedescription]').focus();
                        return false;
                    }

                    $.actjax(actics.api + 'agents/usevaluewithdefinition',
                        'json',
                        { groupname: actics.groupname,
                            agentname: actics.agentname,
                            valuename: valueEntityName,
                            priority: priority,
                            definition: newdefinition
                        },
                         $('#valueManager .valueDescriptionList'),
                        function(data) { valueManager.renderValue(data); }
                    );

                    $('#layerValues').hideLayer();

                    return false;
                })
                .end()
            .find('input[name=usenewvaluewithdefinition]')
                .click(function() {
                    var valueName = $('#layerValues .col2c [name=newvaluename]').val();
                    var priority = parseInt($('#valueManager .valueList .selected .priority').html());

                    var newdefs = [];

                    var haserror = false;

                    $('#layerValues .col2c [name=newvaluedescription]').each(function(i, item) {
                        newdefs[i] = escape($(item).val());

                        if (newdefs[i].length < 10) {
                            haserror = true;
                            alert('Your Value definition is too short.');
                            $(item).focus();
                            return false;
                        }
                    });

                    if (haserror)
                        return false;

                    if (isNaN(priority)) {
                        alert('unexpected error');
                        return false;
                    }

                    if (valueName.length < 3) {
                        alert('Your Value name is too short');
                        $('#layerValues .col2c [name=newvaluename]').focus();
                        return false;
                    }

                    if (newdefs.length == 0) {
                        alert('Your values doesn\'t have definitions');
                        return false;
                    }


                    $.actjax(actics.api + 'agents/usenewvaluewithdefinition',
                        'json',
                        { groupname: actics.groupname,
                            agentname: actics.agentname,
                            newValuename: valueName,
                            priority: priority,
                            definition: newdefs
                        },
                         $('#valueManager .valueDescriptionList'),
                        function(data) { valueManager.renderValue(data); }
                    );

                    $('#layerValues').hideLayer();

                    return false;
                })
                .end();
    },

    setupLayerActions: function() {
        if ($('#layerActions').length != 1) {
            return;
        }

        // Action Layer Setup
        $('#layerActions form').ajaxForm({
            dataType: 'html',
            beforeSubmit: function() {
                var actionName = $('#layerActions form input[name=actionname]').val();
                var newActionName = $('#layerActions form input[name=newactionname]').val();

                if (!actionName && !newActionName) {
                    alert('Please enter desired action or choose a similar action.');
                    return false;
                }
                $('#layerActions').hideLayer();
            },
            success: function(data) {
                valueManager.selectedDescription.find('.actionlist .emptylist').hide();

                $(data)
                    .prependTo(valueManager.selectedDescription.find('.actionlist'))
                    .find('.delete')
                        .click(valueManager.deleteAction)
                        .end();
            }
        });

        $('#layerActions')
            .find('form [name=newactionname]')
                .focus(function() {
                    $('#layerActions .similarActionList .action').removeClass('selected');
                    $('#layerActions form input[name=actionname]').val('');
                })
                .end()
            .find('form input, form textarea')
                .focus(function() {
                    $('#layerActions .similarActionList').parents('.regfield').removeClass('active');
                })
                .end()
            .find('[name=newactionname]')
                .autoComplete(function() {
                    var str = $(this).val();
                    var list = $('#layerActions .similarActionList').html('');

                    var valueName = valueManager.getEntityFromURL(valueManager.selectedValue.find('h3 a').attr('href'));

                    $.actjax(actics.api + 'actions/loadsimilaractions',
                        'html',
                        { groupname: actics.groupname, text: str, valuename: valueName },
                        $('#layerActions .similarActionList'),
                        function(data) {
                            var list = $('#layerActions .similarActionList').html(data);

                            var actions = list.find('.action');

                            if (actions.length == 0) {
                                list.html('<div style="margin:30px;text-align:center;">No similar actions found</div>');
                            } else {
                                actions
                                    .click(function(e) {
                                        $(this).parents('.actionlist').find('.action').removeClass('selected');
                                        $(this).addClass('selected');
                                        list.parents('.regfield').addClass('active');
                                        e.preventDefault();

                                        $('#layerActions form input[name=actionname]').val(valueManager.getEntityFromURL($(this).find('h3 a').attr('href')));
                                    });
                            }
                        });
                })
                .end();
    },

    setupLayerWishes: function() {
        if ($('#layerWishes').length != 1) {
            return;
        }

        // Wish Layer Setup
        $('#layerWishes form').ajaxForm({
            dataType: 'html',
            success: function(data) {
                $('#layerWishes').hideLayer();
                $('#layerWishes').find('#fileattachment').attr('value', '');

                valueManager.selectedDescription.find('.wishlist .emptylist').hide();

                $(data).prependTo(valueManager.selectedDescription.find('.wishlist'))
                    .find('.delete').click(valueManager.deleteWish).end()
                    .find('.adopt').click(valueManager.adoptWish).end();

                $('#requestpopup').showRequestPopup('Involve your network to give its suggestions', 9, null);
            }
        });

        $('#layerWishes')
            .find('form [name=newactionname]')
                .focus(function() {
                    $('#layerWishes .similarActionList .action').removeClass('selected');
                    $('#layerWishes form input[name=actionname]').val('');
                })
                .end()
            .find('form input, form textarea')
                .focus(function() {
                    $('#layerWishes .similarActionList').parents('.regfield').removeClass('active');
                })
                .end()
            .find('[name=newactionname]')
                .autoComplete(function() {
                    var str = $(this).val();
                    var list = $('#layerActions .similarActionList').html('');

                    var valueName = valueManager.getEntityFromURL(valueManager.selectedValue.find('h3 a').attr('href'));

                    $.actjax(actics.api + 'actions/loadsimilaractions',
                        'html',
                        { groupname: actics.groupname, text: $(this).val(), valuename: valueName },
                        $('#layerWishes .similarActionList'),
                        function(data) {
                            var list = $('#layerWishes .similarActionList').html(data);

                            var actions = list.find('.action');

                            if (actions.length == 0) {
                                list.html('<div style="margin:30px;text-align:center;">No similar actions found</div>');
                            } else {
                                actions
                                    .click(function(e) {
                                        $(this).parents('.actionlist').find('.action').removeClass('selected');
                                        $(this).addClass('selected');
                                        list.parents('.regfield').addClass('active');
                                        e.preventDefault();

                                        $('#layerWishes form input[name=actionname]').val(valueManager.getEntityFromURL($(this).find('h3 a').attr('href')));
                                    });
                            }
                        });
                })
                .end();
    },

    setupValue: function() {
        valueManager.selectedDescription
            .find('.removevalue')
                .click(valueManager.removeValue)
                .end()
            .find('.addaction')
                .click(valueManager.showLayerActions)
                .end()
            .find('.actionlist')
                .find('.action .endorse .btn a')
                    .requireBind('click', { login: true, group: true, proximity: true }, valueManager.endorse)
                    .end()
                .find('.action .delete')
                    .click(valueManager.deleteAction)
                    .end()
                .end()
            .find('.addwish')
                .requireBind('click', { login: true, group: true, proximity: true }, valueManager.showLayerWishes)
                .end()
            .find('.wishlist')
                .find('.action .endorse .btn a')
                    .requireBind('click', { login: true, group: true, proximity: true }, valueManager.endorse)
                    .end()
                .find('.action .delete')
                    .click(valueManager.deleteWish)
                    .end()
                .find('.action .adopt')
                    .click(valueManager.adoptWish)
                    .end()
                .end()
            .find('.valueDefinition .endorse .btn a')
                .requireBind('click', { login: true, group: true, proximity: true }, valueManager.endorseValue)
                .end();
    },
    selectValue: function() {
        // Deselect the old value
        valueManager.values.find('.selected').removeClass('selected');
        valueManager.descriptions.find('.selected').hide().removeClass('selected');

        valueManager.selectedValue = $(this);
        valueManager.selectedValue.addClass('selected');

        var valueName = valueManager.getEntityFromURL(valueManager.selectedValue.find('h3 a').attr('href'));
        valueManager.selectedDescription = valueManager.descriptions.find('h2 .title[href$=' + valueName + ']').parents('.valueDescription');

        if (!valueManager.selectedDescription.data('issetup')) {
            valueManager.setupValue();

            valueManager.selectedDescription.data('issetup', true);
        }



        if (valueManager.getEntityFromURL($(valueManager.selectedDescription).find('h2 .title').attr('href')) == valueName && valueName != '#') {
            $(valueManager.selectedDescription).addClass('selected');
            $(valueManager.selectedDescription).show();
        } else {
            if (valueManager.selectedDescription.length > 0) {
                $(valueManager.selectedDescription).eq(0).addClass('selected');
            }
            $(valueManager.selectedDescription).hide();

            if (valueManager.initialized) {
                valueManager.showValueLayer();
            }
        }

        return false;
    },

    removeValue: function() {
        var value = valueManager.getEntityFromURL(valueManager.selectedValue.find('h3 a').attr('href'));
        var valueName = valueManager.selectedValue.find('h3 a').html();

        if (!confirm('Are you sure you want to remove value "' + valueName + '"')) {
            return false;
        }


        $.actjax(actics.api + 'agents/removeagentvalue',
            'json',
            { groupname: actics.groupname, agentname: actics.agentname, valuename: value },
            $('#valueManager .valueDescriptionList'),
            function(data) {
                var priority = parseInt(valueManager.selectedValue.find('.priority').html());

                valueManager.selectedValue
                    .find('h3 a')
                        .attr('href', '#').html(actics.selectvalue + ' ' + priority)
                        .end()
                    .find('.bar').hide()
                        .end();

                valueManager.selectedDescription
                    .find('h2 .title')
                        .attr('href', '#').html('')
                        .end()
                    .hide();

                valueManager.setStatus();

                valueManager.selectedDescription.find('.action').remove();

                return false;
            }
        );

        return false;
    },

    setValueLayerButtons: function(options) {
        $('#layerValues .layerBar input[type=button]').hide();

        if (options == null) return;

        $('#layerValues .layerBar input')
            .each(function() {
                if (options[$(this).attr('name')]) {
                    switch ($(this).attr('name')) {
                        case 'newvalue':
                        case 'newdefinition':
                        case 'usevalue':
                        case 'usevaluewithdefinition':
                        case 'usenewvaluewithdefinition':
                        case 'cancel':
                            $(this).show();
                            break
                    }
                }
            });
    },

    showValueLayer: function() {
        if ($('#layerValues').length == 0) return;

        valueManager.setValueLayerButtons();

        $('#layerValues')
            .find('.col2a,.col2b,.col2c')
                .hide()
                .end()
            .showLayer();

        $.actjax(actics.api + 'values/loadallvalues', 'html', { groupname: actics.groupname }, $('#layerValues .col1 .tagcloud'), function(data) {

            var tagcloud = $('#layerValues .col1 .tagcloud');

            var max = 0;
            var min = 0;

            tagcloud
                .html(data)
                .find('.value')
                    .find('a')
                        .each(function() {
                            var found = false;
                            var valueName = valueManager.getEntityFromURL($(this).attr('href'));

                            $('#valueManager .valueList .value h3 a').each(function() {
                                if (valueManager.getEntityFromURL($(this).attr('href')) == valueName) {
                                    found = true;
                                }
                            });

                            if (found) {
                                $(this).parents('.value').addClass('using');
                            }
                        })
                        .find('span')
                            .each(function() {
                                var count = parseInt($(this).html());
                                if (count > max) {
                                    max = count;
                                }

                                if (count < min) {
                                    min = count;
                                }
                            })
                        .end()
                    .click(valueManager.selectValueInLayer)
                    .end();
            // Nominated Agent should have the same functionalities as normal agent
            //if (actics.isnominee) {
            //    valueManager.setValueLayerButtons();
            //} else {
            valueManager.setValueLayerButtons({ newvalue: true });
            //}
        });

        return false;
    },

    selectValueInLayer: function() {
        if ($(this).parents('.value').hasClass('using')) {
            alert('Already using value');
            return false;
        }

        var value = $(this).clone();
        value.find('span').remove('span');

        var valueName = value.html();
        var valueURL = value.attr('href');
        var valueEntityName = valueManager.getEntityFromURL(valueURL);

        $('#layerValues')
            .find('.tagcloud .selected')
                .removeClass('selected')
                .end()
            .find('.valueDefinitionList')
                .empty()
                .end()
            .find('.col2a')
                .show()
                .find('.selectedValueName')
                    .html(valueName)
                    .attr('href', valueURL)
                    .end()
                .end()
            .find('.col2b')
                .hide()
                .end()
            .find('.col2c')
                .hide()
                .end();

        $(this).addClass('selected');

        valueManager.setValueLayerButtons();

        $('#layerValues .ylist').html('');

        // Nominated Agent should have the same functionalities as normal agent
        // actics.api + (actics.isnominee ? 'values/loadgroupvaluedefinition' : 'values/loadallvaluedefinitions'),
        $.actjax(actics.api + 'values/loadallvaluedefinitions',
            'html',
            { groupname: actics.groupname, valueName: valueEntityName },
            $('#layerValues .ylist'),
            function(data) {
                $('#layerValues .ylist').html(data);

                $('#layerValues .ylist .valueDefinition')
                    .click(function() {
                        $(this).parent().parent().children().children().removeClass('selected');
                        $(this).addClass('selected');
                    });

                $('#layerValues .ylist .valueDefinition:eq(0)').click();

                // Nominated Agent should have the same functionalities as normal agent
                // if (actics.isnominee) {
                //    valueManager.setValueLayerButtons({ usevalue: true });
                // } else {
                valueManager.setValueLayerButtons({ newvalue: true, newdefinition: true, usevalue: true });
                // }
            });

        return false;
    },

    setStatus: function() {
        var feedback = $('#valueManager .valueList .feedbackstatus');
        var feedbackstatuscount = $('#valueManager .valueList .feedbackstatuscount');

        if (actics.isgroup || actics.isselfprofile || $('#valueManager .valueList .value h3 a:not([href=#])').length == 0) {
            feedback.hide();
            if (actics.isgroup) {
                feedbackstatuscount.hide();
            }
        } else {
            if ($('#valueManager .valueList .readonly').length > 0) {
                feedback.show();
            } else {
                feedback.hide();
            }
        }
    },

    showLayerActions: function() {
        var value = valueManager.selectedValue.find('h3 a').html();
        var valueURL = valueManager.selectedValue.find('h3 a').attr('href');
        var valueName = valueManager.getEntityFromURL(valueURL);

        $('#layerActions')
            .find('h2 a').html(value).attr('href', valueURL).end()
            .find('form [name=valuename]').val(valueName).end()
            .find('form [name=actioname]').val('').end()
            .find('form [name=comment]').val('').end()
            .find('form [name=tags]').val('').end()
            .showLayer()
            .find('[name=newactionname]').val('').autoComplete().focus().end();

        return false;
    },

    showLayerWishes: function() {
        var value = valueManager.selectedValue.find('h3 a').html();
        var valueURL = valueManager.selectedValue.find('h3 a').attr('href');
        var valueName = valueManager.getEntityFromURL(valueURL);

        $('#layerWishes')
            .find('h2 a').html(value).attr('href', valueURL).end()
            .find('form [name=valuename]').val(valueName).end()
            .find('form [name=actioname]').val('').end()
            .find('form [name=comment]').val('').end()
            .find('form [name=tags]').val('').end()
            .showLayer()
            .find('[name=newactionname]').val('').autoComplete().focus().end();

        return false;
    },

    renderValue: function(data) {
        var value = $('#valueManager .valueList .selected');
        var description = $('#valueManager .valueDescriptionList .selected');
        var priority = parseInt(value.find('.priority').html());

        value
            .find('h3 a')
                .html(data.valuename)
                .attr('href', data.entityname)
                .end()
            .find('.bar')
                .show()
                .find('.val')
                    .html(data.ratingvalue)
                    .end()
                .find('.info')
                    .html(valueManager.getRatingClass(data.ratingvalue))
                    .end()
                .end()
            .find('.averagebar')
                .width(data.ratingvalue / 100.0 * value.find('.bar').width() - 3)
                .end();

        description
            .find('.valueDefinition')
                .find('.desc')
                    .html(data.definition)
                    .end()
                .find('.info')
                    .empty()
                    .append($('<span>Created by</span> <a href="">test</a> - <span />'))
                    .find('a')
                        .attr('href', data.ownerurl)
                        .html(data.ownername)
                        .end()
                    .find('span:eq(1)')
                        .html(data.createdtext)
                        .end()
                    .end()
                .end()
            .find('h2 a')
                .html(data.valuename)
                //Annesley: need to go back a directory in the case that we are on a profile
                .attr('href', '../' + data.entityname) 
                .end()
            .find('.actionlist .action')
                .remove()
                .end()
            .find('.actionlist .emptylist')
                .show()
                .end()
            .find('.wishlist .action')
                .remove()
                .end()
            .find('.wishlist .emptylist')
                .show()
                .end()
            .fadeIn('slow');

        $.actjax(actics.api + 'agents/loadagentactionsbyvalue',
            'html',
            { groupname: actics.groupname,
                agentname: actics.agentname,
                valueName: data.entityname
            },
            null,
            function(data) {
                if ($(data).find('.action').length > 0) {
                    description
                        .find('.actionlist')
                            .find('.emptylist')
                                .hide()
                                .end()
                            .find('.action .delete')
                                .click(valueManager.deleteAction)
                                .end();
                }
                description
                    .find('.actionlist')
                        .append($(data).find('.action'))
                        .find('.action .delete').click(valueManager.deleteAction).end();
            });

        $.actjax(actics.api + 'agents/loadagentwishesbyvalue',
            'html',
            { groupname: actics.groupname,
                agentname: actics.agentname,
                valueName: data.entityname
            },
            null,
            function(data) {
                if ($(data).find('.action').length > 0) {
                    description
                        .find('.wishlist')
                            .find('.emptylist')
                                .hide()
                                .end()
                            .find('.action .delete')
                                .click(valueManager.deleteWish)
                                .end()
                            .find('.action .adopt')
                                .click(valueManager.adoptWish)
                                .end();
                }
                description
                    .find('.wishlist')
                        .append($(data).find('.action'))
                        .find('.action .delete').click(valueManager.deleteAction).end();
            });
    },

    getRatingClass: function(value) {
        if (value <= 25) return valueManager.ratingClasses[4];
        if (value < 50) return valueManager.ratingClasses[3];
        if (value == 50) return valueManager.ratingClasses[2];
        if (value <= 75) return valueManager.ratingClasses[1];
        return valueManager.ratingClasses[0];
    },

    rate: function() {
        var val = valueManager.selectedValue;
        var valueName = valueManager.getEntityFromURL(val.find('h3 a').attr('href'));
        var friendlyValueName = val.find('h3 a').attr('title');
        var rate = parseInt(val.find('.rating .val').html());

        if (val.find('.dragged').length != 1) {
            alert('Please move the slider before submitting your rating');
            return false;
        }

        $.actjax(actics.api + 'agents/submitrating',
                'json',
                { groupname: actics.groupname, agentname: actics.agentname, valuename: valueName, rating: rate },
                null,
                function(data) {
                    val.find('.custombar').animate({ opacity: '0.20' }, 1000, null);
                    val.find('.custombar').unbind('mousedown');

                    //                    val.addClass('readonly');
                    //                    var max = parseInt(val.find('.bar').width());
                    //                    if (!isNaN(max)) {
                    //                        val.find('.averagebar').width(data.ratingvalue / 100.0 * max-3);
                    //                    }


                    $.actjax(actics.api + 'agents/loadagent',
                        'json',
                        { groupname: actics.groupname, agentname: actics.agentname },
                        null,
                        function(agent) {
                            var feedbackCount = $('#valueManager .feedbackstatuscount');

                            feedbackCount.fadeOut('slow', function() {
                                feedbackCount.find('.val').html(agent.acticsnumberoffeedbacks + (agent.acticsnumberoffeedbacks == 1 ? ' rating' : 'ratings'));
                                feedbackCount.fadeIn('fast');

                            });

                            var number = $('#contenttop .valuenumber');
                            number.fadeOut('slow', function() {
                                number.find('.number').html(Math.abs(agent.acticsnumber) + '%');
                                var change = number.find('.change'); // -neg,.change-pos,.change-none
                                change.removeClass('pos').removeClass('neg').removeClass('none');
                                change.addClass(agent.acticsnumberchange > 0 ? 'pos' : agent.acticsnumberchange < 0 ? 'neg' : 'none');
                                change.children().eq(1).html(Math.abs(agent.acticsnumberchange) + '%');
                                number.fadeIn('fast');
                            });
                        });

                    valueManager.setStatus();

                    val.find('.rate').hide();

                    valueManager.showLayerWishes();
                }
            );

        return false;
    },

    //    rate : function()
    //    {
    //        var ratingsArray = new Array();
    //        var values = new Array();
    //        
    //        var br = false;
    //        var ratedLower = false;
    //        $('#valueManager .valueList .value').each(function(i)
    //        {
    //            if (br) return;
    //            var rate = parseInt($(this).find('.rating .val').html());
    //            var valueName = valueManager.getEntityFromURL($(this).find('h3 a').attr('href'));
    //            
    //            if (valueName != '#')
    //            {
    //                if (!$(this).find('.dragged').length == 1)
    //                {
    //                    alert('Please move the slider on all values, before submitting your rating');
    //                    br = true;
    //                    return false;
    //                }
    //                values[values.length] = $(this);
    //                ratingsArray[ratingsArray.length] = valueName + '|' + rate;
    //            }
    //            
    //            if (!ratedLower)
    //            {
    //                var r = parseInt($(this).find('.bar').data('rate'));
    //                ratedLower =  !isNaN(r) && r>rate;
    //            }
    //        });
    //        
    //        if (br) return false;
    //        
    //        $.actjax(actics.api + 'agents/submitratings',
    //                'json',
    //                {groupname : actics.groupname,agentname : actics.agentname, ratings: ratingsArray}, 
    //                null,
    //                function (data)
    //                {
    //                    // look through the result
    //                    $.each(data, function(key, value)
    //                    {
    //                        $(values[key]).find('.custombar').animate({opacity:'0.20'}, 1000, null);
    //                        $(values[key]).find('.custombar').unbind('mousedown');
    //                        
    //                        $(values[key]).addClass('readonly');
    //                        var max = $(values[key]).find('.bar').width();
    //                        $(values[key]).find('.averagebar').width(value.ratingvalue / 100.0 * max-3);
    //                    });
    //                    
    //                    
    //                    $.actjax(actics.api + 'agents/loadagent',
    //                        'json', 
    //                        {groupname : actics.groupname,agentname : actics.agentname},
    //                        null,
    //                        function (agent)
    //                        {
    //                            var feedbackCount = $('#valueManager .feedbackstatuscount');
    //                            
    //                            feedbackCount.fadeOut('slow', function() {
    //                                feedbackCount.find('.val').html(agent.acticsnumberoffeedbacks + (agent.acticsnumberoffeedbacks==1?' rating':'ratings'));
    //                                feedbackCount.fadeIn('fast');
    //                            
    //                            });
    //                            
    //                            var number = $('#contenttop .valuenumber');
    //                            number.fadeOut('slow', function() {
    //                                number.find('.number').html(Math.abs(agent.acticsnumber) + '%');
    //                                var change = number.find('.change'); // -neg,.change-pos,.change-none
    //                                change.removeClass('pos').removeClass('neg').removeClass('none');
    //                                change.addClass(agent.acticsnumberchange>0?'pos':agent.acticsnumberchange<0?'neg':'none');
    //                                change.children().eq(1).html(Math.abs(agent.acticsnumberchange) + '%');
    //                                number.fadeIn('fast');
    //                            });
    //                        });
    //                    
    //                    valueManager.setStatus();
    //                }
    //            );

    //        if (ratedLower) 
    //        {
    //            valueManager.showLayerWishes();
    //            alert('You have rated less then last rating, please suggest actions on how to improve');
    //        }        
    //        
    //        return false;
    //    },

    endorse: function() {
        var action = $(this).parents('.action');
        if (action.length != 1) {
            return false;
        }

        var isAction = action.parents('.actionlist').length == 1;
        var isWish = action.parents('.wishlist').length == 1;

        if (!isAction && !isWish) {
            throw ('invalid endorse call');
        }

        var box = action.find('.endorse')
        var args = {
            groupname: actics.groupname,
            agentname: actics.agentname,
            actionname: valueManager.getEntityFromURL(action.find('h3 a').attr('href')),
            valuename: valueManager.getEntityFromURL(valueManager.selectedValue.find('h3 a').attr('href'))
        }
        var url = actics.api + (isAction ? 'agents/endorseagentaction' : 'agents/endorseagentwish');

        box.fadeOut('fast', function() {
            $.actjax(url, 'json', args, null, function(data) {
                box
                    .removeClass('can')
                    .addClass('cant')
                    .find('.count')
                        .html(data.endorsements)
                        .end()
                    .fadeIn('slow');
            });
        });

        $('#requestpopup').showRequestPopup('Involve your network in endorsing', 10, args.actionname);

        return false;
    },

    endorseValue: function() {
        var definition = $(this).parents('.valueDefinition');
        if (definition.length != 1) {
            return false;
        }
        var box = definition.find('.endorse')
        var args = {
            groupname: actics.groupname,
            agentname: actics.agentname,
            valuename: valueManager.getEntityFromURL(valueManager.selectedValue.find('h3 a').attr('href'))
        };
        var url = actics.api + 'agents/votevalue';

        box.fadeOut('fast', function() {

            $.actjax(url, 'json', args, null, function(data) {
                box
                    .removeClass('can')
                    .addClass('cant')
                    .find('.count')
                        .html(data.votes.toString())
                        .end()
                    .fadeIn('slow');

                valueManager.selectedValue.find('h3 a span').html(data.votes.toString());

                valueManager.values.sortChildren(function(a, b) {
                    var va = parseInt($(a).find('h3 a span').html());
                    var vb = parseInt($(b).find('h3 a span').html())

                    return vb - va;
                });

            });
        });

        return false;
    },

    deleteAction: function() {

        var action = $(this).parents('.action');
        if (action.length != 1) {
            return false;
        }

        if (!confirm('Are you sure you want to delete action "' + action.find('h3 a').html() + '"')) {
            return false;
        }

        var args = {
            groupname: actics.groupname,
            agentname: actics.agentname,
            valuename: valueManager.getEntityFromURL(valueManager.selectedValue.find('h3 a').attr('href')),
            actionname: valueManager.getEntityFromURL(action.find('h3 a').attr('href'))
        };

        $.actjax(actics.api + 'agents/deleteagentaction', 'json', args, action, function(data) {
            action.remove();
            if (valueManager.selectedDescription.find('.actionlist .action').length == 0) {
                valueManager.selectedDescription.find('.actionlist .emptylist').show();
            }
        });

        return false;
    },

    deleteWish: function() {

        var action = $(this).parents('.action');

        if (action.length == 1) {
            if (!confirm('Are you sure you want to delete suggested action "' + action.find('h3 a').html() + '"')) {
                return false;
            }

            var args = {
                groupname: actics.groupname,
                agentname: actics.agentname,
                valuename: valueManager.getEntityFromURL(valueManager.selectedValue.find('h3 a').attr('href')),
                actionname: valueManager.getEntityFromURL(action.find('h3 a').attr('href'))
            };

            $.actjax(actics.api + 'agents/deleteagentwish', 'json', args, action, function(data) {

                action.remove();

                if (valueManager.selectedDescription.find('.wishlist .action').length == 0) {
                    valueManager.selectedDescription.find('.wishlist .emptylist').show();
                }
            });
        }

        return false;
    },

    adoptWish: function() {

        var action = $(this).parents('.action');
        if (action.length == 1) {

            if (!confirm('Are you sure you want to Adopt Action?')) {
                return false;
            }

            var args = {
                groupname: actics.groupname,
                agentname: actics.agentname,
                valuename: valueManager.getEntityFromURL(valueManager.selectedValue.find('h3 a').attr('href')),
                actionname: valueManager.getEntityFromURL(action.find('h3 a').attr('href'))
            };

            $.actjax(actics.api + 'agents/adoptagentwish', 'html', args, action, function(data) {

                action.remove();
                if (valueManager.selectedDescription.find('.wishlist .action').length == 0) {
                    valueManager.selectedDescription.find('.wishlist .emptylist').show();
                }

                valueManager.selectedDescription.find('.actionlist .emptylist').hide();

                $(data)
                        .prependTo(valueManager.selectedDescription.find('.actionlist'))
                        .find('.delete')
                            .click(valueManager.deleteAction)
                            .end();
            });

        }
        return false;
    }
}

$(document).ready(function() {
    valueManager.init();
});

$(document).ready(function() {

    $('#layerNominationCompleted').showLayer();
    $('#layerNominationError').showLayer();
    $('#layerAlreadyMember').showLayer();
    $('#layerNominationAlternatives').showLayer();
    $('#layerJoinInvite').showLayer();
    $('#layerAcceptInvite').showLayer();

    $('#layerJoinGroupInvite').showLayer();
    $('#layerAcceptGroupInvite').showLayer();
});

$(document).ready(function() {
    $('#pnlActionComments .shownewcomment')
        .requireBind('click', { login: true, group: true }, function() {
            $('#layerActionComments')
            .showLayer()
            .find('[name=comment]').val('').focus().end()
            .find('[name=tags]').val('');
            return false;
        });

    $('#layerActionComments form').ajaxForm({
        dataType: 'html',
        success: function(data) {
            $('#layerActionComments').hideLayer();

            $(data).hide().prependTo('#pnlActionComments .commentlist').fadeIn('slow');
        }
    });
});

// Profile Settings
$(document).ready(function() {
    /*$('.panel .functionlink').mouseover(function() {
        $(this).parents('.panel').addClass('active');
    });

    $('.panel .functionlink').mouseout(function() {
        $(this).parents('.panel').removeClass('active');
    });*/

    $('#formAgentSearch select').change(function() {
        $(this).parents('form').submit();
    });

    if ($('#layerEditProfile').length == 1) {
        // Profile Image
        $('#formProfileImage').ajaxForm({
            dataType: 'json',
            beforeSubmit: function() {

            },
            //            error : function (data) {
            //                alert(data.responseText);
            //            },
            success: function(data) {
                $.refresh();
            }
        });

        // Profile Settings   
        $('#formProfileSettings').ajaxForm({
            dataType: 'json',
            success: function(data) {
                $.refresh(data.url);
            }
            //            error : function(data) {    
            //                alert(data.responseText);
            //            }
        });
    }

    if ($('#pnlDescription').length == 1) {

        $('#layerProfileDescription form').ajaxForm({
            dataType: 'json',
            success: function(data) {
                $('#pnlDescription .desc').html(data.htmldescription).end();

                $('#layerProfileDescription').hideLayer();
            }
        });

        $('#boxDescription a.functionlink').click(function() {
            $('#layerProfileDescription').showLayer();

            $.actjax(actics.api + 'agents/loadagent',
                'json',
                { groupname: actics.groupname, agentName: actics.agentname },
                $('#layerProfileDescription'),
                function(data) {

                    $('#layerProfileDescription textarea[name=description]')
                        .val(data.description)
                        .focus()
                        .end();
                });
            return false;
        });
    }

    if ($('#pnlAgentComments .shownewcomment').length == 1) {

        $('#pnlAgentComments .shownewcomment')
            .requireBind('click', { login: true, group: true, proximity: true }, function() {
                $('#layerAgentComments')
                    .showLayer()
                    .find('textarea[name=comment]')
                        .val('')
                        .focus()
                        .end();

                return false;
            })
            .end();

        $('#layerAgentComments form').ajaxForm({
            dataType: 'post',
            beforeSubmit: function() {
                $('#layerAgentComments').hideLayer();
            },
            success: function(data) {



                $(data).hide().prependTo('#pnlAgentComments .commentlist').fadeIn('slow');
            }
        });
    }

    //    $('.datatable.messagelist tbody tr').click(function() {
    //        
    //        var mid = $(this).attr('id');
    //        
    //        // $(this).removeClass('unread');
    //   
    //        $.refresh(mid);
    //    });
});

// 06 March 2009
// Svetlin
// After Uploading the file we must clear the value
$(document).ready(function() {
    $('#layerRatingReason form').ajaxForm({
        dataType: 'html',
        beforeSubmit: function() {
            var attachment = $('#layerRatingReason').find('#ratefileattachment').attr('value');
            var reasoncomment = $('#layerRatingReason').find('#ratereason').attr('value');

            if (!attachment && !reasoncomment) {
                alert('The comments or file attachment cannot be both empty!');
                return false;
            }
        },
        success: function() {
            $('#layerRatingReason').find('#ratefileattachment').attr('value', '');
            $('#layerRatingReason').find('#ratereason').attr('value', '');
            $('#layerRatingReason').find('#valueid').attr('value', '');
            $('#layerRatingReason').find('#reasonrateid').attr('value', '');
            $('#layerRatingReason').find('#valuename').attr('value', '');
            $('#layerRatingReason').hideLayer();
        }
    });


});

// Setup toolbox
$(document).ready(function() {
    $('#layerNewMessage form').ajaxForm({
        beforeSubmit: function() {
            var subject = $('#layerNewMessage input[name=subject]').val();
            var message = $('#layerNewMessage textarea[name=message]').val();

            if (subject == null || subject == "") {
                alert('Subject field should be filled in.');
                return false;
            }

            if (message == null || message == "") {
                alert('Messsage field should be filled in.');
                return false;
            }

            if (message.length < 5) {
                alert('Message is too short. It should be at least 5 symbols.');
                return false;
            }
        },
        dataType: 'json',
        success: function() {
            $('#layerNewMessage').hideLayer();
            alert('Message send');
        }
    });

    $('#layerFlag form').ajaxForm({
        dataType: 'json',
        success: function() {
            $('#layerFlag').hideLayer();
            alert('Thank you');
        }
    });

    $('#layerAdoptAction form').ajaxForm({
        beforeSubmit: function() {
            var valuename = $('#layerAdoptAction').find('[name=valuename][value]');

            if (!valuename || valuename.length == 0) {
                alert('Please select the value to improve it with this action.');
                return false;
            }

        },
        dataType: 'json',
        success: function() {
            $('#layerAdoptAction').hideLayer();
            alert('Action added to your profile');
        }
    });

    $('#layerShare form').ajaxForm({
        beforeSubmit: function() {
            var value = $('#layerShare form textarea').attr('value');
            var isValid = ActicsValidator.IsLessThanOrEqualStringLength(value, 64);

            var members = $('#layerShare form').find('[name=member][checked]');
            var isValidContacts = (members != null && members.length > 0);

            if (!isValid || !isValidContacts) {
                if (!isValid)
                    alert('The message is too long. Please change the sending message.');
                else if (!isValidContacts)
                    alert('You haven\'t selected any contacts.');

                return false;
            }
        },
        dataType: 'json',
        success: function() {
            $('#layerShare').hideLayer();
            alert('Thank you for sharing');
        }
    });

    $('#toolbox .message').requireBind('click', { login: true, group: true }, function() {
        $('#layerNewMessage')
            .find('[name=subject]').val('').end()
            .find('[name=message]').val('').end()
            .showLayer();
        return false;
    });

    $('#toolbox .proximity').requireBind('click', { login: true, group: true }, function() {
        $('#layerProximity').showLayer();
        return false;
    });

    $('#toolbox .flag').requireBind('click', { login: true, group: true }, function() {
        $('#layerFlag').showLayer();
        return false;
    });

    $('#toolbox .adoptaction').requireBind('click', { login: true, group: true }, function() {
        $('#layerAdoptAction').showLayer();
        return false;
    });

    $('#toolbox .share').requireBind('click', { login: true }, function() {
        $('#layerShare').showLayer();
        return false;
    });

    $('#toolbox .embed').requireBind('click', { login: true }, function() {
        $('#layerEmbed').showLayer();
        return false;
    });
});



/* RichTextEditor */
$(document).ready(function() {
    $('.wysiwyg').wysiwyg();

});

/* Global Methods */
var rgb2hex = function(srgb) {
    var rgbvals = /rgb\((.+),(.+),(.+)\)/i.exec(srgb);
    var rval = parseInt(rgbvals[1]);
    var gval = parseInt(rgbvals[2]);
    var bval = parseInt(rgbvals[3]);

    var toHex = function(N) {
        if (N == null) return "00";
        N = parseInt(N); if (N == 0 || isNaN(N)) return "00";
        N = Math.max(0, N); N = Math.min(N, 255); N = Math.round(N);
        return "0123456789ABCDEF".charAt((N - N % 16) / 16)
      + "0123456789ABCDEF".charAt(N % 16);
    };

    return '#' + toHex(rval) + toHex(gval) + toHex(bval);
};

function popUp(URL) {
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=1024,height=768');");
}



function startsWith(str, begin) {
    return (str.match("^" + begin) == begin)
}


$(document).ready(function() {
    if ($('body.external').length == 1) {
        $('#webproxy').attr('src', actics.webproxy + '?height=' + $(document.body).height() + "&r=" + Math.random());
    }
});


function checkCreateNomination() {

    console.log('checking');
    var radioButtons = $('#nominateForm').find('input[type=radio]');
    var name = $('#nominateForm').find('input[type=text]').val();

    if (radioButtons == null || radioButtons.lenght == 0 || !name) {
        alert("Please type the name of the profile and chose the type of the agent.");
        return false;
    }

    return true;

}
/**
 *
 * Color picker
 * Author: Stefan Petre www.eyecon.ro
 * 
 */
(function ($) {
	var ColorPicker = function () {
		var
			ids = {},
			inAction,
			charMin = 65,
			visible,
			tpl = '<div class="colorpicker"><div class="colorpicker_color"><div><div></div></div></div><div class="colorpicker_hue"><div></div></div><div class="colorpicker_new_color"></div><div class="colorpicker_current_color"></div><div class="colorpicker_hex"><input type="text" maxlength="6" size="6" /></div><div class="colorpicker_rgb_r colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_g colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_h colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_s colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_submit"></div></div>',
			defaults = {
				eventName: 'click',
				onShow: function () {},
				onBeforeShow: function(){},
				onHide: function () {},
				onChange: function () {},
				onSubmit: function () {},
				color: 'ff0000',
				livePreview: true,
				flat: false
			},
			fillRGBFields = function  (hsb, cal) {
				var rgb = HSBToRGB(hsb);
				$(cal).data('colorpicker').fields
					.eq(1).val(rgb.r).end()
					.eq(2).val(rgb.g).end()
					.eq(3).val(rgb.b).end();
			},
			fillHSBFields = function  (hsb, cal) {
				$(cal).data('colorpicker').fields
					.eq(4).val(hsb.h).end()
					.eq(5).val(hsb.s).end()
					.eq(6).val(hsb.b).end();
			},
			fillHexFields = function (hsb, cal) {
				$(cal).data('colorpicker').fields
					.eq(0).val(HSBToHex(hsb)).end();
			},
			setSelector = function (hsb, cal) {
				$(cal).data('colorpicker').selector.css('backgroundColor', '#' + HSBToHex({h: hsb.h, s: 100, b: 100}));
				$(cal).data('colorpicker').selectorIndic.css({
					left: parseInt(150 * hsb.s/100, 10),
					top: parseInt(150 * (100-hsb.b)/100, 10)
				});
			},
			setHue = function (hsb, cal) {
				$(cal).data('colorpicker').hue.css('top', parseInt(150 - 150 * hsb.h/360, 10));
			},
			setCurrentColor = function (hsb, cal) {
				$(cal).data('colorpicker').currentColor.css('backgroundColor', '#' + HSBToHex(hsb));
			},
			setNewColor = function (hsb, cal) {
				$(cal).data('colorpicker').newColor.css('backgroundColor', '#' + HSBToHex(hsb));
			},
			keyDown = function (ev) {
				var pressedKey = ev.charCode || ev.keyCode || -1;
				if ((pressedKey > charMin && pressedKey <= 90) || pressedKey == 32) {
					return false;
				}
				var cal = $(this).parent().parent();
				if (cal.data('colorpicker').livePreview === true) {
					change.apply(this);
				}
			},
			change = function (ev) {
				var cal = $(this).parent().parent(), col;
				if (this.parentNode.className.indexOf('_hex') > 0) {
					cal.data('colorpicker').color = col = HexToHSB(fixHex(this.value));
				} else if (this.parentNode.className.indexOf('_hsb') > 0) {
					cal.data('colorpicker').color = col = fixHSB({
						h: parseInt(cal.data('colorpicker').fields.eq(4).val(), 10),
						s: parseInt(cal.data('colorpicker').fields.eq(5).val(), 10),
						b: parseInt(cal.data('colorpicker').fields.eq(6).val(), 10)
					});
				} else {
					cal.data('colorpicker').color = col = RGBToHSB(fixRGB({
						r: parseInt(cal.data('colorpicker').fields.eq(1).val(), 10),
						g: parseInt(cal.data('colorpicker').fields.eq(2).val(), 10),
						b: parseInt(cal.data('colorpicker').fields.eq(3).val(), 10)
					}));
				}
				if (ev) {
					fillRGBFields(col, cal.get(0));
					fillHexFields(col, cal.get(0));
					fillHSBFields(col, cal.get(0));
				}
				setSelector(col, cal.get(0));
				setHue(col, cal.get(0));
				setNewColor(col, cal.get(0));
				cal.data('colorpicker').onChange.apply(cal, [col, HSBToHex(col), HSBToRGB(col)]);
			},
			blur = function (ev) {
				var cal = $(this).parent().parent();
				cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus')
			},
			focus = function () {
				charMin = this.parentNode.className.indexOf('_hex') > 0 ? 70 : 65;
				$(this).parent().parent().data('colorpicker').fields.parent().removeClass('colorpicker_focus');
				$(this).parent().addClass('colorpicker_focus');
			},
			downIncrement = function (ev) {
				var field = $(this).parent().find('input').focus();
				var current = {
					el: $(this).parent().addClass('colorpicker_slider'),
					max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : (this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255),
					y: ev.pageY,
					field: field,
					val: parseInt(field.val(), 10),
					preview: $(this).parent().parent().data('colorpicker').livePreview					
				};
				$(document).bind('mouseup', current, upIncrement);
				$(document).bind('mousemove', current, moveIncrement);
			},
			moveIncrement = function (ev) {
				ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val + ev.pageY - ev.data.y, 10))));
				if (ev.data.preview) {
					change.apply(ev.data.field.get(0), [true]);
				}
				return false;
			},
			upIncrement = function (ev) {
				change.apply(ev.data.field.get(0), [true]);
				ev.data.el.removeClass('colorpicker_slider').find('input').focus();
				$(document).unbind('mouseup', upIncrement);
				$(document).unbind('mousemove', moveIncrement);
				return false;
			},
			downHue = function (ev) {
				var current = {
					cal: $(this).parent(),
					y: $(this).offset().top
				};
				current.preview = current.cal.data('colorpicker').livePreview;
				$(document).bind('mouseup', current, upHue);
				$(document).bind('mousemove', current, moveHue);
			},
			moveHue = function (ev) {
				change.apply(
					ev.data.cal.data('colorpicker')
						.fields
						.eq(4)
						.val(parseInt(360*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.y))))/150, 10))
						.get(0),
					[ev.data.preview]
				);
				return false;
			},
			upHue = function (ev) {
				fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				$(document).unbind('mouseup', upHue);
				$(document).unbind('mousemove', moveHue);
				return false;
			},
			downSelector = function (ev) {
				var current = {
					cal: $(this).parent(),
					pos: $(this).offset()
				};
				current.preview = current.cal.data('colorpicker').livePreview;
				$(document).bind('mouseup', current, upSelector);
				$(document).bind('mousemove', current, moveSelector);
			},
			moveSelector = function (ev) {
				change.apply(
					ev.data.cal.data('colorpicker')
						.fields
						.eq(6)
						.val(parseInt(100*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.pos.top))))/150, 10))
						.end()
						.eq(5)
						.val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX - ev.data.pos.left))))/150, 10))
						.get(0),
					[ev.data.preview]
				);
				return false;
			},
			upSelector = function (ev) {
				fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				$(document).unbind('mouseup', upSelector);
				$(document).unbind('mousemove', moveSelector);
				return false;
			},
			enterSubmit = function (ev) {
				$(this).addClass('colorpicker_focus');
			},
			leaveSubmit = function (ev) {
				$(this).removeClass('colorpicker_focus');
			},
			clickSubmit = function (ev) {
				var cal = $(this).parent();
				var col = cal.data('colorpicker').color;
				cal.data('colorpicker').origColor = col;
				setCurrentColor(col, cal.get(0));
				cal.data('colorpicker').onSubmit(col, HSBToHex(col), HSBToRGB(col));
			},
			show = function (ev) {
				var cal = $('#' + $(this).data('colorpickerId'));
				cal.data('colorpicker').onBeforeShow.apply(this, [cal.get(0)]);
				var pos = $(this).offset();
				var viewPort = getViewport();
				var top = pos.top + this.offsetHeight;
				var left = pos.left;
				if (top + 176 > viewPort.t + viewPort.h) {
					top -= this.offsetHeight + 176;
				}
				if (left + 356 > viewPort.l + viewPort.w) {
					left -= 356;
				}
				cal.css({left: left + 'px', top: top + 'px'});
				if (cal.data('colorpicker').onShow.apply(this, [cal.get(0)]) != false) {
					cal.show();
				}
				
				$(document).bind('mousedown', {cal: cal}, hide);
				return false;
			},
			hide = function (ev) {
				if (!isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) {
					if (ev.data.cal.data('colorpicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) {
						ev.data.cal.hide();
					}
					$(document).unbind('mousedown', hide);
				}
			},
			isChildOf = function(parentEl, el, container) {
				if (parentEl == el) {
					return true;
				}
				if (parentEl.contains) {
					return parentEl.contains(el);
				}
				if ( parentEl.compareDocumentPosition ) {
					return !!(parentEl.compareDocumentPosition(el) & 16);
				}
				var prEl = el.parentNode;
				while(prEl && prEl != container) {
					if (prEl == parentEl)
						return true;
					prEl = prEl.parentNode;
				}
				return false;
			},
			getViewport = function () {
				var m = document.compatMode == 'CSS1Compat';
				return {
					l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
					t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
					w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
					h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
				};
			},
			fixHSB = function (hsb) {
				return {
					h: Math.min(360, Math.max(0, hsb.h)),
					s: Math.min(100, Math.max(0, hsb.s)),
					b: Math.min(100, Math.max(0, hsb.b))
				};
			}, 
			fixRGB = function (rgb) {
				return {
					r: Math.min(255, Math.max(0, rgb.r)),
					g: Math.min(255, Math.max(0, rgb.g)),
					b: Math.min(255, Math.max(0, rgb.b))
				};
			},
			fixHex = function (hex) {
				var len = 6 - hex.length;
				if (len > 0) {
					var o = [];
					for (var i=0; i<len; i++) {
						o.push('0');
					}
					o.push(hex);
					hex = o.join('');
				}
				return hex;
			}, 
			HexToRGB = function (hex) {
				var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16);
				return {r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF)};
			},
			HexToHSB = function (hex) {
				return RGBToHSB(HexToRGB(hex));
			},
			RGBToHSB = function (rgb) {
				var hsb = {};
				hsb.b = Math.max(Math.max(rgb.r,rgb.g),rgb.b);
				hsb.s = (hsb.b <= 0) ? 0 : Math.round(100*(hsb.b - Math.min(Math.min(rgb.r,rgb.g),rgb.b))/hsb.b);
				hsb.b = Math.round((hsb.b /255)*100);
				if((rgb.r==rgb.g) && (rgb.g==rgb.b)) hsb.h = 0;
				else if(rgb.r>=rgb.g && rgb.g>=rgb.b) hsb.h = 60*(rgb.g-rgb.b)/(rgb.r-rgb.b);
				else if(rgb.g>=rgb.r && rgb.r>=rgb.b) hsb.h = 60  + 60*(rgb.g-rgb.r)/(rgb.g-rgb.b);
				else if(rgb.g>=rgb.b && rgb.b>=rgb.r) hsb.h = 120 + 60*(rgb.b-rgb.r)/(rgb.g-rgb.r);
				else if(rgb.b>=rgb.g && rgb.g>=rgb.r) hsb.h = 180 + 60*(rgb.b-rgb.g)/(rgb.b-rgb.r);
				else if(rgb.b>=rgb.r && rgb.r>=rgb.g) hsb.h = 240 + 60*(rgb.r-rgb.g)/(rgb.b-rgb.g);
				else if(rgb.r>=rgb.b && rgb.b>=rgb.g) hsb.h = 300 + 60*(rgb.r-rgb.b)/(rgb.r-rgb.g);
				else hsb.h = 0;
				hsb.h = Math.round(hsb.h);
				return hsb;
			},
			HSBToRGB = function (hsb) {
				var rgb = {};
				var h = Math.round(hsb.h);
				var s = Math.round(hsb.s*255/100);
				var v = Math.round(hsb.b*255/100);
				if(s == 0) {
					rgb.r = rgb.g = rgb.b = v;
				} else {
					var t1 = v;
					var t2 = (255-s)*v/255;
					var t3 = (t1-t2)*(h%60)/60;
					if(h==360) h = 0;
					if(h<60) {rgb.r=t1;	rgb.b=t2; rgb.g=t2+t3}
					else if(h<120) {rgb.g=t1; rgb.b=t2;	rgb.r=t1-t3}
					else if(h<180) {rgb.g=t1; rgb.r=t2;	rgb.b=t2+t3}
					else if(h<240) {rgb.b=t1; rgb.r=t2;	rgb.g=t1-t3}
					else if(h<300) {rgb.b=t1; rgb.g=t2;	rgb.r=t2+t3}
					else if(h<360) {rgb.r=t1; rgb.g=t2;	rgb.b=t1-t3}
					else {rgb.r=0; rgb.g=0;	rgb.b=0}
				}
				return {r:Math.round(rgb.r), g:Math.round(rgb.g), b:Math.round(rgb.b)};
			},
			RGBToHex = function (rgb) {
				var hex = [
					rgb.r.toString(16),
					rgb.g.toString(16),
					rgb.b.toString(16)
				];
				$.each(hex, function (nr, val) {
					if (val.length == 1) {
						hex[nr] = '0' + val;
					}
				});
				return hex.join('');
			},
			HSBToHex = function (hsb) {
				return RGBToHex(HSBToRGB(hsb));
			};
		return {
			init: function (options) {
				options = $.extend({}, defaults, options||{});
				if (typeof options.color == 'string') {
					options.color = HexToHSB(options.color);
				} else if (options.color.r != undefined && options.color.g != undefined && options.color.b != undefined) {
					options.color = RGBToHSB(options.color);
				} else if (options.color.h != undefined && options.color.s != undefined && options.color.b != undefined) {
					options.color = fixHSB(options.color);
				} else {
					return this;
				}
				options.origColor = options.color;
				return this.each(function () {
					if (!$(this).data('colorpickerId')) {
						var id = 'collorpicker_' + parseInt(Math.random() * 1000);
						$(this).data('colorpickerId', id);
						var cal = $(tpl).attr('id', id);
						if (options.flat) {
							cal.appendTo(this).show();
						} else {
							cal.appendTo(document.body);
						}
						options.fields = cal
											.find('input')
												.bind('keydown', keyDown)
												.bind('change', change)
												.bind('blur', blur)
												.bind('focus', focus);
						cal.find('span').bind('mousedown', downIncrement);
						options.selector = cal.find('div.colorpicker_color').bind('mousedown', downSelector);
						options.selectorIndic = options.selector.find('div div');
						options.hue = cal.find('div.colorpicker_hue div');
						cal.find('div.colorpicker_hue').bind('mousedown', downHue);
						options.newColor = cal.find('div.colorpicker_new_color');
						options.currentColor = cal.find('div.colorpicker_current_color');
						cal.data('colorpicker', options);
						cal.find('div.colorpicker_submit')
							.bind('mouseenter', enterSubmit)
							.bind('mouseleave', leaveSubmit)
							.bind('click', clickSubmit);
						fillRGBFields(options.color, cal.get(0));
						fillHSBFields(options.color, cal.get(0));
						fillHexFields(options.color, cal.get(0));
						setHue(options.color, cal.get(0));
						setSelector(options.color, cal.get(0));
						setCurrentColor(options.color, cal.get(0));
						setNewColor(options.color, cal.get(0));
						if (options.flat) {
							cal.css({
								position: 'relative',
								display: 'block'
							});
						} else {
							$(this).bind(options.eventName, show);
						}
					}
				});
			},
			showPicker: function() {
				return this.each( function () {
					if ($(this).data('colorpickerId')) {
						show.apply(this);
					}
				});
			},
			hidePicker: function() {
				return this.each( function () {
					if ($(this).data('colorpickerId')) {
						$('#' + $(this).data('colorpickerId')).hide();
					}
				});
			},
			setColor: function(col) {
				if (typeof col == 'string') {
					col = HexToHSB(col);
				} else if (col.r != undefined && col.g != undefined && col.b != undefined) {
					col = RGBToHSB(col);
				} else if (col.h != undefined && col.s != undefined && col.b != undefined) {
					col = fixHSB(col);
				} else {
					return this;
				}
				return this.each(function(){
					if ($(this).data('colorpickerId')) {
						var cal = $('#' + $(this).data('colorpickerId'));
						cal.data('colorpicker').color = col;
						cal.data('colorpicker').origColor = col;
						fillRGBFields(col, cal.get(0));
						fillHSBFields(col, cal.get(0));
						fillHexFields(col, cal.get(0));
						setHue(col, cal.get(0));
						setSelector(col, cal.get(0));
						setCurrentColor(col, cal.get(0));
						setNewColor(col, cal.get(0));
					}
				});
			}
		};
	}();
	$.fn.extend({
		ColorPicker: ColorPicker.init,
		ColorPickerHide: ColorPicker.hide,
		ColorPickerShow: ColorPicker.show,
		ColorPickerSetColor: ColorPicker.setColor
	});
})(jQuery)

/* 
   10.Dec.2008
   Svetlin Ralchev 
   NOTE: The line below implements the functionality for close the color picker,
         when you press somewhere different than the area of the control
*/

$(document).ready(function() {
    $(document).bind('click', function(e) 
     {
          $('.colorpicker_Holder').each(
          function() 
          { 
            var picker = $(this).find('.colorpicker');
            
            if(picker.data('innerClick'))
            {
               picker.data('innerClick', false);
               return;
            }
          
            if($(this).data('colorpicker')) 
            {       
               $(this).data('colorpicker', false); 
               return; 
            }
       
            if($(this).data('widt')) 
            { 
               $(this).data('widt', false);
               $(this).stop().animate({height: 0}, 100); 
            } 
        });
     }
    );
});/* widgets */
$(document).ready(function() {
    $('.widget .optionbutton')
        .click(function() {
            var id = $(this).parents('.widget').parents('.widgetContainer').attr('id');
            var optionid = "widget_" + id + "_options";
            $('#' + optionid).find('.widgetOptions').showLayer();
        });

    $('.widget .optionbuttondel')
        .click(function() {
            var id = $(this).parents('.widget').parents('.widgetContainer').attr('id');
            var optionid = "widget_" + id + "_options";
            $('#' + optionid).find('.widgetRemove').showLayer();
        });


    $('#widget_worldatlas map area[title=Africa]').tooltip({
        bodyHandler: function() {
            var html = $('#tooltipAfrica').html();
            return html;
        }
    });

    $('#widget_worldatlas map area[title=Americas]').tooltip({
        bodyHandler: function() {
            var html = $('#tooltipAmericas').html();
            return html;
        }
    });

    $('#widget_worldatlas map area[title=Asia]').tooltip({
        bodyHandler: function() {
            var html = $('#tooltipAsia').html();
            return html;
        }
    });

    $('#widget_worldatlas map area[title=Oceania]').tooltip({
        bodyHandler: function() {
            var html = $('#tooltipOceania').html();
            return html;
        }
    });

    $('#widget_worldatlas map area[title=Europe]').tooltip({
        bodyHandler: function() {
            var html = $('#tooltipEurope').html();
            return html;
        }
    });

    var getWidgetPostition = function(allcurrentwidgets, widgetguid) {
        if (allcurrentwidgets == null || allcurrentwidgets.length == 0)
            return -1;

        for (var i = 0; i < allcurrentwidgets.length; i++) {
            var id = $(allcurrentwidgets[i]).find('#widgetid').text();

            if (id == widgetguid)
                return i + 1;
        }

        return -1;

    };

    var removeHandler = function(ev, ui) { $(ui.item).data('sender', this); };

    var stopHandler = function(ev, ui) {
        var thidid = $(this).attr('id');
        var widget = ui.item;
        var widgetguid = widget.find('#widgetid').text();
        var sender = $(widget).data('sender');
        var widgetcolumn;
        var widgetposition;

        var netboard = $("#mynetworkwidgetboard");
        if (netboard.length > 0) {
            widgetcolumn = 2;
            var rightwidgets = $(netboard).find('.widgetContainer');
            var rightposition = getWidgetPostition(rightwidgets, widgetguid);
            widgetposition = rightposition;
        }
        else {
            if (sender == null) {
                if (thidid == 'columnleft') {
                    widgetcolumn = 1;

                    var leftwidgets = $('#columnleft').find('.widgetContainer');
                    var leftposition = getWidgetPostition(leftwidgets, widgetguid);

                    if (leftposition == -1)
                        leftposition = 1;

                    widgetposition = leftposition;
                }
                else {

                    widgetcolumn = 2;

                    var rightwidgets = $('#columnright').find('.widgetContainer');
                    var rightposition = getWidgetPostition(rightwidgets, widgetguid);

                    if (rightposition == -1)
                        rightposition = 1;

                    widgetposition = rightposition;
                }
            }
            else {
                if (thidid == 'columnleft') {
                    widgetcolumn = 2;
                    $(widget).data('sender', null);

                    var rightwidgets = $('#columnright').find('.widgetContainer');
                    var rightposition = getWidgetPostition(rightwidgets, widgetguid);

                    if (rightposition == -1)
                        rightposition = 1;

                    widgetposition = rightposition;

                }
                else {
                    widgetcolumn = 1;
                    $(widget).data('sender', null);

                    var leftwidgets = $('#columnleft').find('.widgetContainer');
                    var leftposition = getWidgetPostition(leftwidgets, widgetguid);

                    if (leftposition == -1)
                        leftposition = 1;

                    widgetposition = leftposition;

                }

            }
        }

        switch (actics.widgetboardtype) {
            case 'groupwidgetboard':
                $.actjax(actics.api + 'widgets/ChangeGroupWidgetPosition', 'json', { column: widgetcolumn, position: widgetposition, widgetid: widgetguid }, null, function(data) { $.refresh(); });
                break;
            case 'agentwidgetboard':
                $.actjax(actics.api + 'widgets/ChangeAgentWidgetPosition', 'json', { column: widgetcolumn, position: widgetposition, widgetid: widgetguid }, null, function(data) { $.refresh(); });
                break;
            default:
                var exception = 'Invalid widgetboard type ' + actics.widgetboardtype;
                throw exception;
        }
    };


    if (actics.widgetboardisineditmode) {

        var netboard = $("#mynetworkwidgetboard");
        if (netboard.length == 0) {
            $("#columnleft").sortable({
                opacity: 0.65,
                cursor: 'move',
                connectWith: ['#columnright'],
                stop: stopHandler,
                remove: removeHandler
            });


            $("#columnright").sortable({
                opacity: 0.65,
                cursor: 'move',
                connectWith: ['#columnleft'],
                stop: stopHandler,
                remove: removeHandler
            });
        } else {
            $(netboard).sortable({
                opacity: 0.65,
                cursor: 'move',
                stop: stopHandler,
                remove: removeHandler
            });
        }
    }


});

$(document).ready(function() {
    $('.actics-tabs').tabs();
});

// Agent Clound Widget in My Network
function showAgentsInMyNetwork(title, sectorcode, agentid, groupid, networkid) {
    var popup = $('#layerCloudUsersNetwork');
    popup.find('.popuptitle').text(title);
    $.actjax(actics.api + 'network/getmynetworkmembersbysector', 'HTML', { sector: sectorcode, agent: agentid, group: groupid, networktypeid: networkid }, null, function(data) { $('#cloudnetworkuserlist').html(data); popup.showLayer(); });
}function doCreateCookie(name,value,path,domain,expires){
      var cookie_string=name+"="+value;
	  if(expires)
	  {
		expires=new Date(expires);
		cookie_string+=";expires="+expires.toGMTString();
	  }
	  document.cookie=cookie_string+";path="+path+";domain="+domain;
	} 
	
function GetCookie(cookie_name){
	var regexp=new RegExp(cookie_name +"=(.*?)(;|$)","i");
	var results=regexp.exec(document.cookie);
	if(results)
	{
		return(unescape(results[1]));
	}
	else
	{
		return null;
	}
}
 
function getCookieData(cookie){
	var ret=[];
	var subKeys=cookie.split("&");
	for (var i=0;i<subKeys.length;i++)
	{
		var pos=subKeys[i].indexOf("=");
		if(pos!=0){
			ret[subKeys[i].substring(0,pos)]=subKeys[i].substring(pos+1);
		}
	}
	return ret;
}

function CreateCookie(cookieName,keyName,value,path,domain,expires){
	var thisCookie=unescape(GetCookie(cookieName));
	if(thisCookie)
	{
		if(keyName)
		{
			var cookieData=getCookieData(thisCookie);
			cookieData[keyName]=value;
			value="";
			for (var cookie in cookieData){
			    if(cookie == null) continue;
				value += cookie + "=" +cookieData[cookie]+"&";
			}
			if(value.charAt(value.length-1)=="&"){value=value.substring(0,value.length-1)}
		}
	}
	doCreateCookie(cookieName,value,path,domain,expires);
}

// Show My Network Edit Popup

function editMyNetwork(title, type, networktypeid, groupid) {
    var popup = $('#layerEditNetwork');
    popup.find('.popuptitle').text(title);

    var weight = 0;

    if (type == 'group') {
        var edittitle = $('#' + groupid + '-' + type + '-edit');
        weight = edittitle.attr('class').replace('agent ', '');
    } else if (type == 'connections') {
        var edittitle = $('#' + networktypeid + '-' + type + '-edit');
        weight = edittitle.attr('class').replace('functionlink mynetwork ', '');
    }

    $('#im_connected_heading').css('display', 'none');
    $('#connected_to_me_heading').css('display', 'none');
    $('#marketplace_conn_heading').css('display', 'none');
    $('#marketplace_weighting').css('display', 'none');
    $('#connection_heading').css('display', 'none');

    $(popup).css('height', 400);
    $('#networkuserlist').css('display', 'block');
    
    if (type == 'group') {
        $(popup).css('height', 150);
        $('#networkuserlist').css('display', 'none');
        $('#marketplace_conn_heading').css('display', 'block');
        $('#marketplace_weighting').css('display', 'block');
    } else if (type == 'connections') {
        $('#marketplace_conn_heading').css('display', 'block');
        $('#connection_heading').css('display', 'block');
    } else if (type == 'imconnectedto') {
        $('#im_connected_heading').css('display', 'block');
    } else if (type == 'connectedtome') {
        $('#connected_to_me_heading').css('display', 'block');
    }

    popup.find('input[name=viewtype]').val(type);
    popup.find('#ddlNetworkImportance').val(weight);
    popup.find('input[name=mynetworkgroupid]').val(groupid);
    popup.find('input[name=networktypeid]').val(networktypeid);

    $.actjax(actics.api + 'network/getmynetworkmembers', 'HTML', { groupname: actics.groupname, viewtype: type, nettypeID: networktypeid }, null, function(data) { $('#networkuserlist').html(data); popup.showLayer(); });
}

$(document).ready(function() {
    var button = $('#btnSaveNetworkWeight');
    button.click(function() {

        var popup = $('#layerEditNetwork');
        var groupid = popup.find('input[name=mynetworkgroupid]').val();
        var nettypeid = popup.find('input[name=networktypeid]').val();
        var newweight = popup.find('#ddlNetworkImportance').val();
        var view = popup.find('input[name=viewtype]').val();

        $.actjax(actics.api + 'network/savenetworkweight', 'HTML', { groupname: actics.groupname, mynetworkgroupid: groupid, networktypeid: nettypeid, weight: newweight }, null, null);

        if (view != 'group') {
            var weightName = '';

            if (newweight == 1)
                weightName = "Low";
            else if (newweight == 2)
                weightName = "Medium";
            else if (newweight == 3)
                weightName = "High";

            var title = $('#' + nettypeid);

            if (title != null && title != "" && title.length != 0) {
                var txt = title.text();

                txt = txt.replace('Low', '#VAL#');
                txt = txt.replace('Medium', '#VAL#');
                txt = txt.replace('High', '#VAL#');

                txt = txt.replace('#VAL#', weightName);
                title.text(txt);

                var edittitle = $('#' + nettypeid + '-' + view + '-edit');
                edittitle.attr('class', 'functionlink mynetwork ' + newweight);
            }
        }
        else {
            var edittitle = $('#' + groupid + '-' + view + '-edit');
            edittitle.attr('class', 'agent ' + newweight);
        }
    });
});

function deleteConnection(button, vtype, ownerid, currnettypeid) {
    $.actjax(actics.api + 'network/deleteconnection', 'HTML', { groupname: actics.groupname, viewtype: vtype, owner: ownerid, currentnettype: currnettypeid }, null, function(data) {
        var item = $(button).parent().parent();
        $(item).css('display', 'none');

        var popup = $('#layerEditNetwork');
        var view = popup.find('input[name=viewtype]').val();

        if (view == 'connections') {

            var nettypeid = popup.find('input[name=networktypeid]').val();
            var titleBox = $('#' + nettypeid);
            var title = titleBox.text();
            var array = title.split('(');
            var num = array[1].replace(')', '') - 1;
            var newtitle = array[0] + ' (' + num + ') (' + array[2];
            titleBox.text(newtitle);
        }
        else if (view == 'imconnectedto') {
            var titleObject = $('#imconnectedto-title');
            var title = titleObject.text();
            var array = title.split('(');
            var num = parseInt(array[1].replace(')', '')) - 1;
            var newtitle = array[0] + ' (' + num + ')';
            titleObject.text(newtitle);

        } else if (view == 'connectedtome') {
            var titleObject = $('#connectedtome-title');
            var title = titleObject.text();
            var array = title.split('(');
            var num = parseInt(array[1].replace(')', '')) - 1;
            var newtitle = array[0] + '(' + num + ')';
            titleObject.text(newtitle);
        }
    });
}


function changeNetworkType(dropdown, vtype, ownerid, currnettypeid) {

    var newtype = $(dropdown).val();
    var popup = $('#layerEditNetwork');
    var view = popup.find('input[name=viewtype]').val();

    $.actjax(actics.api + 'network/changenetworktype', 'HTML', { groupname: actics.groupname, owner: ownerid, currnettype: currnettypeid, nettypeid: newtype }, null, function(data) {

        if (view == 'connections') {
            var item = $(dropdown).parent().parent();
            $(item).css('display', 'none');

            var nettypeid = popup.find('input[name=networktypeid]').val();
            var titleBox = $('#' + nettypeid);
            var title = titleBox.text();
            var array = title.split('(');
            var num = parseInt(array[1].replace(')', '')) - 1;
            var newtitle = array[0] + ' (' + num + ') (' + array[2];
            titleBox.text(newtitle);

            var newtitleBox = $('#' + newtype);
            var newtitle = newtitleBox.text();
            var newarray = newtitle.split('(');
            var newnum = parseInt(newarray[1].replace(')', '')) + 1;
            var newtitle = newarray[0] + ' (' + newnum + ') (' + newarray[2];
            newtitleBox.text(newtitle);
        }
    });
}

function approveConnection(button, typeid, ownerid, typename) {
    $.actjax(actics.api + 'network/approveconnection', 'HTML', { groupname: actics.groupname, nettypeid: typeid, owner: ownerid }, null, function(data) {
        var titleObject = $('#connectedtome-title');
        var title = titleObject.text();
        var array = title.split('(');
        var num = parseInt(array[1].replace(')', '')) - 1;
        var newtitle = array[0] + '(' + num + ')';
        titleObject.text(newtitle);


        var titleBox = $('#' + typeid);

        if (titleBox != null && titleBox.length > 0) {
            var title = titleBox.text();
            var array = title.split('(');
            var num = array[1].replace(')', '') + 1;
            var newtitle = array[0] + ' (' + num + ') (' + array[2];
            titleBox.text(newtitle);
        } else {
            var title = typename + ' (1) (Medium)';
            var newelement = '<a id="' + typeid + '" href="#" title="' + title + '" >' + title + '</a> <a id="' + typeid + '-connections-edit" class="functionlink mynetwork 2" href="#" onclick="editMyNetwork(\'Connection Type: ' + typename + '\', \'connections\', \'' + typeid + '\', \'' + ownerid + '\');">Edit</a>';
            $('#connectionslist').append('<li><h3>' + newelement + '</h3></li>');
        }

        var item = $(button).parent().parent();
        $(item).css('display', 'none');
    });
};

// ControlInviteForFeedback

$(document).ready(function() {
    $('#layerInviteForFeedback form').ajaxForm({
        dataType: 'json',
        beforeSubmit: function() {
            var name = $('#layerInviteForFeedback').find('#inviteReceiverName').attr('value');
            var email = $('#layerInviteForFeedback').find('#inviteReceiverEmail').attr('value');
            var msg = $('#layerInviteForFeedback').find('#inviteMsg').attr('value');

            if (!name || !msg || !email) {
                alert('Name, email or message fields cannot be empty.');
                return false;
            }

            if (!ActicsValidator.IsValidEmail(email)) {
                alert('Email address \'' + email + '\' is not valid.');
                return false;
            }
        },
        success: function() {
            $('#layerInviteForFeedback').hideLayer();
            alert('The invitation has been sent.');
        }
    });

});

$(document).ready(function() {
    $('#subheader').find('ul.headernav > li').hover(function() {


        var submenu = $(this).find('ul.submenu:first');
        var link = $(this).find('a:first');

        var colorLeft = link.css('border-left-color');
        var colorRight = link.css('border-right-color');
        var colorTop = link.css('border-top-color');
        var colorBg = link.css('background-color');
        var height = link.css('height');
        var colorText = link.css('color');

        var isVisible = submenu.data('isVisible');

        submenu.data('hover-border-left-color', colorLeft);
        submenu.data('hover-border-right-color', colorRight);
        submenu.data('hover-border-top-color', colorTop);
        submenu.data('hover-background-color', colorBg);
        submenu.data('hover-height', height);
        submenu.data('hover-color-text', colorText);


        if (!isVisible) {
            submenu.fadeIn('fast');
            submenu.data('isVisible', true);

        }
    },
     function() {
         var submenu = $(this).find('ul.submenu');
         var isVisible = submenu.data('isVisible');
         if (isVisible) {
             submenu.fadeOut('fast');
             submenu.data('isVisible', false);
         }
     }
    );

    $('#subheader').find('ul.headernav > li > ul.submenu').hover(function() {
        var submenu = $(this);
        var link = $(this).parent().find('a:first');

        var hoverColorLeft = submenu.data('hover-border-left-color');
        var hoverColorRight = submenu.data('hover-border-right-color');
        var hoverColorTop = submenu.data('hover-border-top-color');
        var hoverColorBg = submenu.data('hover-background-color');
        var hoverHeight = submenu.data('hover-height');
        var hoverColorText = submenu.data('hover-color-text');

        link.css('border-left-color', hoverColorLeft);
        link.css('border-right-color', hoverColorRight);
        link.css('border-top-color', hoverColorTop);
        link.css('background-color', hoverColorBg);
        link.css('height', hoverHeight);
        link.css('color', hoverColorText);
    },
    function() {
        var link = $(this).parent().find('a:first');
        link.attr('style', '');
    }
   );

    $('#subheader').find('ul.headernav > li > ul.submenu > ul.submenuchild').hover(function() {
        var submenu = $(this);
        var link = $(this).parent().find('a:first');

        var hoverColorLeft = submenu.data('hover-border-left-color');
        var hoverColorRight = submenu.data('hover-border-right-color');
        var hoverColorTop = submenu.data('hover-border-top-color');
        var hoverColorBg = submenu.data('hover-background-color');
        var hoverHeight = submenu.data('hover-height');
        var hoverColorText = submenu.data('hover-color-text');

        link.css('border-left-color', hoverColorLeft);
        link.css('border-right-color', hoverColorRight);
        link.css('border-top-color', hoverColorTop);
        link.css('background-color', hoverColorBg);
        link.css('height', hoverHeight);
        link.css('color', hoverColorText);
    },
    function() {
        var link = $(this).parent().find('a:first');
        link.attr('style', '');
    }
   );

    $('#subheader').find('ul.headernav > li > ul.submenu > li').hover(function() {

        var submenu = $(this).find('ul.submenuchild');
        var link = $(this).find('a:first');

        var colorLeft = link.css('border-left-color');
        var colorRight = link.css('border-right-color');
        var colorTop = link.css('border-top-color');
        var colorBg = link.css('background-color');
        var height = link.css('height');
        var colorText = link.css('color');
        var width = $(this).parent().width();
        var height = $(this).height() + 1;
        var zIndex = $(this).parent().css('z-index');


        var isVisible = submenu.data('isVisible');

        submenu.data('hover-border-left-color', colorLeft);
        submenu.data('hover-border-right-color', colorRight);
        submenu.data('hover-border-top-color', colorTop);
        submenu.data('hover-background-color', colorBg);
        submenu.data('hover-height', height);
        submenu.data('hover-color-text', colorText);

        if (!isVisible) {
            submenu.fadeIn('fast');
            submenu.css('margin-left', width);
            submenu.css('margin-top', -height);
            submenu.css('z-index', zIndex);
            submenu.data('isVisible', true);
        }
    }
      ,
      function() {
          var submenu = $(this).find('ul.submenuchild');
          var isVisible = submenu.data('isVisible');

          if (isVisible) {
              submenu.fadeOut('fast');
              submenu.data('isVisible', false);
          }
      }
     );

});

var WizardControl = {
    loadNext: function(controlid, divout, divin) {
        var wizard = $('#' + controlid);
        wizard.find("." + divout).hide();
        wizard.find("." + divin).fadeIn("fast");
    }
}

$(document).ready(function() {
    $('#addvaluedef').click(function() {
        var alldeflayer = $('#valuealldefs');
        var textareas = $(alldeflayer).find('textarea');
        var nextIndex = $(textareas).length + 2;

        var removescript = '$(\'#lbaelvalueDef' + nextIndex + '\').remove();$(\'#txtvaluedef' + nextIndex + '\').remove();';

        var title = 'Additional Definition';

        var newhtml = '<label class="useraddeddef" id="labelvalueDef' + nextIndex + '" for="newvaluedescription">' + title + '<a href="#" class="removevaluedef" onclick="' + removescript + '">Remove</a></label><textarea class="useraddeddef" id="txtvaluedef' + nextIndex + '" rows="80" cols="120" style="width: 420px; height: 120px" tabindex="' + nextIndex + '" name="newvaluedescription"></textarea>';

        alldeflayer.append(newhtml);

        return false;
    });
});


$(document).ready(function() {

    var showIt = !actics.helpisread;

    if (showIt) {
        $('#layerGetHelp').showLayer();
        $('#layerGetHelp').bind('onHideLayer', function() { $.actjax(actics.api + 'agents/sethelpisread', 'JSON', { groupname: actics.groupname }, null, null); });
    }
});

$(document).ready(function() {
    $('.fieldwithinfobox').focus(function() {

        $('.fieldinfobox').each(function(index, item) {
            $(item).css('display', 'none');
        });

        var id = $(this).attr('id') + "_infofieldbox";
        $('#' + id).css('display', 'block');

    });

    $('.fieldwithinfobox.focus').focus();
});

// ComboBox
function txbkd() {
    var p = window.event.srcElement.cbx.lst;

    if (window.event.keyCode == 9) {
        phide(p);
        return true;
    }

    if (window.event.keyCode == 13) {
        if (p.selectedItem != null) {
            p.cbx.txb.value = p.selectedItem.innerText;
            //itemDeselect(p.selectedItem);
            phide(p);
            window.event.returnValue = false;
            window.event.srcElement.select();

            __combobox_invokepostback(p.cbx);

            return false;
        }
    }

    if (window.event.keyCode == 40 || window.event.keyCode == 38) {
        if (p.selectedItem != null && p.style.visibility == 'visible') {
            var index = p.selectedIndex;
            itemDeselect(p.selectedItem);
            var dir = window.event.keyCode == 40 ? 1 : -1;
            if (index + dir >= 0 && index + dir < p.childNodes.length) {
                itemSelect(p.childNodes[index + dir]);
            }
        }
        else {
            p.style.visibility = 'visible';
            if (0 < p.childNodes.length) {
                itemSelect(p.childNodes[0]);
            }
        }
    }
    else if (window.event.keyCode == 27) {
        phide(p);
    }
}

function itemFocus() {
}

function getSelectedItem(comboBox) {
    var cbx = _cbx(comboBox);
    var li = cbx.lst.childNodes;
    for (var i = 0; i < li.length; i++)
        if (li[i].isSelected) return li[i];
}

function txbku() {
    var ev = window.event;
    var e = window.event.srcElement;
    var c = e.cbx;
    var p = c.lst;
    var txt = e.value;
    if (ev.keyCode != 38 && ev.keyCode != 40 && e.keyCode != 37 && ev.keyCode != 39 && ev.keyCode != 9 && ev.keyCode != 13) {
        itemDeselect(p.selectedItem);
        if (txt != '' && e.cbx.autocomplete) {
            var j = 0;
            if (c.cases) {
                for (var i = 0; i < p.items.length; i++) if (p.items[i].indexOf(txt) == 0) j++;
            }
            else {
                for (var i = 0; i < p.items.length; i++) if (p.items[i].toLowerCase().indexOf(txt.toLowerCase()) == 0) j++;
            }

            var selectedList = new Array(j);

            j = 0;
            if (c.cases) {
                for (var i = 0; i < p.items.length; i++)
                    if (p.items[i].indexOf(txt) == 0)
                    selectedList[j++] = p.items[i];
            }
            else {
                for (var i = 0; i < p.items.length; i++)
                    if (p.items[i].toLowerCase().indexOf(txt.toLowerCase()) == 0)
                    selectedList[j++] = p.items[i];
            }

            var fireList = (j != 0 ? selectedList : null);

            popItems(e.cbx, fireList);

            // set the textbox value & selection
            if (((ev.keyCode >= 48 && ev.keyCode <= 57) || (ev.keyCode >= 65 && ev.keyCode <= 90)) && j != 0) {
                for (var i = 0; i < p.items.length; i++) {
                    if ((!c.cases && ((p.items[i].toLowerCase().indexOf(txt.toLowerCase()) == 0))) || (p.items[i].indexOf(txt) == 0)) {
                        e.value = p.items[i];
                        var tr = e.createTextRange();
                        tr.moveStart('character', txt.length);
                        tr.select();
                        break;
                    }
                }
            }
        }
        else {
            popItems(e.cbx, null);
        }
    }
}

function txblur() {
    var e = window.event.srcElement;
    var p = e.cbx.lst;
    var b = e.cbx.btn;
    if (!p.ison && !b.ison) {
        phide(p);
        //p.style.visibility = 'hidden';
    } //itemDeselect(p.selectedItem);
    //itemsDeselect(p);
}

function pmr() {
    var d = window.event.srcElement;
    d.ison = true;
}

function pmt() {
    var d = window.event.srcElement;
    d.ison = false;
}

function mr() {
    itemSelect(window.event.srcElement);
}

function itemSelect(i) {
    if (i != null) {
        i.style.backgroundColor = 'buttonshadow';
        i.style.color = 'window';

        i.isSelected = true;
        i.parentElement.cbx.lst.ison = true;
        i.parentElement.selectedItem = i;
        i.parentElement.selectedIndex = i.itemIndex;
    }
}

function itemDeselect(i) {
    if (i != null) {
        i.style.backgroundColor = 'window';
        i.style.color = 'windowtext';

        i.isSelected = false;
        i.parentElement.cbx.lst.ison = false;
        i.parentElement.selectedItem = null;
        i.parentElement.selectedIndex = -1;
    }
}

function itemsDeselect(p) {
    for (var i = 0; i < p.subitems.length; i++) {
        itemDeselect(p.childNodes[i]);
    }
}

function phide(p) {
    if (p.style.visibility == 'visible')
        p.style.visibility = 'hidden';
    itemsDeselect(p);
}

function mt() {
    itemDeselect(window.event.srcElement);
}

function getRealIndex(comboBox) {
    var l = comboBox.lst;
    var t = comboBox.txb;

    for (i = 0; i < l.items.length; i++)
        if (l.items[i] == t.value)
        return i;
    return -1;
}

function mc() {
    var d = window.event.srcElement;
    var l = d.parentElement;
    var c = l.cbx;
    var t = c.txb;

    t.value = d.innerText;
    if (c.autopostback) {
        __combobox_postback(c, getRealIndex(c));
    }
    else {
        phide(l);
        t.focus();
        t.select();
    }
}

function _cbx(comboBox) {
    return document.getElementById(comboBox);
}

function clearlst(lst) {
    lst.innerHTML = '';
}

function popItems(comboBox, list, itin) {
    var p = comboBox.lst;

    if (itin) {
        p.items = list;
    }
    p.subitems = (list == null ? p.items : list);

    clearlst(p);

    for (var c = 0; c < p.subitems.length; c++) {
        var ps = p.style;
        var i = document.createElement('div');

        i.id = 'item' + p.childNodes.length;

        //if (itin)
        i.itemIndex = c;

        i.style.cursor = 'default';
        i.style.whitespace = 'default';


        i.bgcolor = '#000000';
        i.innerText = p.subitems[c];

        i.style.fontFamily = comboBox.txb.style.fontFamily;
        i.style.fontSize = comboBox.txb.style.fontSize;

        i.style.width = isNaN(parseInt(comboBox.txb.style.width, 10)) ? '200px' : comboBox.txb.style.width;
        //i.style.height = '24px';

        i.style.verticalAlign = 'middle';

        //i.innerHTML = "<table><tr><td valign = 'center'>" + p.subitems[c] + "</td></tr></table>";

        i.onmouseover = mr;
        i.onmouseout = mt;
        i.onclick = mc;

        p.appendChild(i);
    }
}

function pstyle(p) {
    var ps = p.style;
    ps.position = 'absolute';
    ps.width = p.cbx.style.width;
    var iHeight = p.cbx.offsetHeight - 5;
    ps.height = (p.maxDropDownItems * iHeight) + 2 + 'px';

    ps.top = p.cbx.style.position != 'absolute' ? getElementPosition(p.cbx).top + p.cbx.offsetHeight + 2 : p.cbx.offsetHeight + 1; //+ 'px';

    ps.border = '1px solid #000000';
    ps.backgroundColor = '#ffffff';
}

function getElementPosition(el) {
    var c = el, l = 0, t = 0;
    for (; c.offsetParent.offsetParent; c = c.offsetParent) {
        l += c.offsetLeft;
        t += c.offsetTop;
    }
    return { left: l, top: t };
}

function flip() {
    var e = window.event.srcElement;
    var t = e.cbx.txb;
    var p = e.cbx.lst;
    var ps = p.style;

    if (ps.visibility == 'hidden') {
        ps.visibility = 'visible';
        t.focus();
    }
    else {
        phide(p);
    }
}

function __combobox_invokepostback(comboBox) {
    if (comboBox.autopostback)
        __combobox_postback(comboBox, getRealIndex(comboBox));
}

function initCombo(comboBox, _items, apb, autocomplete, cases, maxDropDownItems) {
    var e = document.getElementById(comboBox);
    e.lst = e.childNodes[0];
    e.txb = e.childNodes[1].rows[0].cells[0].childNodes[0];
    e.btn = e.childNodes[1].rows[0].cells[1];
    e.btn.cbx = e.lst.cbx = e.txb.cbx = e;
    e.lst.maxDropDownItems = maxDropDownItems;

    if (e.autocomplete = autocomplete)
        e.cases = cases;

    e.autopostback = apb;

    pstyle(e.lst);

    popItems(e, _items, true);
}
