/*
 * VERSION June 5, 2008
 */


/*
 * jQuery 1.2.3 - 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-02-06 00:21:25 -0500 (Wed, 06 Feb 2008) $
 * $Rev: 4663 $
 */
 
(function(){if(window.jQuery)var _jQuery=window.jQuery;var jQuery=window.jQuery=function(selector,context){return new jQuery.prototype.init(selector,context);};if(window.$)var _$=window.$;window.$=jQuery;var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/;var isSimple=/^.[^:#\[\.]*$/;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(selector.nodeType){this[0]=selector;this.length=1;return this;}else if(typeof selector=="string"){var match=quickExpr.exec(selector);if(match&&(match[1]||!context)){if(match[1])selector=jQuery.clean([match[1]],context);else{var elem=document.getElementById(match[3]);if(elem)if(elem.id!=match[3])return jQuery().find(selector);else{this[0]=elem;this.length=1;return this;}else selector=[];}}else return new jQuery(context).find(selector);}else if(jQuery.isFunction(selector))return new jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(selector.constructor==Array&&selector||(selector.jquery||selector.length&&selector!=window&&!selector.nodeType&&selector[0]!=undefined&&selector[0].nodeType)&&jQuery.makeArray(selector)||[selector]);},jquery:"1.2.3",size:function(){return this.length;},length:0,get:function(num){return num==undefined?jQuery.makeArray(this):this[num];},pushStack:function(elems){var ret=jQuery(elems);ret.prevObject=this;return ret;},setArray:function(elems){this.length=0;Array.prototype.push.apply(this,elems);return this;},each:function(callback,args){return jQuery.each(this,callback,args);},index:function(elem){var ret=-1;this.each(function(i){if(this==elem)ret=i;});return ret;},attr:function(name,value,type){var options=name;if(name.constructor==String)if(value==undefined)return this.length&&jQuery[type||"attr"](this[0],name)||undefined;else{options={};options[name]=value;}return this.each(function(i){for(name in options)jQuery.attr(type?this.style:this,name,jQuery.prop(this,options[name],type,i,name));});},css:function(key,value){if((key=='width'||key=='height')&&parseFloat(value)<0)value=undefined;return this.attr(key,value,"curCSS");},text:function(text){if(typeof text!="object"&&text!=null)return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(text));var ret="";jQuery.each(text||this,function(){jQuery.each(this.childNodes,function(){if(this.nodeType!=8)ret+=this.nodeType!=1?this.nodeValue:jQuery.fn.text([this]);});});return ret;},wrapAll:function(html){if(this[0])jQuery(html,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var elem=this;while(elem.firstChild)elem=elem.firstChild;return elem;}).append(this);return this;},wrapInner:function(html){return this.each(function(){jQuery(this).contents().wrapAll(html);});},wrap:function(html){return this.each(function(){jQuery(this).wrapAll(html);});},append:function(){return this.domManip(arguments,true,false,function(elem){if(this.nodeType==1)this.appendChild(elem);});},prepend:function(){return this.domManip(arguments,true,true,function(elem){if(this.nodeType==1)this.insertBefore(elem,this.firstChild);});},before:function(){return this.domManip(arguments,false,false,function(elem){this.parentNode.insertBefore(elem,this);});},after:function(){return this.domManip(arguments,false,true,function(elem){this.parentNode.insertBefore(elem,this.nextSibling);});},end:function(){return this.prevObject||jQuery([]);},find:function(selector){var elems=jQuery.map(this,function(elem){return jQuery.find(selector,elem);});return this.pushStack(/[^+>] [^+>]/.test(selector)||selector.indexOf("..")>-1?jQuery.unique(elems):elems);},clone:function(events){var ret=this.map(function(){if(jQuery.browser.msie&&!jQuery.isXMLDoc(this)){var clone=this.cloneNode(true),container=document.createElement("div");container.appendChild(clone);return jQuery.clean([container.innerHTML])[0];}else return this.cloneNode(true);});var clone=ret.find("*").andSelf().each(function(){if(this[expando]!=undefined)this[expando]=null;});if(events===true)this.find("*").andSelf().each(function(i){if(this.nodeType==3)return;var events=jQuery.data(this,"events");for(var type in events)for(var handler in events[type])jQuery.event.add(clone[i],type,events[type][handler],events[type][handler].data);});return ret;},filter:function(selector){return this.pushStack(jQuery.isFunction(selector)&&jQuery.grep(this,function(elem,i){return selector.call(elem,i);})||jQuery.multiFilter(selector,this));},not:function(selector){if(selector.constructor==String)if(isSimple.test(selector))return this.pushStack(jQuery.multiFilter(selector,this,true));else selector=jQuery.multiFilter(selector,this);var isArrayLike=selector.length&&selector[selector.length-1]!==undefined&&!selector.nodeType;return this.filter(function(){return isArrayLike?jQuery.inArray(this,selector)<0:this!=selector;});},add:function(selector){return!selector?this:this.pushStack(jQuery.merge(this.get(),selector.constructor==String?jQuery(selector).get():selector.length!=undefined&&(!selector.nodeName||jQuery.nodeName(selector,"form"))?selector:[selector]));},is:function(selector){return selector?jQuery.multiFilter(selector,this).length>0:false;},hasClass:function(selector){return this.is("."+selector);},val:function(value){if(value==undefined){if(this.length){var elem=this[0];if(jQuery.nodeName(elem,"select")){var index=elem.selectedIndex,values=[],options=elem.options,one=elem.type=="select-one";if(index<0)return null;for(var i=one?index:0,max=one?index+1:options.length;i<max;i++){var option=options[i];if(option.selected){value=jQuery.browser.msie&&!option.attributes.value.specified?option.text:option.value;if(one)return value;values.push(value);}}return values;}else return(this[0].value||"").replace(/\r/g,"");}return undefined;}return this.each(function(){if(this.nodeType!=1)return;if(value.constructor==Array&&/radio|checkbox/.test(this.type))this.checked=(jQuery.inArray(this.value,value)>=0||jQuery.inArray(this.name,value)>=0);else if(jQuery.nodeName(this,"select")){var values=value.constructor==Array?value:[value];jQuery("option",this).each(function(){this.selected=(jQuery.inArray(this.value,values)>=0||jQuery.inArray(this.text,values)>=0);});if(!values.length)this.selectedIndex=-1;}else this.value=value;});},html:function(value){return value==undefined?(this.length?this[0].innerHTML:null):this.empty().append(value);},replaceWith:function(value){return this.after(value).remove();},eq:function(i){return this.slice(i,i+1);},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem);}));},andSelf:function(){return this.add(this.prevObject);},data:function(key,value){var parts=key.split(".");parts[1]=parts[1]?"."+parts[1]:"";if(value==null){var data=this.triggerHandler("getData"+parts[1]+"!",[parts[0]]);if(data==undefined&&this.length)data=jQuery.data(this[0],key);return data==null&&parts[1]?this.data(parts[0]):data;}else return this.trigger("setData"+parts[1]+"!",[parts[0],value]).each(function(){jQuery.data(this,key,value);});},removeData:function(key){return this.each(function(){jQuery.removeData(this,key);});},domManip:function(args,table,reverse,callback){var clone=this.length>1,elems;return this.each(function(){if(!elems){elems=jQuery.clean(args,this.ownerDocument);if(reverse)elems.reverse();}var obj=this;if(table&&jQuery.nodeName(this,"table")&&jQuery.nodeName(elems[0],"tr"))obj=this.getElementsByTagName("tbody")[0]||this.appendChild(this.ownerDocument.createElement("tbody"));var scripts=jQuery([]);jQuery.each(elems,function(){var elem=clone?jQuery(this).clone(true)[0]:this;if(jQuery.nodeName(elem,"script")){scripts=scripts.add(elem);}else{if(elem.nodeType==1)scripts=scripts.add(jQuery("script",elem).remove());callback.call(obj,elem);}});scripts.each(evalScript);});}};jQuery.prototype.init.prototype=jQuery.prototype;function evalScript(i,elem){if(elem.src)jQuery.ajax({url:elem.src,async:false,dataType:"script"});else
jQuery.globalEval(elem.text||elem.textContent||elem.innerHTML||"");if(elem.parentNode)elem.parentNode.removeChild(elem);}jQuery.extend=jQuery.fn.extend=function(){var target=arguments[0]||{},i=1,length=arguments.length,deep=false,options;if(target.constructor==Boolean){deep=target;target=arguments[1]||{};i=2;}if(typeof target!="object"&&typeof target!="function")target={};if(length==1){target=this;i=0;}for(;i<length;i++)if((options=arguments[i])!=null)for(var name in options){if(target===options[name])continue;if(deep&&options[name]&&typeof options[name]=="object"&&target[name]&&!options[name].nodeType)target[name]=jQuery.extend(target[name],options[name]);else if(options[name]!=undefined)target[name]=options[name];}return target;};var expando="jQuery"+(new Date()).getTime(),uuid=0,windowData={};var exclude=/z-?index|font-?weight|opacity|zoom|line-?height/i;jQuery.extend({noConflict:function(deep){window.$=_$;if(deep)window.jQuery=_jQuery;return jQuery;},isFunction:function(fn){return!!fn&&typeof fn!="string"&&!fn.nodeName&&fn.constructor!=Array&&/function/i.test(fn+"");},isXMLDoc:function(elem){return elem.documentElement&&!elem.body||elem.tagName&&elem.ownerDocument&&!elem.ownerDocument.body;},globalEval:function(data){data=jQuery.trim(data);if(data){var head=document.getElementsByTagName("head")[0]||document.documentElement,script=document.createElement("script");script.type="text/javascript";if(jQuery.browser.msie)script.text=data;else
script.appendChild(document.createTextNode(data));head.appendChild(script);head.removeChild(script);}},nodeName:function(elem,name){return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();},cache:{},data:function(elem,name,data){elem=elem==window?windowData:elem;var id=elem[expando];if(!id)id=elem[expando]=++uuid;if(name&&!jQuery.cache[id])jQuery.cache[id]={};if(data!=undefined)jQuery.cache[id][name]=data;return name?jQuery.cache[id][name]:id;},removeData:function(elem,name){elem=elem==window?windowData:elem;var id=elem[expando];if(name){if(jQuery.cache[id]){delete jQuery.cache[id][name];name="";for(name in jQuery.cache[id])break;if(!name)jQuery.removeData(elem);}}else{try{delete elem[expando];}catch(e){if(elem.removeAttribute)elem.removeAttribute(expando);}delete jQuery.cache[id];}},each:function(object,callback,args){if(args){if(object.length==undefined){for(var name in object)if(callback.apply(object[name],args)===false)break;}else
for(var i=0,length=object.length;i<length;i++)if(callback.apply(object[i],args)===false)break;}else{if(object.length==undefined){for(var name in object)if(callback.call(object[name],name,object[name])===false)break;}else
for(var i=0,length=object.length,value=object[0];i<length&&callback.call(value,i,value)!==false;value=object[++i]){}}return object;},prop:function(elem,value,type,i,name){if(jQuery.isFunction(value))value=value.call(elem,i);return value&&value.constructor==Number&&type=="curCSS"&&!exclude.test(name)?value+"px":value;},className:{add:function(elem,classNames){jQuery.each((classNames||"").split(/\s+/),function(i,className){if(elem.nodeType==1&&!jQuery.className.has(elem.className,className))elem.className+=(elem.className?" ":"")+className;});},remove:function(elem,classNames){if(elem.nodeType==1)elem.className=classNames!=undefined?jQuery.grep(elem.className.split(/\s+/),function(className){return!jQuery.className.has(classNames,className);}).join(" "):"";},has:function(elem,className){return jQuery.inArray(className,(elem.className||elem).toString().split(/\s+/))>-1;}},swap:function(elem,options,callback){var old={};for(var name in options){old[name]=elem.style[name];elem.style[name]=options[name];}callback.call(elem);for(var name in options)elem.style[name]=old[name];},css:function(elem,name,force){if(name=="width"||name=="height"){var val,props={position:"absolute",visibility:"hidden",display:"block"},which=name=="width"?["Left","Right"]:["Top","Bottom"];function getWH(){val=name=="width"?elem.offsetWidth:elem.offsetHeight;var padding=0,border=0;jQuery.each(which,function(){padding+=parseFloat(jQuery.curCSS(elem,"padding"+this,true))||0;border+=parseFloat(jQuery.curCSS(elem,"border"+this+"Width",true))||0;});val-=Math.round(padding+border);}if(jQuery(elem).is(":visible"))getWH();else
jQuery.swap(elem,props,getWH);return Math.max(0,val);}return jQuery.curCSS(elem,name,force);},curCSS:function(elem,name,force){var ret;function color(elem){if(!jQuery.browser.safari)return false;var ret=document.defaultView.getComputedStyle(elem,null);return!ret||ret.getPropertyValue("color")=="";}if(name=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(elem.style,"opacity");return ret==""?"1":ret;}if(jQuery.browser.opera&&name=="display"){var save=elem.style.outline;elem.style.outline="0 solid black";elem.style.outline=save;}if(name.match(/float/i))name=styleFloat;if(!force&&elem.style&&elem.style[name])ret=elem.style[name];else if(document.defaultView&&document.defaultView.getComputedStyle){if(name.match(/float/i))name="float";name=name.replace(/([A-Z])/g,"-$1").toLowerCase();var getComputedStyle=document.defaultView.getComputedStyle(elem,null);if(getComputedStyle&&!color(elem))ret=getComputedStyle.getPropertyValue(name);else{var swap=[],stack=[];for(var a=elem;a&&color(a);a=a.parentNode)stack.unshift(a);for(var i=0;i<stack.length;i++)if(color(stack[i])){swap[i]=stack[i].style.display;stack[i].style.display="block";}ret=name=="display"&&swap[stack.length-1]!=null?"none":(getComputedStyle&&getComputedStyle.getPropertyValue(name))||"";for(var i=0;i<swap.length;i++)if(swap[i]!=null)stack[i].style.display=swap[i];}if(name=="opacity"&&ret=="")ret="1";}else if(elem.currentStyle){var camelCase=name.replace(/\-(\w)/g,function(all,letter){return letter.toUpperCase();});ret=elem.currentStyle[name]||elem.currentStyle[camelCase];if(!/^\d+(px)?$/i.test(ret)&&/^\d/.test(ret)){var style=elem.style.left,runtimeStyle=elem.runtimeStyle.left;elem.runtimeStyle.left=elem.currentStyle.left;elem.style.left=ret||0;ret=elem.style.pixelLeft+"px";elem.style.left=style;elem.runtimeStyle.left=runtimeStyle;}}return ret;},clean:function(elems,context){var ret=[];context=context||document;if(typeof context.createElement=='undefined')context=context.ownerDocument||context[0]&&context[0].ownerDocument||document;jQuery.each(elems,function(i,elem){if(!elem)return;if(elem.constructor==Number)elem=elem.toString();if(typeof elem=="string"){elem=elem.replace(/(<(\w+)[^>]*?)\/>/g,function(all,front,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?all:front+"></"+tag+">";});var tags=jQuery.trim(elem).toLowerCase(),div=context.createElement("div");var wrap=!tags.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!tags.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||tags.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!tags.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!tags.indexOf("<td")||!tags.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!tags.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||jQuery.browser.msie&&[1,"div<div>","</div>"]||[0,"",""];div.innerHTML=wrap[1]+elem+wrap[2];while(wrap[0]--)div=div.lastChild;if(jQuery.browser.msie){var tbody=!tags.indexOf("<table")&&tags.indexOf("<tbody")<0?div.firstChild&&div.firstChild.childNodes:wrap[1]=="<table>"&&tags.indexOf("<tbody")<0?div.childNodes:[];for(var j=tbody.length-1;j>=0;--j)if(jQuery.nodeName(tbody[j],"tbody")&&!tbody[j].childNodes.length)tbody[j].parentNode.removeChild(tbody[j]);if(/^\s/.test(elem))div.insertBefore(context.createTextNode(elem.match(/^\s*/)[0]),div.firstChild);}elem=jQuery.makeArray(div.childNodes);}if(elem.length===0&&(!jQuery.nodeName(elem,"form")&&!jQuery.nodeName(elem,"select")))return;if(elem[0]==undefined||jQuery.nodeName(elem,"form")||elem.options)ret.push(elem);else
ret=jQuery.merge(ret,elem);});return ret;},attr:function(elem,name,value){if(!elem||elem.nodeType==3||elem.nodeType==8)return undefined;var fix=jQuery.isXMLDoc(elem)?{}:jQuery.props;if(name=="selected"&&jQuery.browser.safari)elem.parentNode.selectedIndex;if(fix[name]){if(value!=undefined)elem[fix[name]]=value;return elem[fix[name]];}else if(jQuery.browser.msie&&name=="style")return jQuery.attr(elem.style,"cssText",value);else if(value==undefined&&jQuery.browser.msie&&jQuery.nodeName(elem,"form")&&(name=="action"||name=="method"))return elem.getAttributeNode(name).nodeValue;else if(elem.tagName){if(value!=undefined){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)throw"type property can't be changed";elem.setAttribute(name,""+value);}if(jQuery.browser.msie&&/href|src/.test(name)&&!jQuery.isXMLDoc(elem))return elem.getAttribute(name,2);return elem.getAttribute(name);}else{if(name=="opacity"&&jQuery.browser.msie){if(value!=undefined){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseFloat(value).toString()=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter&&elem.filter.indexOf("opacity=")>=0?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100).toString():"";}name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});if(value!='NaNpx'&&value!=undefined)elem[name]=value;return elem[name];}},trim:function(text){return(text||"").replace(/^\s+|\s+$/g,"");},makeArray:function(array){var ret=[];if(typeof array!="array")for(var i=0,length=array.length;i<length;i++)ret.push(array[i]);else
ret=array.slice(0);return ret;},inArray:function(elem,array){for(var i=0,length=array.length;i<length;i++)if(array[i]==elem)return i;return-1;},merge:function(first,second){if(jQuery.browser.msie){for(var i=0;second[i];i++)if(second[i].nodeType!=8)first.push(second[i]);}else
for(var i=0;second[i];i++)first.push(second[i]);return first;},unique:function(array){var ret=[],done={};try{for(var i=0,length=array.length;i<length;i++){var id=jQuery.data(array[i]);if(!done[id]){done[id]=true;ret.push(array[i]);}}}catch(e){ret=array;}return ret;},grep:function(elems,callback,inv){var ret=[];for(var i=0,length=elems.length;i<length;i++)if(!inv&&callback(elems[i],i)||inv&&!callback(elems[i],i))ret.push(elems[i]);return ret;},map:function(elems,callback){var ret=[];for(var i=0,length=elems.length;i<length;i++){var value=callback(elems[i],i);if(value!==null&&value!=undefined){if(value.constructor!=Array)value=[value];ret=ret.concat(value);}}return ret;}});var userAgent=navigator.userAgent.toLowerCase();jQuery.browser={version:(userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[])[1],safari:/webkit/.test(userAgent),opera:/opera/.test(userAgent),msie:/msie/.test(userAgent)&&!/opera/.test(userAgent),mozilla:/mozilla/.test(userAgent)&&!/(compatible|webkit)/.test(userAgent)};var styleFloat=jQuery.browser.msie?"styleFloat":"cssFloat";jQuery.extend({boxModel:!jQuery.browser.msie||document.compatMode=="CSS1Compat",props:{"for":"htmlFor","class":"className","float":styleFloat,cssFloat:styleFloat,styleFloat:styleFloat,innerHTML:"innerHTML",className:"className",value:"value",disabled:"disabled",checked:"checked",readonly:"readOnly",selected:"selected",maxlength:"maxLength",selectedIndex:"selectedIndex",defaultValue:"defaultValue",tagName:"tagName",nodeName:"nodeName"}});jQuery.each({parent:function(elem){return elem.parentNode;},parents:function(elem){return jQuery.dir(elem,"parentNode");},next:function(elem){return jQuery.nth(elem,2,"nextSibling");},prev:function(elem){return jQuery.nth(elem,2,"previousSibling");},nextAll:function(elem){return jQuery.dir(elem,"nextSibling");},prevAll:function(elem){return jQuery.dir(elem,"previousSibling");},siblings:function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},children:function(elem){return jQuery.sibling(elem.firstChild);},contents:function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}},function(name,fn){jQuery.fn[name]=function(selector){var ret=jQuery.map(this,fn);if(selector&&typeof selector=="string")ret=jQuery.multiFilter(selector,ret);return this.pushStack(jQuery.unique(ret));};});jQuery.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(name,original){jQuery.fn[name]=function(){var args=arguments;return this.each(function(){for(var i=0,length=args.length;i<length;i++)jQuery(args[i])[original](this);});};});jQuery.each({removeAttr:function(name){jQuery.attr(this,name,"");if(this.nodeType==1)this.removeAttribute(name);},addClass:function(classNames){jQuery.className.add(this,classNames);},removeClass:function(classNames){jQuery.className.remove(this,classNames);},toggleClass:function(classNames){jQuery.className[jQuery.className.has(this,classNames)?"remove":"add"](this,classNames);},remove:function(selector){if(!selector||jQuery.filter(selector,[this]).r.length){jQuery("*",this).add(this).each(function(){jQuery.event.remove(this);jQuery.removeData(this);});if(this.parentNode)this.parentNode.removeChild(this);}},empty:function(){jQuery(">*",this).remove();while(this.firstChild)this.removeChild(this.firstChild);}},function(name,fn){jQuery.fn[name]=function(){return this.each(fn,arguments);};});jQuery.each(["Height","Width"],function(i,name){var type=name.toLowerCase();jQuery.fn[type]=function(size){return this[0]==window?jQuery.browser.opera&&document.body["client"+name]||jQuery.browser.safari&&window["inner"+name]||document.compatMode=="CSS1Compat"&&document.documentElement["client"+name]||document.body["client"+name]:this[0]==document?Math.max(Math.max(document.body["scroll"+name],document.documentElement["scroll"+name]),Math.max(document.body["offset"+name],document.documentElement["offset"+name])):size==undefined?(this.length?jQuery.css(this[0],type):null):this.css(type,size.constructor==String?size:size+"px");};});var chars=jQuery.browser.safari&&parseInt(jQuery.browser.version)<417?"(?:[\\w*_-]|\\\\.)":"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",quickChild=new RegExp("^>\\s*("+chars+"+)"),quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)"),quickClass=new RegExp("^([#.]?)("+chars+"*)");jQuery.extend({expr:{"":function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},"#":function(a,i,m){return a.getAttribute("id")==m[2];},":":{lt:function(a,i,m){return i<m[3]-0;},gt:function(a,i,m){return i>m[3]-0;},nth:function(a,i,m){return m[3]-0==i;},eq:function(a,i,m){return m[3]-0==i;},first:function(a,i){return i==0;},last:function(a,i,m,r){return i==r.length-1;},even:function(a,i){return i%2==0;},odd:function(a,i){return i%2;},"first-child":function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},"last-child":function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},"only-child":function(a){return!jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},parent:function(a){return a.firstChild;},empty:function(a){return!a.firstChild;},contains:function(a,i,m){return(a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},visible:function(a){return"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},hidden:function(a){return"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},enabled:function(a){return!a.disabled;},disabled:function(a){return a.disabled;},checked:function(a){return a.checked;},selected:function(a){return a.selected||jQuery.attr(a,"selected");},text:function(a){return"text"==a.type;},radio:function(a){return"radio"==a.type;},checkbox:function(a){return"checkbox"==a.type;},file:function(a){return"file"==a.type;},password:function(a){return"password"==a.type;},submit:function(a){return"submit"==a.type;},image:function(a){return"image"==a.type;},reset:function(a){return"reset"==a.type;},button:function(a){return"button"==a.type||jQuery.nodeName(a,"button");},input:function(a){return/input|select|textarea|button/i.test(a.nodeName);},has:function(a,i,m){return jQuery.find(m[3],a).length;},header:function(a){return/h\d/i.test(a.nodeName);},animated:function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+chars+"+)")],multiFilter:function(expr,elems,not){var old,cur=[];while(expr&&expr!=old){old=expr;var f=jQuery.filter(expr,elems,not);expr=f.t.replace(/^\s*,\s*/,"");cur=not?elems=f.r:jQuery.merge(cur,f.r);}return cur;},find:function(t,context){if(typeof t!="string")return[t];if(context&&context.nodeType!=1&&context.nodeType!=9)return[];context=context||document;var ret=[context],done=[],last,nodeName;while(t&&last!=t){var r=[];last=t;t=jQuery.trim(t);var foundToken=false;var re=quickChild;var m=re.exec(t);if(m){nodeName=m[1].toUpperCase();for(var i=0;ret[i];i++)for(var c=ret[i].firstChild;c;c=c.nextSibling)if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName))r.push(c);ret=r;t=t.replace(re,"");if(t.indexOf(" ")==0)continue;foundToken=true;}else{re=/^([>+~])\s*(\w*)/i;if((m=re.exec(t))!=null){r=[];var merge={};nodeName=m[2].toUpperCase();m=m[1];for(var j=0,rl=ret.length;j<rl;j++){var n=m=="~"||m=="+"?ret[j].nextSibling:ret[j].firstChild;for(;n;n=n.nextSibling)if(n.nodeType==1){var id=jQuery.data(n);if(m=="~"&&merge[id])break;if(!nodeName||n.nodeName.toUpperCase()==nodeName){if(m=="~")merge[id]=true;r.push(n);}if(m=="+")break;}}ret=r;t=jQuery.trim(t.replace(re,""));foundToken=true;}}if(t&&!foundToken){if(!t.indexOf(",")){if(context==ret[0])ret.shift();done=jQuery.merge(done,ret);r=ret=[context];t=" "+t.substr(1,t.length);}else{var re2=quickID;var m=re2.exec(t);if(m){m=[0,m[2],m[3],m[1]];}else{re2=quickClass;m=re2.exec(t);}m[2]=m[2].replace(/\\/g,"");var elem=ret[ret.length-1];if(m[1]=="#"&&elem&&elem.getElementById&&!jQuery.isXMLDoc(elem)){var oid=elem.getElementById(m[2]);if((jQuery.browser.msie||jQuery.browser.opera)&&oid&&typeof oid.id=="string"&&oid.id!=m[2])oid=jQuery('[@id="'+m[2]+'"]',elem)[0];ret=r=oid&&(!m[3]||jQuery.nodeName(oid,m[3]))?[oid]:[];}else{for(var i=0;ret[i];i++){var tag=m[1]=="#"&&m[3]?m[3]:m[1]!=""||m[0]==""?"*":m[2];if(tag=="*"&&ret[i].nodeName.toLowerCase()=="object")tag="param";r=jQuery.merge(r,ret[i].getElementsByTagName(tag));}if(m[1]==".")r=jQuery.classFilter(r,m[2]);if(m[1]=="#"){var tmp=[];for(var i=0;r[i];i++)if(r[i].getAttribute("id")==m[2]){tmp=[r[i]];break;}r=tmp;}ret=r;}t=t.replace(re2,"");}}if(t){var val=jQuery.filter(t,r);ret=r=val.r;t=jQuery.trim(val.t);}}if(t)ret=[];if(ret&&context==ret[0])ret.shift();done=jQuery.merge(done,ret);return done;},classFilter:function(r,m,not){m=" "+m+" ";var tmp=[];for(var i=0;r[i];i++){var pass=(" "+r[i].className+" ").indexOf(m)>=0;if(!not&&pass||not&&!pass)tmp.push(r[i]);}return tmp;},filter:function(t,r,not){var last;while(t&&t!=last){last=t;var p=jQuery.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break;}}if(!m)break;if(m[1]==":"&&m[2]=="not")r=isSimple.test(m[3])?jQuery.filter(m[3],r,true).r:jQuery(r).not(m[3]);else if(m[1]==".")r=jQuery.classFilter(r,m[2],not);else if(m[1]=="["){var tmp=[],type=m[3];for(var i=0,rl=r.length;i<rl;i++){var a=r[i],z=a[jQuery.props[m[2]]||m[2]];if(z==null||/href|src|selected/.test(m[2]))z=jQuery.attr(a,m[2])||'';if((type==""&&!!z||type=="="&&z==m[5]||type=="!="&&z!=m[5]||type=="^="&&z&&!z.indexOf(m[5])||type=="$="&&z.substr(z.length-m[5].length)==m[5]||(type=="*="||type=="~=")&&z.indexOf(m[5])>=0)^not)tmp.push(a);}r=tmp;}else if(m[1]==":"&&m[2]=="nth-child"){var merge={},tmp=[],test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"0n+"+m[3]||m[3]),first=(test[1]+(test[2]||1))-0,last=test[3]-0;for(var i=0,rl=r.length;i<rl;i++){var node=r[i],parentNode=node.parentNode,id=jQuery.data(parentNode);if(!merge[id]){var c=1;for(var n=parentNode.firstChild;n;n=n.nextSibling)if(n.nodeType==1)n.nodeIndex=c++;merge[id]=true;}var add=false;if(first==0){if(node.nodeIndex==last)add=true;}else if((node.nodeIndex-last)%first==0&&(node.nodeIndex-last)/first>=0)add=true;if(add^not)tmp.push(node);}r=tmp;}else{var fn=jQuery.expr[m[1]];if(typeof fn=="object")fn=fn[m[2]];if(typeof fn=="string")fn=eval("false||function(a,i){return "+fn+";}");r=jQuery.grep(r,function(elem,i){return fn(elem,i,m,r);},not);}}return{r:r,t:t};},dir:function(elem,dir){var matched=[];var cur=elem[dir];while(cur&&cur!=document){if(cur.nodeType==1)matched.push(cur);cur=cur[dir];}return matched;},nth:function(cur,result,dir,elem){result=result||1;var num=0;for(;cur;cur=cur[dir])if(cur.nodeType==1&&++num==result)break;return cur;},sibling:function(n,elem){var r=[];for(;n;n=n.nextSibling){if(n.nodeType==1&&(!elem||n!=elem))r.push(n);}return r;}});jQuery.event={add:function(elem,types,handler,data){if(elem.nodeType==3||elem.nodeType==8)return;if(jQuery.browser.msie&&elem.setInterval!=undefined)elem=window;if(!handler.guid)handler.guid=this.guid++;if(data!=undefined){var fn=handler;handler=function(){return fn.apply(this,arguments);};handler.data=data;handler.guid=fn.guid;}var events=jQuery.data(elem,"events")||jQuery.data(elem,"events",{}),handle=jQuery.data(elem,"handle")||jQuery.data(elem,"handle",function(){var val;if(typeof jQuery=="undefined"||jQuery.event.triggered)return val;val=jQuery.event.handle.apply(arguments.callee.elem,arguments);return val;});handle.elem=elem;jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];handler.type=parts[1];var handlers=events[type];if(!handlers){handlers=events[type]={};if(!jQuery.event.special[type]||jQuery.event.special[type].setup.call(elem)===false){if(elem.addEventListener)elem.addEventListener(type,handle,false);else if(elem.attachEvent)elem.attachEvent("on"+type,handle);}}handlers[handler.guid]=handler;jQuery.event.global[type]=true;});elem=null;},guid:1,global:{},remove:function(elem,types,handler){if(elem.nodeType==3||elem.nodeType==8)return;var events=jQuery.data(elem,"events"),ret,index;if(events){if(types==undefined||(typeof types=="string"&&types.charAt(0)=="."))for(var type in events)this.remove(elem,type+(types||""));else{if(types.type){handler=types.handler;types=types.type;}jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];if(events[type]){if(handler)delete events[type][handler.guid];else
for(handler in events[type])if(!parts[1]||events[type][handler].type==parts[1])delete events[type][handler];for(ret in events[type])break;if(!ret){if(!jQuery.event.special[type]||jQuery.event.special[type].teardown.call(elem)===false){if(elem.removeEventListener)elem.removeEventListener(type,jQuery.data(elem,"handle"),false);else if(elem.detachEvent)elem.detachEvent("on"+type,jQuery.data(elem,"handle"));}ret=null;delete events[type];}}});}for(ret in events)break;if(!ret){var handle=jQuery.data(elem,"handle");if(handle)handle.elem=null;jQuery.removeData(elem,"events");jQuery.removeData(elem,"handle");}}},trigger:function(type,data,elem,donative,extra){data=jQuery.makeArray(data||[]);if(type.indexOf("!")>=0){type=type.slice(0,-1);var exclusive=true;}if(!elem){if(this.global[type])jQuery("*").add([window,document]).trigger(type,data);}else{if(elem.nodeType==3||elem.nodeType==8)return undefined;var val,ret,fn=jQuery.isFunction(elem[type]||null),event=!data[0]||!data[0].preventDefault;if(event)data.unshift(this.fix({type:type,target:elem}));data[0].type=type;if(exclusive)data[0].exclusive=true;if(jQuery.isFunction(jQuery.data(elem,"handle")))val=jQuery.data(elem,"handle").apply(elem,data);if(!fn&&elem["on"+type]&&elem["on"+type].apply(elem,data)===false)val=false;if(event)data.shift();if(extra&&jQuery.isFunction(extra)){ret=extra.apply(elem,val==null?data:data.concat(val));if(ret!==undefined)val=ret;}if(fn&&donative!==false&&val!==false&&!(jQuery.nodeName(elem,'a')&&type=="click")){this.triggered=true;try{elem[type]();}catch(e){}}this.triggered=false;}return val;},handle:function(event){var val;event=jQuery.event.fix(event||window.event||{});var parts=event.type.split(".");event.type=parts[0];var handlers=jQuery.data(this,"events")&&jQuery.data(this,"events")[event.type],args=Array.prototype.slice.call(arguments,1);args.unshift(event);for(var j in handlers){var handler=handlers[j];args[0].handler=handler;args[0].data=handler.data;if(!parts[1]&&!event.exclusive||handler.type==parts[1]){var ret=handler.apply(this,args);if(val!==false)val=ret;if(ret===false){event.preventDefault();event.stopPropagation();}}}if(jQuery.browser.msie)event.target=event.preventDefault=event.stopPropagation=event.handler=event.data=null;return val;},fix:function(event){var originalEvent=event;event=jQuery.extend({},originalEvent);event.preventDefault=function(){if(originalEvent.preventDefault)originalEvent.preventDefault();originalEvent.returnValue=false;};event.stopPropagation=function(){if(originalEvent.stopPropagation)originalEvent.stopPropagation();originalEvent.cancelBubble=true;};if(!event.target)event.target=event.srcElement||document;if(event.target.nodeType==3)event.target=originalEvent.target.parentNode;if(!event.relatedTarget&&event.fromElement)event.relatedTarget=event.fromElement==event.target?event.toElement:event.fromElement;if(event.pageX==null&&event.clientX!=null){var doc=document.documentElement,body=document.body;event.pageX=event.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc.clientLeft||0);event.pageY=event.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc.clientTop||0);}if(!event.which&&((event.charCode||event.charCode===0)?event.charCode:event.keyCode))event.which=event.charCode||event.keyCode;if(!event.metaKey&&event.ctrlKey)event.metaKey=event.ctrlKey;if(!event.which&&event.button)event.which=(event.button&1?1:(event.button&2?3:(event.button&4?2:0)));return event;},special:{ready:{setup:function(){bindReady();return;},teardown:function(){return;}},mouseenter:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseover",jQuery.event.special.mouseenter.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseover",jQuery.event.special.mouseenter.handler);return true;},handler:function(event){if(withinElement(event,this))return true;arguments[0].type="mouseenter";return jQuery.event.handle.apply(this,arguments);}},mouseleave:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseout",jQuery.event.special.mouseleave.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseout",jQuery.event.special.mouseleave.handler);return true;},handler:function(event){if(withinElement(event,this))return true;arguments[0].type="mouseleave";return jQuery.event.handle.apply(this,arguments);}}}};jQuery.fn.extend({bind:function(type,data,fn){return type=="unload"?this.one(type,data,fn):this.each(function(){jQuery.event.add(this,type,fn||data,fn&&data);});},one:function(type,data,fn){return this.each(function(){jQuery.event.add(this,type,function(event){jQuery(this).unbind(event);return(fn||data).apply(this,arguments);},fn&&data);});},unbind:function(type,fn){return this.each(function(){jQuery.event.remove(this,type,fn);});},trigger:function(type,data,fn){return this.each(function(){jQuery.event.trigger(type,data,this,true,fn);});},triggerHandler:function(type,data,fn){if(this[0])return jQuery.event.trigger(type,data,this[0],false,fn);return undefined;},toggle:function(){var args=arguments;return this.click(function(event){this.lastToggle=0==this.lastToggle?1:0;event.preventDefault();return args[this.lastToggle].apply(this,arguments)||false;});},hover:function(fnOver,fnOut){return this.bind('mouseenter',fnOver).bind('mouseleave',fnOut);},ready:function(fn){bindReady();if(jQuery.isReady)fn.call(document,jQuery);else
jQuery.readyList.push(function(){return fn.call(this,jQuery);});return this;}});jQuery.extend({isReady:false,readyList:[],ready:function(){if(!jQuery.isReady){jQuery.isReady=true;if(jQuery.readyList){jQuery.each(jQuery.readyList,function(){this.apply(document);});jQuery.readyList=null;}jQuery(document).triggerHandler("ready");}}});var readyBound=false;function bindReady(){if(readyBound)return;readyBound=true;if(document.addEventListener&&!jQuery.browser.opera)document.addEventListener("DOMContentLoaded",jQuery.ready,false);if(jQuery.browser.msie&&window==top)(function(){if(jQuery.isReady)return;try{document.documentElement.doScroll("left");}catch(error){setTimeout(arguments.callee,0);return;}jQuery.ready();})();if(jQuery.browser.opera)document.addEventListener("DOMContentLoaded",function(){if(jQuery.isReady)return;for(var i=0;i<document.styleSheets.length;i++)if(document.styleSheets[i].disabled){setTimeout(arguments.callee,0);return;}jQuery.ready();},false);if(jQuery.browser.safari){var numStyles;(function(){if(jQuery.isReady)return;if(document.readyState!="loaded"&&document.readyState!="complete"){setTimeout(arguments.callee,0);return;}if(numStyles===undefined)numStyles=jQuery("style, link[rel=stylesheet]").length;if(document.styleSheets.length!=numStyles){setTimeout(arguments.callee,0);return;}jQuery.ready();})();}jQuery.event.add(window,"load",jQuery.ready);}jQuery.each(("blur,focus,load,resize,scroll,unload,click,dblclick,"+"mousedown,mouseup,mousemove,mouseover,mouseout,change,select,"+"submit,keydown,keypress,keyup,error").split(","),function(i,name){jQuery.fn[name]=function(fn){return fn?this.bind(name,fn):this.trigger(name);};});var withinElement=function(event,elem){var parent=event.relatedTarget;while(parent&&parent!=elem)try{parent=parent.parentNode;}catch(error){parent=elem;}return parent==elem;};jQuery(window).bind("unload",function(){jQuery("*").add(document).unbind();});jQuery.fn.extend({load:function(url,params,callback){if(jQuery.isFunction(url))return this.bind("load",url);var off=url.indexOf(" ");if(off>=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}callback=callback||function(){};var type="GET";if(params)if(jQuery.isFunction(params)){callback=params;params=null;}else{params=jQuery.param(params);type="POST";}var self=this;jQuery.ajax({url:url,type:type,dataType:"html",data:params,complete:function(res,status){if(status=="success"||status=="notmodified")self.html(selector?jQuery("<div/>").append(res.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(selector):res.responseText);self.each(callback,[res.responseText,status,res]);}});return this;},serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){return jQuery.nodeName(this,"form")?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:val.constructor==Array?jQuery.map(val,function(val,i){return{name:elem.name,value:val};}):{name:elem.name,value:val};}).get();}});jQuery.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){jQuery.fn[o]=function(f){return this.bind(o,f);};});var jsc=(new Date).getTime();jQuery.extend({get:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data=null;}return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type});},getScript:function(url,callback){return jQuery.get(url,null,callback,"script");},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},post:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data={};}return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type});},ajaxSetup:function(settings){jQuery.extend(jQuery.ajaxSettings,settings);},ajaxSettings:{global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null,username:null,password:null,accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(s){var jsonp,jsre=/=\?(&|$)/g,status,data;s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));if(s.data&&s.processData&&typeof s.data!="string")s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(s.type.toLowerCase()=="get"){if(!s.url.match(jsre))s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?";}else if(!s.data||!s.data.match(jsre))s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";s.dataType="json";}if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){jsonp="jsonp"+jsc++;if(s.data)s.data=(s.data+"").replace(jsre,"="+jsonp+"$1");s.url=s.url.replace(jsre,"="+jsonp+"$1");s.dataType="script";window[jsonp]=function(tmp){data=tmp;success();complete();window[jsonp]=undefined;try{delete window[jsonp];}catch(e){}if(head)head.removeChild(script);};}if(s.dataType=="script"&&s.cache==null)s.cache=false;if(s.cache===false&&s.type.toLowerCase()=="get"){var ts=(new Date()).getTime();var ret=s.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+ts+"$2");s.url=ret+((ret==s.url)?(s.url.match(/\?/)?"&":"?")+"_="+ts:"");}if(s.data&&s.type.toLowerCase()=="get"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++)jQuery.event.trigger("ajaxStart");if((!s.url.indexOf("http")||!s.url.indexOf("//"))&&s.dataType=="script"&&s.type.toLowerCase()=="get"){var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=s.url;if(s.scriptCharset)script.charset=s.scriptCharset;if(!jsonp){var done=false;script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){done=true;success();complete();head.removeChild(script);}};}head.appendChild(script);return undefined;}var requestDone=false;var xml=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();xml.open(s.type,s.url,s.async,s.username,s.password);try{if(s.data)xml.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)xml.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xml.setRequestHeader("X-Requested-With","XMLHttpRequest");xml.setRequestHeader("Accept",s.dataType&&s.accepts[s.dataType]?s.accepts[s.dataType]+", */*":s.accepts._default);}catch(e){}if(s.beforeSend)s.beforeSend(xml);if(s.global)jQuery.event.trigger("ajaxSend",[xml,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xml&&(xml.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xml)&&"error"||s.ifModified&&jQuery.httpNotModified(xml,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xml,s.dataType);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xml.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes)jQuery.lastModified[s.url]=modRes;if(!jsonp)success();}else
jQuery.handleError(s,xml,status);complete();if(s.async)xml=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)setTimeout(function(){if(xml){xml.abort();if(!requestDone)onreadystatechange("timeout");}},s.timeout);}try{xml.send(s.data);}catch(e){jQuery.handleError(s,xml,null,e);}if(!s.async)onreadystatechange();function success(){if(s.success)s.success(data,status);if(s.global)jQuery.event.trigger("ajaxSuccess",[xml,s]);}function complete(){if(s.complete)s.complete(xml,status);if(s.global)jQuery.event.trigger("ajaxComplete",[xml,s]);if(s.global&&!--jQuery.active)jQuery.event.trigger("ajaxStop");}return xml;},handleError:function(s,xml,status,e){if(s.error)s.error(xml,status,e);if(s.global)jQuery.event.trigger("ajaxError",[xml,s,e]);},active:0,httpSuccess:function(r){try{return!r.status&&location.protocol=="file:"||(r.status>=200&&r.status<300)||r.status==304||r.status==1223||jQuery.browser.safari&&r.status==undefined;}catch(e){}return false;},httpNotModified:function(xml,url){try{var xmlRes=xml.getResponseHeader("Last-Modified");return xml.status==304||xmlRes==jQuery.lastModified[url]||jQuery.browser.safari&&xml.status==undefined;}catch(e){}return false;},httpData:function(r,type){var ct=r.getResponseHeader("content-type");var xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0;var data=xml?r.responseXML:r.responseText;if(xml&&data.documentElement.tagName=="parsererror")throw"parsererror";if(type=="script")jQuery.globalEval(data);if(type=="json")data=eval("("+data+")");return data;},param:function(a){var s=[];if(a.constructor==Array||a.jquery)jQuery.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value));});else for(var j in a)if(a[j]&&a[j].constructor==Array)jQuery.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this));});else
s.push(encodeURIComponent(j)+"="+encodeURIComponent(a[j]));return s.join("&").replace(/%20/g,"+");}});jQuery.fn.extend({show:function(speed,callback){return speed?this.animate({height:"show",width:"show",opacity:"show"},speed,callback):this.filter(":hidden").each(function(){this.style.display=this.oldblock||"";if(jQuery.css(this,"display")=="none"){var elem=jQuery("<"+this.tagName+" />").appendTo("body");this.style.display=elem.css("display");if(this.style.display=="none")this.style.display="block";elem.remove();}}).end();},hide:function(speed,callback){return speed?this.animate({height:"hide",width:"hide",opacity:"hide"},speed,callback):this.filter(":visible").each(function(){this.oldblock=this.oldblock||jQuery.css(this,"display");this.style.display="none";}).end();},_toggle:jQuery.fn.toggle,toggle:function(fn,fn2){return jQuery.isFunction(fn)&&jQuery.isFunction(fn2)?this._toggle(fn,fn2):fn?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},fn,fn2):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();});},slideDown:function(speed,callback){return this.animate({height:"show"},speed,callback);},slideUp:function(speed,callback){return this.animate({height:"hide"},speed,callback);},slideToggle:function(speed,callback){return this.animate({height:"toggle"},speed,callback);},fadeIn:function(speed,callback){return this.animate({opacity:"show"},speed,callback);},fadeOut:function(speed,callback){return this.animate({opacity:"hide"},speed,callback);},fadeTo:function(speed,to,callback){return this.animate({opacity:to},speed,callback);},animate:function(prop,speed,easing,callback){var optall=jQuery.speed(speed,easing,callback);return this[optall.queue===false?"each":"queue"](function(){if(this.nodeType!=1)return false;var opt=jQuery.extend({},optall);var hidden=jQuery(this).is(":hidden"),self=this;for(var p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)return jQuery.isFunction(opt.complete)&&opt.complete.apply(this);if(p=="height"||p=="width"){opt.display=jQuery.css(this,"display");opt.overflow=this.style.overflow;}}if(opt.overflow!=null)this.style.overflow="hidden";opt.curAnim=jQuery.extend({},prop);jQuery.each(prop,function(name,val){var e=new jQuery.fx(self,opt,name);if(/toggle|show|hide/.test(val))e[val=="toggle"?hidden?"show":"hide":val](prop);else{var parts=val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(parts){var end=parseFloat(parts[2]),unit=parts[3]||"px";if(unit!="px"){self.style[name]=(end||1)+unit;start=((end||1)/e.cur(true))*start;self.style[name]=start+unit;}if(parts[1])end=((parts[1]=="-="?-1:1)*end)+start;e.custom(start,end,unit);}else e.custom(start,val,"");}});return true;});},queue:function(type,fn){if(jQuery.isFunction(type)||(type&&type.constructor==Array)){fn=type;type="fx";}if(!type||(typeof type=="string"&&!fn))return queue(this[0],type);return this.each(function(){if(fn.constructor==Array)queue(this,type,fn);else{queue(this,type).push(fn);if(queue(this,type).length==1)fn.apply(this);}});},stop:function(clearQueue,gotoEnd){var timers=jQuery.timers;if(clearQueue)this.queue([]);this.each(function(){for(var i=timers.length-1;i>=0;i--)if(timers[i].elem==this){if(gotoEnd)timers[i](true);timers.splice(i,1);}});if(!gotoEnd)this.dequeue();return this;}});var queue=function(elem,type,array){if(!elem)return undefined;type=type||"fx";var q=jQuery.data(elem,type+"queue");if(!q||array)q=jQuery.data(elem,type+"queue",array?jQuery.makeArray(array):[]);return q;};jQuery.fn.dequeue=function(type){type=type||"fx";return this.each(function(){var q=queue(this,type);q.shift();if(q.length)q[0].apply(this);});};jQuery.extend({speed:function(speed,easing,fn){var opt=speed&&speed.constructor==Object?speed:{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&easing.constructor!=Function&&easing};opt.duration=(opt.duration&&opt.duration.constructor==Number?opt.duration:{slow:600,fast:200}[opt.duration])||400;opt.old=opt.complete;opt.complete=function(){if(opt.queue!==false)jQuery(this).dequeue();if(jQuery.isFunction(opt.old))opt.old.apply(this);};return opt;},easing:{linear:function(p,n,firstNum,diff){return firstNum+diff*p;},swing:function(p,n,firstNum,diff){return((-Math.cos(p*Math.PI)/2)+0.5)*diff+firstNum;}},timers:[],timerId:null,fx:function(elem,options,prop){this.options=options;this.elem=elem;this.prop=prop;if(!options.orig)options.orig={};}});jQuery.fx.prototype={update:function(){if(this.options.step)this.options.step.apply(this.elem,[this.now,this]);(jQuery.fx.step[this.prop]||jQuery.fx.step._default)(this);if(this.prop=="height"||this.prop=="width")this.elem.style.display="block";},cur:function(force){if(this.elem[this.prop]!=null&&this.elem.style[this.prop]==null)return this.elem[this.prop];var r=parseFloat(jQuery.css(this.elem,this.prop,force));return r&&r>-10000?r:parseFloat(jQuery.curCSS(this.elem,this.prop))||0;},custom:function(from,to,unit){this.startTime=(new Date()).getTime();this.start=from;this.end=to;this.unit=unit||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var self=this;function t(gotoEnd){return self.step(gotoEnd);}t.elem=this.elem;jQuery.timers.push(t);if(jQuery.timerId==null){jQuery.timerId=setInterval(function(){var timers=jQuery.timers;for(var i=0;i<timers.length;i++)if(!timers[i]())timers.splice(i--,1);if(!timers.length){clearInterval(jQuery.timerId);jQuery.timerId=null;}},13);}},show:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.show=true;this.custom(0,this.cur());if(this.prop=="width"||this.prop=="height")this.elem.style[this.prop]="1px";jQuery(this.elem).show();},hide:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0);},step:function(gotoEnd){var t=(new Date()).getTime();if(gotoEnd||t>this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var done=true;for(var i in this.options.curAnim)if(this.options.curAnim[i]!==true)done=false;if(done){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(jQuery.css(this.elem,"display")=="none")this.elem.style.display="block";}if(this.options.hide)this.elem.style.display="none";if(this.options.hide||this.options.show)for(var p in this.options.curAnim)jQuery.attr(this.elem.style,p,this.options.orig[p]);}if(done&&jQuery.isFunction(this.options.complete))this.options.complete.apply(this.elem);return false;}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=jQuery.easing[this.options.easing||(jQuery.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update();}return true;}};jQuery.fx.step={scrollLeft:function(fx){fx.elem.scrollLeft=fx.now;},scrollTop:function(fx){fx.elem.scrollTop=fx.now;},opacity:function(fx){jQuery.attr(fx.elem.style,"opacity",fx.now);},_default:function(fx){fx.elem.style[fx.prop]=fx.now+fx.unit;}};jQuery.fn.offset=function(){var left=0,top=0,elem=this[0],results;if(elem)with(jQuery.browser){var parent=elem.parentNode,offsetChild=elem,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522&&!/adobeair/i.test(userAgent),fixed=jQuery.css(elem,"position")=="fixed";if(elem.getBoundingClientRect){var box=elem.getBoundingClientRect();add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));add(-doc.documentElement.clientLeft,-doc.documentElement.clientTop);}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&!/^t(able|d|h)$/i.test(offsetParent.tagName)||safari&&!safari2)border(offsetParent);if(!fixed&&jQuery.css(offsetParent,"position")=="fixed")fixed=true;offsetChild=/^body$/i.test(offsetParent.tagName)?offsetChild:offsetParent;offsetParent=offsetParent.offsetParent;}while(parent&&parent.tagName&&!/^body|html$/i.test(parent.tagName)){if(!/^inline|table.*$/i.test(jQuery.css(parent,"display")))add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&jQuery.css(parent,"overflow")!="visible")border(parent);parent=parent.parentNode;}if((safari2&&(fixed||jQuery.css(offsetChild,"position")=="absolute"))||(mozilla&&jQuery.css(offsetChild,"position")!="absolute"))add(-doc.body.offsetLeft,-doc.body.offsetTop);if(fixed)add(Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));}results={top:top,left:left};}function border(elem){add(jQuery.curCSS(elem,"borderLeftWidth",true),jQuery.curCSS(elem,"borderTopWidth",true));}function add(l,t){left+=parseInt(l)||0;top+=parseInt(t)||0;}return results;};})();

/* ---------- ADD JAVASCRIPT PLUGINS BELOW THIS LINE ---------- */ 
/*
 * 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
 *
 * $Date: 2008-04-01 10:23:47 -0300 (Ter, 01 Abr 2008) $
 * $Rev: 5174 $
 */
(function(C){C.ui=C.ui||{};C.extend(C.ui,{plugin:{add:function(E,F,H){var G=C.ui[E].prototype;for(var D in H){G.plugins[D]=G.plugins[D]||[];G.plugins[D].push([F,H[D]])}},call:function(D,E,G){var H=D.plugins[E];if(!H){return }for(var F=0;F<H.length;F++){if(D.options[H[F][0]]){H[F][1].apply(D.element,G)}}}},cssCache:{},css:function(D){if(C.ui.cssCache[D]){return C.ui.cssCache[D]}var E=C('<div class="ui-resizable-gen">').addClass(D).css({position:"absolute",top:"-5000px",left:"-5000px",display:"block"}).appendTo("body");C.ui.cssCache[D]=!!((!/auto|default/.test(E.css("cursor"))||(/^[1-9]/).test(E.css("height"))||(/^[1-9]/).test(E.css("width"))||!(/none/).test(E.css("backgroundImage"))||!(/transparent|rgba\(0, 0, 0, 0\)/).test(E.css("backgroundColor"))));try{C("body").get(0).removeChild(E.get(0))}catch(F){}return C.ui.cssCache[D]},disableSelection:function(D){D.unselectable="on";D.onselectstart=function(){return false};if(D.style){D.style.MozUserSelect="none"}},enableSelection:function(D){D.unselectable="off";D.onselectstart=function(){return true};if(D.style){D.style.MozUserSelect=""}},hasScroll:function(G,E){var D=/top/.test(E||"top")?"scrollTop":"scrollLeft",F=false;if(G[D]>0){return true}G[D]=1;F=G[D]>0?true:false;G[D]=0;return F}});C.each(["Left","Top"],function(E,D){if(!C.fn["scroll"+D]){C.fn["scroll"+D]=function(F){return F!=undefined?this.each(function(){this==window||this==document?window.scrollTo(D=="Left"?F:C(window)["scrollLeft"](),D=="Top"?F:C(window)["scrollTop"]()):this["scroll"+D]=F}):this[0]==window||this[0]==document?self[(D=="Left"?"pageXOffset":"pageYOffset")]||C.boxModel&&document.documentElement["scroll"+D]||document.body["scroll"+D]:this[0]["scroll"+D]}}});var B=C.fn.remove;C.fn.extend({position:function(){var F=this.offset();var E=this.offsetParent();var D=E.offset();return{top:F.top-A(this[0],"marginTop")-D.top-A(E,"borderTopWidth"),left:F.left-A(this[0],"marginLeft")-D.left-A(E,"borderLeftWidth")}},offsetParent:function(){var D=this[0].offsetParent;while(D&&(!/^body|html$/i.test(D.tagName)&&C.css(D,"position")=="static")){D=D.offsetParent}return C(D)},mouseInteraction:function(D){return this.each(function(){new C.ui.mouseInteraction(this,D)})},removeMouseInteraction:function(D){return this.each(function(){if(C.data(this,"ui-mouse")){C.data(this,"ui-mouse").destroy()}})},remove:function(){jQuery("*",this).add(this).trigger("remove");return B.apply(this,arguments)}});function A(D,E){return parseInt(C.curCSS(D.jquery?D[0]:D,E,true))||0}C.ui.mouseInteraction=function(F,E){var D=this;this.element=F;C.data(this.element,"ui-mouse",this);this.options=C.extend({},E);C(F).bind("mousedown.draggable",function(){return D.click.apply(D,arguments)});if(C.browser.msie){C(F).attr("unselectable","on")}C(F).mouseup(function(){if(D.timer){clearInterval(D.timer)}})};C.extend(C.ui.mouseInteraction.prototype,{destroy:function(){C(this.element).unbind("mousedown.draggable")},trigger:function(){return this.click.apply(this,arguments)},click:function(F){if(F.which!=1||C.inArray(F.target.nodeName.toLowerCase(),this.options.dragPrevention||[])!=-1||(this.options.condition&&!this.options.condition.apply(this.options.executor||this,[F,this.element]))){return true}var E=this;var D=function(){E._MP={left:F.pageX,top:F.pageY};C(document).bind("mouseup.draggable",function(){return E.stop.apply(E,arguments)});C(document).bind("mousemove.draggable",function(){return E.drag.apply(E,arguments)});if(!E.initalized&&Math.abs(E._MP.left-F.pageX)>=E.options.distance||Math.abs(E._MP.top-F.pageY)>=E.options.distance){if(E.options.start){E.options.start.call(E.options.executor||E,F,E.element)}if(E.options.drag){E.options.drag.call(E.options.executor||E,F,this.element)}E.initialized=true}};if(this.options.delay){if(this.timer){clearInterval(this.timer)}this.timer=setTimeout(D,this.options.delay)}else{D()}return false},stop:function(D){var E=this.options;if(!this.initialized){return C(document).unbind("mouseup.draggable").unbind("mousemove.draggable")}if(this.options.stop){this.options.stop.call(this.options.executor||this,D,this.element)}C(document).unbind("mouseup.draggable").unbind("mousemove.draggable");this.initialized=false;return false},drag:function(D){var E=this.options;if(C.browser.msie&&!D.button){return this.stop.apply(this,[D])}if(!this.initialized&&(Math.abs(this._MP.left-D.pageX)>=E.distance||Math.abs(this._MP.top-D.pageY)>=E.distance)){if(this.options.start){this.options.start.call(this.options.executor||this,D,this.element)}this.initialized=true}else{if(!this.initialized){return false}}if(E.drag){E.drag.call(this.options.executor||this,D,this.element)}return false}})})(jQuery);(function(A){A.fn.extend({draggable:function(C){var B=Array.prototype.slice.call(arguments,1);return this.each(function(){if(typeof C=="string"){var D=A.data(this,"draggable");if(D){D[C].apply(D,B)}}else{if(!A.data(this,"draggable")){new A.ui.draggable(this,C)}}})}});A.ui.draggable=function(D,C){var B=this;this.element=A(D);A.data(D,"draggable",this);this.element.addClass("ui-draggable");this.options=A.extend({},C);var E=this.options;A.extend(E,{helper:E.ghosting==true?"clone":(E.helper||"original"),handle:E.handle?(A(E.handle,D)[0]?A(E.handle,D):this.element):this.element,appendTo:E.appendTo||"parent"});A(D).bind("setData.draggable",function(G,F,H){B.options[F]=H}).bind("getData.draggable",function(G,F){return B.options[F]});A(E.handle).mouseInteraction({executor:this,delay:E.delay,distance:E.distance||1,dragPrevention:E.cancel||E.cancel===""?E.cancel.toLowerCase().split(","):["input","textarea","button","select","option"],start:this.start,stop:this.stop,drag:this.drag,condition:function(F){return !(F.target.className.indexOf("ui-resizable-handle")!=-1||this.options.disabled)}});if(E.helper=="original"&&(this.element.css("position")=="static"||this.element.css("position")=="")){this.element.css("position","relative")}if(E.cursorAt&&E.cursorAt.constructor==Array){E.cursorAt={left:E.cursorAt[0],top:E.cursorAt[1]}}};A.extend(A.ui.draggable.prototype,{plugins:{},ui:function(B){return{helper:this.helper,position:this.position,absolutePosition:this.positionAbs,instance:this,options:this.options,element:this.element}},propagate:function(C,B){A.ui.plugin.call(this,C,[B,this.ui()]);return this.element.triggerHandler(C=="drag"?C:"drag"+C,[B,this.ui()],this.options[C])},destroy:function(){if(!A.data(this.element[0],"draggable")){return }this.options.handle.removeMouseInteraction();this.element.removeClass("ui-draggable ui-draggable-disabled").removeData("draggable").unbind(".draggable")},enable:function(){this.element.removeClass("ui-draggable-disabled");this.options.disabled=false},disable:function(){this.element.addClass("ui-draggable-disabled");this.options.disabled=true},setContrains:function(B,C,E,D){this.minLeft=B;this.maxLeft=C;this.minTop=E;this.maxTop=D;this.constrainsSet=true},checkConstrains:function(){if(!this.constrainsSet){return }if(this.position.left<this.minLeft){this.position.left=this.minLeft}if(this.position.left>this.maxLeft-this.helperProportions.width){this.position.left=this.maxLeft-this.helperProportions.width}if(this.position.top<this.minTop){this.position.top=this.minTop}if(this.position.top>this.maxTop-this.helperProportions.height){this.position.top=this.maxTop-this.helperProportions.height}},recallOffset:function(D){var C={left:this.elementOffset.left-this.offsetParentOffset.left,top:this.elementOffset.top-this.offsetParentOffset.top};var B=this.helper.css("position")=="relative";this.originalPosition={left:(B?parseInt(this.helper.css("left"),10)||0:C.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft)),top:(B?parseInt(this.helper.css("top"),10)||0:C.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop))};this.offset={left:this._pageX-this.originalPosition.left,top:this._pageY-this.originalPosition.top}},start:function(D){var E=this.options;if(A.ui.ddmanager){A.ui.ddmanager.current=this}this.helper=typeof E.helper=="function"?A(E.helper.apply(this.element[0],[D])):(E.helper=="clone"?this.element.clone().appendTo((E.appendTo=="parent"?this.element[0].parentNode:E.appendTo)):this.element);if(this.helper[0]!=this.element[0]){this.helper.css("position","absolute")}if(!this.helper.parents("body").length){this.helper.appendTo((E.appendTo=="parent"?this.element[0].parentNode:E.appendTo))}this.offsetParent=(function(F){while(F){if(F.style&&(/(absolute|relative|fixed)/).test(A.css(F,"position"))){return A(F)}F=F.parentNode?F.parentNode:null}return A("body")})(this.helper[0].parentNode);this.elementOffset=this.element.offset();this.offsetParentOffset=this.offsetParent.offset();var C={left:this.elementOffset.left-this.offsetParentOffset.left,top:this.elementOffset.top-this.offsetParentOffset.top};this._pageX=D.pageX;this._pageY=D.pageY;this.clickOffset={left:D.pageX-this.elementOffset.left,top:D.pageY-this.elementOffset.top};var B=this.helper.css("position")=="relative";this.originalPosition={left:(B?parseInt(this.helper.css("left"),10)||0:C.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft)),top:(B?parseInt(this.helper.css("top"),10)||0:C.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop))};if(this.element.css("position")=="fixed"){this.originalPosition.top-=this.offsetParent[0]==document.body?A(document).scrollTop():this.offsetParent[0].scrollTop;this.originalPosition.left-=this.offsetParent[0]==document.body?A(document).scrollLeft():this.offsetParent[0].scrollLeft}this.offset={left:D.pageX-this.originalPosition.left,top:D.pageY-this.originalPosition.top};if(this.element[0]!=this.helper[0]){this.offset.left+=parseInt(this.element.css("marginLeft"),10)||0;this.offset.top+=parseInt(this.element.css("marginTop"),10)||0}this.propagate("start",D);this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()};if(A.ui.ddmanager&&!E.dropBehaviour){A.ui.ddmanager.prepareOffsets(this,D)}if(E.cursorAt){if(E.cursorAt.top!=undefined||E.cursorAt.bottom!=undefined){this.offset.top-=this.clickOffset.top-(E.cursorAt.top!=undefined?E.cursorAt.top:(this.helperProportions.height-E.cursorAt.bottom));this.clickOffset.top=(E.cursorAt.top!=undefined?E.cursorAt.top:(this.helperProportions.height-E.cursorAt.bottom))}if(E.cursorAt.left!=undefined||E.cursorAt.right!=undefined){this.offset.left-=this.clickOffset.left-(E.cursorAt.left!=undefined?E.cursorAt.left:(this.helperProportions.width-E.cursorAt.right));this.clickOffset.left=(E.cursorAt.left!=undefined?E.cursorAt.left:(this.helperProportions.width-E.cursorAt.right))}}return false},clear:function(){if(A.ui.ddmanager){A.ui.ddmanager.current=null}this.helper=null},stop:function(B){if(A.ui.ddmanager&&!this.options.dropBehaviour){A.ui.ddmanager.drop(this,B)}this.propagate("stop",B);if(this.cancelHelperRemoval){return false}if(this.options.helper!="original"){this.helper.remove()}this.clear();return false},drag:function(B){this.position={top:B.pageY-this.offset.top,left:B.pageX-this.offset.left};this.positionAbs={left:B.pageX-this.clickOffset.left,top:B.pageY-this.clickOffset.top};this.checkConstrains();this.position=this.propagate("drag",B)||this.position;this.checkConstrains();A(this.helper).css({left:this.position.left+"px",top:this.position.top+"px"});if(A.ui.ddmanager){A.ui.ddmanager.drag(this,B)}return false}});A.ui.plugin.add("draggable","cursor",{start:function(D,C){var B=A("body");if(B.css("cursor")){C.options._cursor=B.css("cursor")}B.css("cursor",C.options.cursor)},stop:function(C,B){if(B.options._cursor){A("body").css("cursor",B.options._cursor)}}});A.ui.plugin.add("draggable","zIndex",{start:function(D,C){var B=A(C.helper);if(B.css("zIndex")){C.options._zIndex=B.css("zIndex")}B.css("zIndex",C.options.zIndex)},stop:function(C,B){if(B.options._zIndex){A(B.helper).css("zIndex",B.options._zIndex)}}});A.ui.plugin.add("draggable","opacity",{start:function(D,C){var B=A(C.helper);if(B.css("opacity")){C.options._opacity=B.css("opacity")}B.css("opacity",C.options.opacity)},stop:function(C,B){if(B.options._opacity){A(B.helper).css("opacity",B.options._opacity)}}});A.ui.plugin.add("draggable","revert",{stop:function(E,D){var B=D.instance,C=A(B.helper);B.cancelHelperRemoval=true;A(D.helper).animate({left:B.originalPosition.left,top:B.originalPosition.top},parseInt(D.options.revert,10)||500,function(){if(D.options.helper!="original"){C.remove()}if(!C){B.clear()}})}});A.ui.plugin.add("draggable","iframeFix",{start:function(D,C){var F=C.options;if(C.instance.slowMode){return }if(F.iframeFix.constructor==Array){for(var B=0;B<F.iframeFix.length;B++){var E=A(F.iframeFix[B]).offset({border:false});A('<div class="DragDropIframeFix"" style="background: #fff;"></div>').css("width",A(F.iframeFix[B])[0].offsetWidth+"px").css("height",A(F.iframeFix[B])[0].offsetHeight+"px").css("position","absolute").css("opacity","0.001").css("z-index","1000").css("top",E.top+"px").css("left",E.left+"px").appendTo("body")}}else{A("iframe").each(function(){var G=A(this).offset({border:false});A('<div class="DragDropIframeFix" style="background: #fff;"></div>').css("width",this.offsetWidth+"px").css("height",this.offsetHeight+"px").css("position","absolute").css("opacity","0.001").css("z-index","1000").css("top",G.top+"px").css("left",G.left+"px").appendTo("body")})}},stop:function(C,B){if(B.options.iframeFix){A("div.DragDropIframeFix").each(function(){this.parentNode.removeChild(this)})}}});A.ui.plugin.add("draggable","containment",{start:function(E,C){var G=C.options;var B=C.instance;if((G.containment.left!=undefined||G.containment.constructor==Array)&&!G._containment){return }if(!G._containment){G._containment=G.containment}if(G._containment=="parent"){G._containment=this[0].parentNode}if(G._containment=="document"){G.containment=[0,0,A(document).width(),(A(document).height()||document.body.parentNode.scrollHeight)]}else{var D=A(G._containment)[0];var F=A(G._containment).offset();G.containment=[F.left,F.top,F.left+(D.offsetWidth||D.scrollWidth),F.top+(D.offsetHeight||D.scrollHeight)]}var H=G.containment;C.instance.setContrains(H[0]-(B.offset.left-B.clickOffset.left),H[2]-(B.offset.left-B.clickOffset.left),H[1]-(B.offset.top-B.clickOffset.top),H[3]-(B.offset.top-B.clickOffset.top))}});A.ui.plugin.add("draggable","grid",{drag:function(E,D){var F=D.options;var C=D.instance.originalPosition.left+Math.round((E.pageX-D.instance._pageX)/F.grid[0])*F.grid[0];var B=D.instance.originalPosition.top+Math.round((E.pageY-D.instance._pageY)/F.grid[1])*F.grid[1];D.instance.position.left=C;D.instance.position.top=B}});A.ui.plugin.add("draggable","axis",{drag:function(C,B){var D=B.options;if(D.constraint){D.axis=D.constraint}switch(D.axis){case"x":B.instance.position.top=B.instance.originalPosition.top;break;case"y":B.instance.position.left=B.instance.originalPosition.left;break}}});A.ui.plugin.add("draggable","scroll",{start:function(C,B){var D=B.options;D.scrollSensitivity=D.scrollSensitivity||20;D.scrollSpeed=D.scrollSpeed||20;B.instance.overflowY=function(E){do{if(/auto|scroll/.test(E.css("overflow"))||(/auto|scroll/).test(E.css("overflow-y"))){return E}E=E.parent()}while(E[0].parentNode);return A(document)}(this);B.instance.overflowX=function(E){do{if(/auto|scroll/.test(E.css("overflow"))||(/auto|scroll/).test(E.css("overflow-x"))){return E}E=E.parent()}while(E[0].parentNode);return A(document)}(this)},drag:function(D,C){var E=C.options;var B=C.instance;if(B.overflowY[0]!=document&&B.overflowY[0].tagName!="HTML"){if(B.overflowY[0].offsetHeight-(C.position.top-B.overflowY[0].scrollTop+B.clickOffset.top)<E.scrollSensitivity){B.overflowY[0].scrollTop=B.overflowY[0].scrollTop+E.scrollSpeed}if((C.position.top-B.overflowY[0].scrollTop+B.clickOffset.top)<E.scrollSensitivity){B.overflowY[0].scrollTop=B.overflowY[0].scrollTop-E.scrollSpeed}}else{if(D.pageY-A(document).scrollTop()<E.scrollSensitivity){A(document).scrollTop(A(document).scrollTop()-E.scrollSpeed)}if(A(window).height()-(D.pageY-A(document).scrollTop())<E.scrollSensitivity){A(document).scrollTop(A(document).scrollTop()+E.scrollSpeed)}}if(B.overflowX[0]!=document&&B.overflowX[0].tagName!="HTML"){if(B.overflowX[0].offsetWidth-(C.position.left-B.overflowX[0].scrollLeft+B.clickOffset.left)<E.scrollSensitivity){B.overflowX[0].scrollLeft=B.overflowX[0].scrollLeft+E.scrollSpeed}if((C.position.top-B.overflowX[0].scrollLeft+B.clickOffset.left)<E.scrollSensitivity){B.overflowX[0].scrollLeft=B.overflowX[0].scrollLeft-E.scrollSpeed}}else{if(D.pageX-A(document).scrollLeft()<E.scrollSensitivity){A(document).scrollLeft(A(document).scrollLeft()-E.scrollSpeed)}if(A(window).width()-(D.pageX-A(document).scrollLeft())<E.scrollSensitivity){A(document).scrollLeft(A(document).scrollLeft()+E.scrollSpeed)}}C.instance.recallOffset(D)}});A.ui.plugin.add("draggable","snap",{start:function(C,B){B.instance.snapElements=[];A(B.options.snap===true?".ui-draggable":B.options.snap).each(function(){var E=A(this);var D=E.offset();if(this!=B.instance.element[0]){B.instance.snapElements.push({item:this,width:E.outerWidth(),height:E.outerHeight(),top:D.top,left:D.left})}})},drag:function(I,M){var K=M.options.snapTolerance||20;var D=M.absolutePosition.left,C=D+M.instance.helperProportions.width,O=M.absolutePosition.top,N=O+M.instance.helperProportions.height;for(var H=M.instance.snapElements.length-1;H>=0;H--){var E=M.instance.snapElements[H].left,B=E+M.instance.snapElements[H].width,Q=M.instance.snapElements[H].top,L=Q+M.instance.snapElements[H].height;if(!((E-K<D&&D<B+K&&Q-K<O&&O<L+K)||(E-K<D&&D<B+K&&Q-K<N&&N<L+K)||(E-K<C&&C<B+K&&Q-K<O&&O<L+K)||(E-K<C&&C<B+K&&Q-K<N&&N<L+K))){continue}if(M.options.snapMode!="inner"){var J=Math.abs(Q-N)<=20;var P=Math.abs(L-O)<=20;var G=Math.abs(E-C)<=20;var F=Math.abs(B-D)<=20;if(J){M.position.top=Q-M.instance.offset.top+M.instance.clickOffset.top-M.instance.helperProportions.height}if(P){M.position.top=L-M.instance.offset.top+M.instance.clickOffset.top}if(G){M.position.left=E-M.instance.offset.left+M.instance.clickOffset.left-M.instance.helperProportions.width}if(F){M.position.left=B-M.instance.offset.left+M.instance.clickOffset.left}}if(M.options.snapMode!="outer"){var J=Math.abs(Q-O)<=20;var P=Math.abs(L-N)<=20;var G=Math.abs(E-D)<=20;var F=Math.abs(B-C)<=20;if(J){M.position.top=Q-M.instance.offset.top+M.instance.clickOffset.top}if(P){M.position.top=L-M.instance.offset.top+M.instance.clickOffset.top-M.instance.helperProportions.height}if(G){M.position.left=E-M.instance.offset.left+M.instance.clickOffset.left}if(F){M.position.left=B-M.instance.offset.left+M.instance.clickOffset.left-M.instance.helperProportions.width}}}}});A.ui.plugin.add("draggable","connectToSortable",{start:function(C,B){B.instance.sortable=A.data(A(B.options.connectToSortable)[0],"sortable");B.instance.sortableOffset=B.instance.sortable.element.offset();B.instance.sortableOuterWidth=B.instance.sortable.element.outerWidth();B.instance.sortableOuterHeight=B.instance.sortable.element.outerHeight();if(B.instance.sortable.options.revert){B.instance.sortable.shouldRevert=true}},stop:function(D,C){var B=C.instance.sortable;if(B.isOver){B.isOver=0;C.instance.cancelHelperRemoval=true;B.cancelHelperRemoval=false;if(B.shouldRevert){B.options.revert=true}B.stop(D);B.options.helper="original"}},drag:function(F,E){var D=E.instance.sortable;E.instance.position.absolute=E.absolutePosition;if(D.intersectsWith.call(E.instance,{left:E.instance.sortableOffset.left,top:E.instance.sortableOffset.top,width:E.instance.sortableOuterWidth,height:E.instance.sortableOuterHeight})){if(!D.isOver){D.isOver=1;var B=D.options.placeholderElement?A(D.options.placeholderElement,A(D.options.items,D.element)).innerHeight():A(D.options.items,D.element).innerHeight();var C=D.options.placeholderElement?A(D.options.placeholderElement,A(D.options.items,D.element)).innerWidth():A(D.options.items,D.element).innerWidth();D.currentItem=A(this).clone().appendTo(D.element);D.options.helper=function(){return E.helper[0]};D.start(F);D.clickOffset.top=E.instance.clickOffset.top;D.clickOffset.left=E.instance.clickOffset.left;D.offset.left-=E.absolutePosition.left-D.position.absolute.left;D.offset.top-=E.absolutePosition.top-D.position.absolute.top;D.helperProportions={width:C,height:B};E.helper.animate({height:B,width:C},500);E.instance.propagate("toSortable",F)}if(D.currentItem){D.drag(F)}}else{if(D.isOver){D.isOver=0;D.cancelHelperRemoval=true;D.options.revert=false;D.stop(F);D.options.helper="original";D.currentItem.remove();D.placeholder.remove();E.helper.animate({height:this.innerHeight(),width:this.innerWidth()},500);E.instance.propagate("fromSortable",F)}}}})})(jQuery);(function(A){A.fn.extend({droppable:function(C){var B=Array.prototype.slice.call(arguments,1);return this.each(function(){if(typeof C=="string"){var D=A.data(this,"droppable");if(D){D[C].apply(D,B)}}else{if(!A.data(this,"droppable")){new A.ui.droppable(this,C)}}})}});A.ui.droppable=function(E,C){var B=this;this.element=A(E);A.data(E,"droppable",this);this.element.addClass("ui-droppable");var F=this.options=C=A.extend({},A.ui.droppable.defaults,C);var D=F.accept;F=A.extend(F,{accept:F.accept&&F.accept.constructor==Function?F.accept:function(G){return A(G).is(D)}});A(E).bind("setData.droppable",function(H,G,I){F[G]=I}).bind("getData.droppable",function(H,G){return F[G]}).bind("remove",function(){B.destroy()});this.proportions={width:this.element.outerWidth(),height:this.element.outerHeight()};A.ui.ddmanager.droppables.push({item:this,over:0,out:1})};A.extend(A.ui.droppable,{defaults:{disabled:false,tolerance:"intersect"}});A.extend(A.ui.droppable.prototype,{plugins:{},ui:function(B){return{instance:this,draggable:(B.currentItem||B.element),helper:B.helper,position:B.position,absolutePosition:B.positionAbs,options:this.options,element:this.element}},destroy:function(){var B=A.ui.ddmanager.droppables;for(var C=0;C<B.length;C++){if(B[C].item==this){B.splice(C,1)}}this.element.removeClass("ui-droppable ui-droppable-disabled").removeData("droppable").unbind(".droppable")},enable:function(){this.element.removeClass("ui-droppable-disabled");this.options.disabled=false},disable:function(){this.element.addClass("ui-droppable-disabled");this.options.disabled=true},over:function(C){var B=A.ui.ddmanager.current;if(!B||(B.currentItem||B.element)[0]==this.element[0]){return }if(this.options.accept.call(this.element,(B.currentItem||B.element))){A.ui.plugin.call(this,"over",[C,this.ui(B)]);this.element.triggerHandler("dropover",[C,this.ui(B)],this.options.over)}},out:function(C){var B=A.ui.ddmanager.current;if(!B||(B.currentItem||B.element)[0]==this.element[0]){return }if(this.options.accept.call(this.element,(B.currentItem||B.element))){A.ui.plugin.call(this,"out",[C,this.ui(B)]);this.element.triggerHandler("dropout",[C,this.ui(B)],this.options.out)}},drop:function(D,C){var B=C||A.ui.ddmanager.current;if(!B||(B.currentItem||B.element)[0]==this.element[0]){return }var E=false;this.element.find(".ui-droppable").each(function(){var F=A.data(this,"droppable");if(F.options.greedy&&A.ui.intersect(B,{item:F,offset:F.element.offset()},F.options.tolerance)){E=true;return false}});if(E){return }if(this.options.accept.call(this.element,(B.currentItem||B.element))){A.ui.plugin.call(this,"drop",[D,this.ui(B)]);this.element.triggerHandler("drop",[D,this.ui(B)],this.options.drop)}},activate:function(C){var B=A.ui.ddmanager.current;A.ui.plugin.call(this,"activate",[C,this.ui(B)]);if(B){this.element.triggerHandler("dropactivate",[C,this.ui(B)],this.options.activate)}},deactivate:function(C){var B=A.ui.ddmanager.current;A.ui.plugin.call(this,"deactivate",[C,this.ui(B)]);if(B){this.element.triggerHandler("dropdeactivate",[C,this.ui(B)],this.options.deactivate)}}});A.ui.intersect=function(L,F,J){if(!F.offset){return false}var D=(L.positionAbs||L.position.absolute).left,C=D+L.helperProportions.width,I=(L.positionAbs||L.position.absolute).top,H=I+L.helperProportions.height;var E=F.offset.left,B=E+F.item.proportions.width,K=F.offset.top,G=K+F.item.proportions.height;switch(J){case"fit":if(!((H-(L.helperProportions.height/2)>K&&I<K)||(I<G&&H>G)||(C>E&&D<E)||(D<B&&C>B))){return false}if(H-(L.helperProportions.height/2)>K&&I<K){return 1}if(I<G&&H>G){return 2}if(C>E&&D<E){return 1}if(D<B&&C>B){return 2}break;case"intersect":return(E<D+(L.helperProportions.width/2)&&C-(L.helperProportions.width/2)<B&&K<I+(L.helperProportions.height/2)&&H-(L.helperProportions.height/2)<G);break;case"pointer":return(E<((L.positionAbs||L.position.absolute).left+L.clickOffset.left)&&((L.positionAbs||L.position.absolute).left+L.clickOffset.left)<B&&K<((L.positionAbs||L.position.absolute).top+L.clickOffset.top)&&((L.positionAbs||L.position.absolute).top+L.clickOffset.top)<G);break;case"touch":return((I>=K&&I<=G)||(H>=K&&H<=G)||(I<K&&H>G))&&((D>=E&&D<=B)||(C>=E&&C<=B)||(D<E&&C>B));break;default:return false;break}};A.ui.ddmanager={current:null,droppables:[],prepareOffsets:function(D,F){var B=A.ui.ddmanager.droppables;var E=F?F.type:null;for(var C=0;C<B.length;C++){if(B[C].item.options.disabled||(D&&!B[C].item.options.accept.call(B[C].item.element,(D.currentItem||D.element)))){continue}B[C].offset=A(B[C].item.element).offset();B[C].item.proportions={width:B[C].item.element.outerWidth(),height:B[C].item.element.outerHeight()};if(E=="dragstart"){B[C].item.activate.call(B[C].item,F)}}},drop:function(B,C){A.each(A.ui.ddmanager.droppables,function(){if(!this.item.options.disabled&&A.ui.intersect(B,this,this.item.options.tolerance)){this.item.drop.call(this.item,C)}if(!this.item.options.disabled&&this.item.options.accept.call(this.item.element,(B.currentItem||B.element))){this.out=1;this.over=0;this.item.deactivate.call(this.item,C)}})},drag:function(B,C){if(B.options.refreshPositions){A.ui.ddmanager.prepareOffsets(B,C)}A.each(A.ui.ddmanager.droppables,function(){if(this.item.disabled||this.greedyChild){return }var E=A.ui.intersect(B,this,this.item.options.tolerance);var F=!E&&this.over==1?"out":(E&&this.over==0?"over":null);if(!F){return }var D=A.data(this.item.element[0],"droppable");if(D.options.greedy){this.item.element.parents(".ui-droppable:eq(0)").each(function(){var G=this;A.each(A.ui.ddmanager.droppables,function(){if(this.item.element[0]!=G){return }this[F]=0;this[F=="out"?"over":"out"]=1;this.greedyChild=(F=="over"?1:0);this.item[F=="out"?"over":"out"].call(this.item,C);return false})})}this[F]=1;this[F=="out"?"over":"out"]=0;this.item[F].call(this.item,C)})}};A.ui.plugin.add("droppable","activeClass",{activate:function(C,B){A(this).addClass(B.options.activeClass)},deactivate:function(C,B){A(this).removeClass(B.options.activeClass)},drop:function(C,B){A(this).removeClass(B.options.activeClass)}});A.ui.plugin.add("droppable","hoverClass",{over:function(C,B){A(this).addClass(B.options.hoverClass)},out:function(C,B){A(this).removeClass(B.options.hoverClass)},drop:function(C,B){A(this).removeClass(B.options.hoverClass)}})})(jQuery);(function(A){A.fn.extend({resizable:function(C,D){var B=Array.prototype.slice.call(arguments,1);return this.each(function(){if(typeof C=="string"){var E=A.data(this,"resizable");if(E){E[C].apply(E,B)}}else{if(!A(this).is(".ui-resizable")){new A.ui.resizable(this,C)}}})}});A.ui.resizable=function(E,H){var O=this;this.element=A(E);A.data(E,"resizable",this);var S=this.element.css("position");this.element.addClass("ui-resizable").css({position:/static/.test(S)?"relative":S});this.options=A.extend({preventDefault:true,transparent:false,minWidth:10,minHeight:10,aspectRatio:false,disableSelection:true,preserveCursor:true,autohide:false,knobHandles:false},H);this.options._aspectRatio=!!(this.options.aspectRatio);this.options.proxy=this.options.proxy||this.options.ghost?"proxy":null;this.options.proxy=this.options.proxy||this.options.animate?"proxy":null;this.options.knobHandles=this.options.knobHandles===true?"ui-resizable-knob-handle":this.options.knobHandles;A(E).bind("setData.resizable",function(X,W,Y){O.options[W]=Y}).bind("getData.resizable",function(X,W){return O.options[W]});var P=this.options;var J="1px solid #DEDEDE";P.defaultTheme={"ui-resizable":{display:"block"},"ui-resizable-handle":{position:"absolute",background:"#F2F2F2",fontSize:"0.1px"},"ui-resizable-n":{cursor:"n-resize",height:"4px",left:"0px",right:"0px",borderTop:J},"ui-resizable-s":{cursor:"s-resize",height:"4px",left:"0px",right:"0px",borderBottom:J},"ui-resizable-e":{cursor:"e-resize",width:"4px",top:"0px",bottom:"0px",borderRight:J},"ui-resizable-w":{cursor:"w-resize",width:"4px",top:"0px",bottom:"0px",borderLeft:J},"ui-resizable-se":{cursor:"se-resize",width:"4px",height:"4px",borderRight:J,borderBottom:J},"ui-resizable-sw":{cursor:"sw-resize",width:"4px",height:"4px",borderBottom:J,borderLeft:J},"ui-resizable-ne":{cursor:"ne-resize",width:"4px",height:"4px",borderRight:J,borderTop:J},"ui-resizable-nw":{cursor:"nw-resize",width:"4px",height:"4px",borderLeft:J,borderTop:J}};P.knobTheme={"ui-resizable-handle":{background:"#F2F2F2",border:"1px solid #808080",height:"8px",width:"8px"},"ui-resizable-n":{cursor:"n-resize",top:"-4px",left:"45%"},"ui-resizable-s":{cursor:"s-resize",bottom:"-4px",left:"45%"},"ui-resizable-e":{cursor:"e-resize",right:"-4px",top:"45%"},"ui-resizable-w":{cursor:"w-resize",left:"-4px",top:"45%"},"ui-resizable-se":{cursor:"se-resize",right:"-4px",bottom:"-4px"},"ui-resizable-sw":{cursor:"sw-resize",left:"-4px",bottom:"-4px"},"ui-resizable-nw":{cursor:"nw-resize",left:"-4px",top:"-4px"},"ui-resizable-ne":{cursor:"ne-resize",right:"-4px",top:"-4px"}};if(!P.proxy&&(this.element.css("position")=="static"||this.element.css("position")==="")){this.element.css("position","relative")}P._nodeName=E.nodeName;if(P._nodeName.match(/textarea|input|select|button|img/i)){var B=this.element;if(/relative/.test(B.css("position"))&&A.browser.opera){B.css({position:"relative",top:"auto",left:"auto"})}B.wrap(A('<div class="ui-wrapper"	style="overflow: hidden;"></div>').css({position:B.css("position"),width:B.outerWidth(),height:B.outerHeight(),top:B.css("top"),left:B.css("left")}));var L=this.element;E=E.parentNode;this.element=A(E);this.element.css({marginLeft:L.css("marginLeft"),marginTop:L.css("marginTop"),marginRight:L.css("marginRight"),marginBottom:L.css("marginBottom")});L.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0});if(A.browser.safari&&P.preventDefault){L.css("resize","none")}P.proportionallyResize=L.css({position:"static",zoom:1,display:"block"});this.element.css({margin:L.css("margin")});this._proportionallyResize()}if(!P.handles){P.handles=!A(".ui-resizable-handle",E).length?"e,s,se":{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}}if(P.handles.constructor==String){if(P.handles=="all"){P.handles="n,e,s,w,se,sw,ne,nw"}var Q=P.handles.split(",");P.handles={};P.zIndex=P.zIndex||1000;var I={handle:"position: absolute; display: none; overflow:hidden;",n:"top: 0pt; width:100%;",e:"right: 0pt; height:100%;",s:"bottom: 0pt; width:100%;",w:"left: 0pt; height:100%;",se:"bottom: 0pt; right: 0px;",sw:"bottom: 0pt; left: 0px;",ne:"top: 0pt; right: 0px;",nw:"top: 0pt; left: 0px;"};for(var T=0;T<Q.length;T++){var U=jQuery.trim(Q[T]),N=P.defaultTheme,G="ui-resizable-"+U,D=!A.ui.css(G)&&!P.knobHandles,R=A.ui.css("ui-resizable-knob-handle"),V=A.extend(N[G],N["ui-resizable-handle"]),C=A.extend(P.knobTheme[G],!R?P.knobTheme["ui-resizable-handle"]:{});var M=/sw|se|ne|nw/.test(U)?{zIndex:++P.zIndex}:{};var K=(D?I[U]:""),F=A(['<div class="ui-resizable-handle ',G,'" style="',K,I.handle,'"></div>'].join("")).css(M);P.handles[U]=".ui-resizable-"+U;this.element.append(F.css(D?V:{}).css(P.knobHandles?C:{}).addClass(P.knobHandles?"ui-resizable-knob-handle":"").addClass(P.knobHandles))}if(P.knobHandles){this.element.addClass("ui-resizable-knob").css(!A.ui.css("ui-resizable-knob")?{}:{})}}this._renderAxis=function(a){a=a||this.element;for(var X in P.handles){if(P.handles[X].constructor==String){P.handles[X]=A(P.handles[X],E).show()}if(P.transparent){P.handles[X].css({opacity:0})}if(this.element.is(".ui-wrapper")&&P._nodeName.match(/textarea|input|select|button/i)){var Y=A(P.handles[X],E),Z=0;Z=/sw|ne|nw|se|n|s/.test(X)?Y.outerHeight():Y.outerWidth();var W=["padding",/ne|nw|n/.test(X)?"Top":/se|sw|s/.test(X)?"Bottom":/^e$/.test(X)?"Right":"Left"].join("");if(!P.transparent){a.css(W,Z)}this._proportionallyResize()}if(!A(P.handles[X]).length){continue}}};this._renderAxis(this.element);P._handles=A(".ui-resizable-handle",O.element);if(P.disableSelection){P._handles.each(function(W,X){A.ui.disableSelection(X)})}P._handles.mouseover(function(){if(!P.resizing){if(this.className){var W=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)}O.axis=P.axis=W&&W[1]?W[1]:"se"}});if(P.autohide){P._handles.hide();A(O.element).addClass("ui-resizable-autohide").hover(function(){A(this).removeClass("ui-resizable-autohide");P._handles.show()},function(){if(!P.resizing){A(this).addClass("ui-resizable-autohide");P._handles.hide()}})}this.element.mouseInteraction({executor:this,delay:0,distance:0,dragPrevention:["input","textarea","button","select","option"],start:this.start,stop:this.stop,drag:this.drag,condition:function(X){if(this.disabled){return false}for(var W in this.options.handles){if(A(this.options.handles[W])[0]==X.target){return true}}return false}})};A.extend(A.ui.resizable.prototype,{plugins:{},ui:function(){return{instance:this,axis:this.options.axis,options:this.options}},_renderProxy:function(){var C=this.element,F=this.options;this.elementOffset=C.offset();if(F.proxy){this.helper=this.helper||A('<div style="overflow:hidden;"></div>');var B=A.browser.msie&&A.browser.version<7,D=(B?1:0),E=(B?2:-1);this.helper.addClass(F.proxy).css({width:C.outerWidth()+E,height:C.outerHeight()+E,position:"absolute",left:this.elementOffset.left-D+"px",top:this.elementOffset.top-D+"px",zIndex:++F.zIndex});this.helper.appendTo("body");if(F.disableSelection){A.ui.disableSelection(this.helper.get(0))}}else{this.helper=C}},propagate:function(C,B){A.ui.plugin.call(this,C,[B,this.ui()]);this.element.triggerHandler(C=="resize"?C:["resize",C].join(""),[B,this.ui()],this.options[C])},destroy:function(){var D=this.element,C=D.children(".ui-resizable").get(0),B=function(E){A(E).removeClass("ui-resizable ui-resizable-disabled").removeMouseInteraction().removeData("resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};B(D);if(D.is(".ui-wrapper")&&C){D.parent().append(A(C).css({position:D.css("position"),width:D.outerWidth(),height:D.outerHeight(),top:D.css("top"),left:D.css("left")})).end().remove();B(C)}},enable:function(){this.element.removeClass("ui-resizable-disabled");this.disabled=false},disable:function(){this.element.addClass("ui-resizable-disabled");this.disabled=true},start:function(I){var C=this.options,B=this.element.position(),D=this.element,H=function(M){return parseInt(M,10)||0},G=A.browser.msie&&A.browser.version<7;C.resizing=true;C.documentScroll={top:A(document).scrollTop(),left:A(document).scrollLeft()};if(D.is(".ui-draggable")||(/absolute/).test(D.css("position"))){var J=A.browser.msie&&!C.containment&&(/absolute/).test(D.css("position"))&&!(/relative/).test(D.parent().css("position"));var K=J?C.documentScroll.top:0,F=J?C.documentScroll.left:0;D.css({position:"absolute",top:(B.top+K),left:(B.left+F)})}if(/relative/.test(D.css("position"))&&A.browser.opera){D.css({position:"relative",top:"auto",left:"auto"})}this._renderProxy();var L=H(this.helper.css("left")),E=H(this.helper.css("top"));this.offset=this.helper.offset();this.position={left:L,top:E};this.size=C.proxy||G?{width:D.outerWidth(),height:D.outerHeight()}:{width:D.width(),height:D.height()};this.originalSize=C.proxy||G?{width:D.outerWidth(),height:D.outerHeight()}:{width:D.width(),height:D.height()};this.originalPosition={left:L,top:E};this.sizeDiff={width:D.outerWidth()-D.width(),height:D.outerHeight()-D.height()};this.originalMousePosition={left:I.pageX,top:I.pageY};C.aspectRatio=(typeof C.aspectRatio=="number")?C.aspectRatio:((this.originalSize.height/this.originalSize.width)||1);if(C.preserveCursor){A("body").css("cursor",this.axis+"-resize")}this.propagate("start",I);return false},stop:function(J){this.options.resizing=false;var F=this.options,I=function(M){return parseInt(M,10)||0},L=this;if(F.proxy){var E=F.proportionallyResize,B=E&&/textarea/i.test(E.get(0).nodeName),C=B&&A.ui.hasScroll(E.get(0),"left")?0:L.sizeDiff.height,H=B?0:L.sizeDiff.width;var D={width:(L.size.width-H),height:(L.size.height-C)},G=parseInt(L.element.css("left"),10)+(L.position.left-L.originalPosition.left),K=parseInt(L.element.css("top"),10)+(L.position.top-L.originalPosition.top);if(!F.animate){this.element.css(A.extend(D,{top:K,left:G}))}if(F.proxy&&!F.animate){this._proportionallyResize()}this.helper.remove()}if(F.preserveCursor){A("body").css("cursor","auto")}this.propagate("stop",J);return false},drag:function(I){var D=this.helper,C=this.options,J={},M=this,F=this.originalMousePosition,K=this.axis;var N=(I.pageX-F.left)||0,L=(I.pageY-F.top)||0;var E=this.change[K];if(!E){return false}var H=E.apply(this,[I,N,L]),G=A.browser.msie&&A.browser.version<7,B=this.sizeDiff;if(C._aspectRatio||I.shiftKey){H=this._updateRatio(H,I)}H=this._respectSize(H,I);this.propagate("resize",I);D.css({top:this.position.top+"px",left:this.position.left+"px",width:this.size.width+"px",height:this.size.height+"px"});if(!C.proxy&&C.proportionallyResize){this._proportionallyResize()}this._updateCache(H);return false},_updateCache:function(B){var C=this.options;this.offset=this.helper.offset();if(B.left){this.position.left=B.left}if(B.top){this.position.top=B.top}if(B.height){this.size.height=B.height}if(B.width){this.size.width=B.width}},_updateRatio:function(D,E){var F=this.options,G=this.position,C=this.size,B=this.axis;if(D.height){D.width=Math.round(C.height/F.aspectRatio)}else{if(D.width){D.height=Math.round(C.width*F.aspectRatio)}}if(B=="sw"){D.left=G.left+(C.width-D.width);D.top=null}if(B=="nw"){D.top=G.top+(C.height-D.height);D.left=G.left+(C.width-D.width)}return D},_respectSize:function(H,I){var F=this.helper,E=this.options,N=E._aspectRatio||I.shiftKey,M=this.axis,P=H.width&&E.maxWidth&&E.maxWidth<H.width,J=H.height&&E.maxHeight&&E.maxHeight<H.height,D=H.width&&E.minWidth&&E.minWidth>H.width,O=H.height&&E.minHeight&&E.minHeight>H.height;if(D){H.width=E.minWidth}if(O){H.height=E.minHeight}if(P){H.width=E.maxWidth}if(J){H.height=E.maxHeight}var C=this.originalPosition.left+this.originalSize.width,L=this.position.top+this.size.height;var G=/sw|nw|w/.test(M),B=/nw|ne|n/.test(M);if(D&&G){H.left=C-E.minWidth}if(P&&G){H.left=C-E.maxWidth}if(O&&B){H.top=L-E.minHeight}if(J&&B){H.top=L-E.maxHeight}var K=!H.width&&!H.height;if(K&&!H.left&&H.top){H.top=null}else{if(K&&!H.top&&H.left){H.left=null}}return H},_proportionallyResize:function(){var F=this.options;if(!F.proportionallyResize){return }var D=F.proportionallyResize,C=this.helper||this.element;if(!F.borderDif){var B=[D.css("borderTopWidth"),D.css("borderRightWidth"),D.css("borderBottomWidth"),D.css("borderLeftWidth")],E=[D.css("paddingTop"),D.css("paddingRight"),D.css("paddingBottom"),D.css("paddingLeft")];F.borderDif=A.map(B,function(G,I){var H=parseInt(G,10)||0,J=parseInt(E[I],10)||0;return H+J})}D.css({height:(C.height()-F.borderDif[0]-F.borderDif[2])+"px",width:(C.width()-F.borderDif[1]-F.borderDif[3])+"px"})},change:{e:function(D,C,B){return{width:this.originalSize.width+C}},w:function(F,C,B){var G=this.options,D=this.originalSize,E=this.originalPosition;return{left:E.left+C,width:D.width-C}},n:function(F,C,B){var G=this.options,D=this.originalSize,E=this.originalPosition;return{top:E.top+B,height:D.height-B}},s:function(D,C,B){return{height:this.originalSize.height+B}},se:function(D,C,B){return A.extend(this.change.s.apply(this,arguments),this.change.e.apply(this,[D,C,B]))},sw:function(D,C,B){return A.extend(this.change.s.apply(this,arguments),this.change.w.apply(this,[D,C,B]))},ne:function(D,C,B){return A.extend(this.change.n.apply(this,arguments),this.change.e.apply(this,[D,C,B]))},nw:function(D,C,B){return A.extend(this.change.n.apply(this,arguments),this.change.w.apply(this,[D,C,B]))}}});A.ui.plugin.add("resizable","containment",{start:function(I,K){var E=K.options,M=K.instance,G=M.element;var C=E.containment,F=(C instanceof jQuery)?C.get(0):(/parent/.test(C))?G.parent().get(0):C;if(!F){return }if(/document/.test(C)||C==document){M.containerOffset={left:0,top:0};M.parentData={element:A(document),left:0,top:0,width:A(document).width(),height:A(document).height()||document.body.parentNode.scrollHeight}}else{M.containerOffset=A(F).offset(),M.containerSize={height:A(F).innerHeight(),width:A(F).innerWidth()};var J=M.containerOffset,B=M.containerSize.height,H=M.containerSize.width,D=(A.ui.hasScroll(F,"left")?F.scrollWidth:H),L=(A.ui.hasScroll(F)?F.scrollHeight:B);M.parentData={element:F,left:J.left,top:J.top,width:D,height:L}}},resize:function(F,I){var C=I.options,L=I.instance,B=L.containerSize,H=L.containerOffset,E=L.size,G=L.position,J=C._aspectRatio||F.shiftKey;if(G.left<(C.proxy?H.left:0)){L.size.width=L.size.width+(C.proxy?(L.position.left-H.left):L.position.left);if(J){L.size.height=L.size.width*C.aspectRatio}L.position.left=C.proxy?H.left:0}if(G.top<(C.proxy?H.top:0)){L.size.height=L.size.height+(C.proxy?(L.position.top-H.top):L.position.top);if(J){L.size.width=L.size.height/C.aspectRatio}L.position.top=C.proxy?H.top:0}var D=(C.proxy?L.offset.left-H.left:L.position.left)+L.sizeDiff.width,K=(C.proxy?L.offset.top-H.top:L.position.top)+L.sizeDiff.height;if(D+L.size.width>=L.parentData.width){L.size.width=L.parentData.width-D;if(J){L.size.height=L.size.width*C.aspectRatio}}if(K+L.size.height>=L.parentData.height){L.size.height=L.parentData.height-K;if(J){L.size.width=L.size.height/C.aspectRatio}}}});A.ui.plugin.add("resizable","grid",{resize:function(H,J){var D=J.options,L=J.instance,G=L.size,E=L.originalSize,F=L.originalPosition,K=L.axis,I=D._aspectRatio||H.shiftKey;D.grid=typeof D.grid=="number"?[D.grid,D.grid]:D.grid;var C=Math.round((G.width-E.width)/D.grid[0])*D.grid[0],B=Math.round((G.height-E.height)/D.grid[1])*D.grid[1];if(/^(se|s|e)$/.test(K)){L.size.width=E.width+C;L.size.height=E.height+B}else{if(/^(ne)$/.test(K)){L.size.width=E.width+C;L.size.height=E.height+B;L.position.top=F.top-B}else{if(/^(sw)$/.test(K)){L.size.width=E.width+C;L.size.height=E.height+B;L.position.left=F.left-C}else{L.size.width=E.width+C;L.size.height=E.height+B;L.position.top=F.top-B;L.position.left=F.left-C}}}}});A.ui.plugin.add("resizable","animate",{stop:function(I,K){var F=K.options,L=K.instance;var E=F.proportionallyResize,B=E&&/textarea/i.test(E.get(0).nodeName),C=B&&A.ui.hasScroll(E.get(0),"left")?0:L.sizeDiff.height,H=B?0:L.sizeDiff.width;var D={width:(L.size.width-H),height:(L.size.height-C)},G=parseInt(L.element.css("left"),10)+(L.position.left-L.originalPosition.left),J=parseInt(L.element.css("top"),10)+(L.position.top-L.originalPosition.top);L.element.animate(A.extend(D,{top:J,left:G}),{duration:F.animateDuration||"slow",easing:F.animateEasing||"swing",step:function(){if(E){E.css({width:L.element.css("width"),height:L.element.css("height")})}}})}});A.ui.plugin.add("resizable","ghost",{start:function(E,D){var F=D.options,B=D.instance,G=F.proportionallyResize,C=B.size;if(!G){B.ghost=B.element.clone()}else{B.ghost=G.clone()}B.ghost.css({opacity:0.25,display:"block",position:"relative",height:C.height,width:C.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof F.ghost=="string"?F.ghost:"");B.ghost.appendTo(B.helper)},resize:function(D,C){var E=C.options,B=C.instance,F=E.proportionallyResize;if(B.ghost){B.ghost.css({position:"relative",height:B.size.height,width:B.size.width})}},stop:function(D,C){var E=C.options,B=C.instance,F=E.proportionallyResize;if(B.ghost&&B.helper){B.helper.get(0).removeChild(B.ghost.get(0))}}})})(jQuery);(function(A){A.fn.extend({selectable:function(C){var B=Array.prototype.slice.call(arguments,1);return this.each(function(){if(typeof C=="string"){var D=A.data(this,"selectable");if(D){D[C].apply(D,B)}}else{if(!A.data(this,"selectable")){new A.ui.selectable(this,C)}}})}});A.ui.selectable=function(D,C){var B=this;this.element=A(D);A.data(D,"selectable",this);this.element.addClass("ui-selectable");this.options=A.extend({appendTo:"body",autoRefresh:true,filter:"*",tolerance:"touch"},C);A(D).bind("setData.selectable",function(G,F,H){B.options[F]=H}).bind("getData.selectable",function(G,F){return B.options[F]});this.dragged=false;var E;this.refresh=function(){E=A(B.options.filter,B.element[0]);E.each(function(){var F=A(this);var G=F.offset();A.data(this,"selectable-item",{element:this,$element:F,left:G.left,top:G.top,right:G.left+F.width(),bottom:G.top+F.height(),startselected:false,selected:F.hasClass("ui-selected"),selecting:F.hasClass("ui-selecting"),unselecting:F.hasClass("ui-unselecting")})})};this.refresh();this.selectees=E.addClass("ui-selectee");this.element.mouseInteraction({executor:this,appendTo:"body",delay:0,distance:0,dragPrevention:["input","textarea","button","select","option"],start:this.start,stop:this.stop,drag:this.drag,condition:function(G){var F=false;A(G.target).parents().andSelf().each(function(){if(A.data(this,"selectable-item")){F=true}});return this.options.keyboard?!F:true}});this.helper=A(document.createElement("div")).css({border:"1px dotted black"})};A.extend(A.ui.selectable.prototype,{toggle:function(){if(this.disabled){this.enable()}else{this.disable()}},destroy:function(){this.element.removeClass("ui-selectable ui-selectable-disabled").removeData("selectable").unbind(".selectable").removeMouseInteraction()},enable:function(){this.element.removeClass("ui-selectable-disabled");this.disabled=false},disable:function(){this.element.addClass("ui-selectable-disabled");this.disabled=true},start:function(D,C){this.opos=[D.pageX,D.pageY];if(this.disabled){return }var B=this.options;this.selectees=A(B.filter,C);this.element.triggerHandler("selectablestart",[D,{selectable:C,options:B}],B.start);A("body").append(this.helper);this.helper.css({"z-index":100,position:"absolute",left:D.clientX,top:D.clientY,width:0,height:0});if(B.autoRefresh){this.refresh()}this.selectees.filter(".ui-selected").each(function(){var E=A.data(this,"selectable-item");E.startselected=true;if(!D.ctrlKey){E.$element.removeClass("ui-selected");E.selected=false;E.$element.addClass("ui-unselecting");E.unselecting=true;A(this.element).triggerHandler("selectableunselecting",[D,{selectable:C,unselecting:E.element,options:B}],B.unselecting)}})},drag:function(I,G){this.dragged=true;if(this.disabled){return }var D=this.options;var C=this.opos[0],H=this.opos[1],B=I.pageX,F=I.pageY;if(C>B){var E=B;B=C;C=E}if(H>F){var E=F;F=H;H=E}this.helper.css({left:C,top:H,width:B-C,height:F-H});this.selectees.each(function(){var J=A.data(this,"selectable-item");if(!J||J.element==G){return }var K=false;if(D.tolerance=="touch"){K=(!(J.left>B||J.right<C||J.top>F||J.bottom<H))}else{if(D.tolerance=="fit"){K=(J.left>C&&J.right<B&&J.top>H&&J.bottom<F)}}if(K){if(J.selected){J.$element.removeClass("ui-selected");J.selected=false}if(J.unselecting){J.$element.removeClass("ui-unselecting");J.unselecting=false}if(!J.selecting){J.$element.addClass("ui-selecting");J.selecting=true;A(this.element).triggerHandler("selectableselecting",[I,{selectable:G,selecting:J.element,options:D}],D.selecting)}}else{if(J.selecting){if(I.ctrlKey&&J.startselected){J.$element.removeClass("ui-selecting");J.selecting=false;J.$element.addClass("ui-selected");J.selected=true}else{J.$element.removeClass("ui-selecting");J.selecting=false;if(J.startselected){J.$element.addClass("ui-unselecting");J.unselecting=true}A(this.element).triggerHandler("selectableunselecting",[I,{selectable:G,unselecting:J.element,options:D}],D.unselecting)}}if(J.selected){if(!I.ctrlKey&&!J.startselected){J.$element.removeClass("ui-selected");J.selected=false;J.$element.addClass("ui-unselecting");J.unselecting=true;A(this.element).triggerHandler("selectableunselecting",[I,{selectable:G,unselecting:J.element,options:D}],D.unselecting)}}}})},stop:function(D,C){this.dragged=false;var B=this.options;A(".ui-unselecting",this.element).each(function(){var E=A.data(this,"selectable-item");E.$element.removeClass("ui-unselecting");E.unselecting=false;E.startselected=false;A(this.element).triggerHandler("selectableunselected",[D,{selectable:C,unselected:E.element,options:B}],B.unselected)});A(".ui-selecting",this.element).each(function(){var E=A.data(this,"selectable-item");E.$element.removeClass("ui-selecting").addClass("ui-selected");E.selecting=false;E.selected=true;E.startselected=true;A(this.element).triggerHandler("selectableselected",[D,{selectable:C,selected:E.element,options:B}],B.selected)});A(this.element).triggerHandler("selectablestop",[D,{selectable:C,options:this.options}],this.options.stop);this.helper.remove()}})})(jQuery);(function(A){if(window.Node&&Node.prototype&&!Node.prototype.contains){Node.prototype.contains=function(B){return !!(this.compareDocumentPosition(B)&16)}}A.fn.extend({sortable:function(C){var B=Array.prototype.slice.call(arguments,1);if(C=="serialize"||C=="toArray"){return A.data(this[0],"sortable")[C](arguments[1])}return this.each(function(){if(typeof C=="string"){var D=A.data(this,"sortable");if(D){D[C].apply(D,B)}}else{if(!A.data(this,"sortable")){new A.ui.sortable(this,C)}}})}});A.ui.sortable=function(D,C){var B=this;this.element=A(D);this.containerCache={};A.data(D,"sortable",this);this.element.addClass("ui-sortable");this.options=A.extend({},C);var E=this.options;A.extend(E,{items:this.options.items||"> *",zIndex:this.options.zIndex||1000,startCondition:function(){return !B.options.disabled}});A(D).bind("setData.sortable",function(G,F,H){B.options[F]=H}).bind("getData.sortable",function(G,F){return B.options[F]});this.refresh();this.floating=this.items.length?(/left|right/).test(this.items[0].item.css("float")):false;if(!(/(relative|absolute|fixed)/).test(this.element.css("position"))){this.element.css("position","relative")}this.offset=this.element.offset();this.element.mouseInteraction({executor:this,delay:E.delay,distance:E.distance||0,dragPrevention:E.prevention?E.prevention.toLowerCase().split(","):["input","textarea","button","select","option"],start:this.start,stop:this.stop,drag:this.drag,condition:function(H){if(this.options.disabled||this.options.type=="static"){return false}var G=null,F=A(H.target).parents().each(function(){if(A.data(this,"sortable-item")){G=A(this);return false}});if(A.data(H.target,"sortable-item")){G=A(H.target)}if(!G){return false}if(this.options.handle){var I=false;A(this.options.handle,G).each(function(){if(this==H.target){I=true}});if(!I){return false}}this.currentItem=G;return true}});if(E.cursorAt&&E.cursorAt.constructor==Array){E.cursorAt={left:E.cursorAt[0],top:E.cursorAt[1]}}};A.extend(A.ui.sortable.prototype,{plugins:{},ui:function(B){return{helper:(B||this)["helper"],placeholder:(B||this)["placeholder"]||A([]),position:(B||this)["position"].current,absolutePosition:(B||this)["position"].absolute,instance:this,options:this.options,element:this.element,item:(B||this)["currentItem"],sender:B?B.element:null}},propagate:function(D,C,B){A.ui.plugin.call(this,D,[C,this.ui(B)]);this.element.triggerHandler(D=="sort"?D:"sort"+D,[C,this.ui(B)],this.options[D])},serialize:function(D){var B=A(this.options.items,this.element).not(".ui-sortable-helper");var C=[];D=D||{};B.each(function(){var E=(A(this).attr(D.attribute||"id")||"").match(D.expression||(/(.+)[-=_](.+)/));if(E){C.push((D.key||E[1])+"[]="+(D.key?E[1]:E[2]))}});return C.join("&")},toArray:function(B){var C=A(this.options.items,this.element).not(".ui-sortable-helper");var D=[];C.each(function(){D.push(A(this).attr(B||"id"))});return D},enable:function(){this.element.removeClass("ui-sortable-disabled");this.options.disabled=false},disable:function(){this.element.addClass("ui-sortable-disabled");this.options.disabled=true},intersectsWith:function(I){var D=this.position.absolute.left,C=D+this.helperProportions.width,H=this.position.absolute.top,G=H+this.helperProportions.height;var E=I.left,B=E+I.width,J=I.top,F=J+I.height;return(E<D+(this.helperProportions.width/2)&&C-(this.helperProportions.width/2)<B&&J<H+(this.helperProportions.height/2)&&G-(this.helperProportions.height/2)<F)},intersectsWithEdge:function(I){var D=this.position.absolute.left,C=D+this.helperProportions.width,H=this.position.absolute.top,G=H+this.helperProportions.height;var E=I.left,B=E+I.width,J=I.top,F=J+I.height;if(!(E<D+(this.helperProportions.width/2)&&C-(this.helperProportions.width/2)<B&&J<H+(this.helperProportions.height/2)&&G-(this.helperProportions.height/2)<F)){return false}if(this.floating){if(C>E&&D<E){return 2}if(D<B&&C>B){return 1}}else{if(G>J&&H<J){return 1}if(H<F&&G>F){return 2}}return false},inEmptyZone:function(B){if(!A(B.options.items,B.element).length){return B.options.dropOnEmpty?true:false}var C=A(B.options.items,B.element).not(".ui-sortable-helper");C=A(C[C.length-1]);var D=C.offset()[this.floating?"left":"top"]+C[0][this.floating?"offsetWidth":"offsetHeight"];return(this.position.absolute[this.floating?"left":"top"]>D)},refresh:function(){this.refreshItems();this.refreshPositions()},refreshItems:function(){this.items=[];this.containers=[this];var B=this.items;var D=[A(this.options.items,this.element)];if(this.options.connectWith){for(var E=this.options.connectWith.length-1;E>=0;E--){var G=A(this.options.connectWith[E]);for(var C=G.length-1;C>=0;C--){var F=A.data(G[C],"sortable");if(F&&!F.options.disabled){D.push(A(F.options.items,F.element));this.containers.push(F)}}}}for(var E=D.length-1;E>=0;E--){D[E].each(function(){A.data(this,"sortable-item",true);B.push({item:A(this),width:0,height:0,left:0,top:0})})}},refreshPositions:function(B){for(var C=this.items.length-1;C>=0;C--){if(!B){this.items[C].width=this.items[C].item.outerWidth()}if(!B){this.items[C].height=this.items[C].item.outerHeight()}var D=this.items[C].item.offset();this.items[C].left=D.left;this.items[C].top=D.top}for(var C=this.containers.length-1;C>=0;C--){var D=this.containers[C].element.offset();this.containers[C].containerCache.left=D.left;this.containers[C].containerCache.top=D.top;this.containers[C].containerCache.width=this.containers[C].element.outerWidth();this.containers[C].containerCache.height=this.containers[C].element.outerHeight()}},destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled").removeData("sortable").unbind(".sortable").removeMouseInteraction();for(var B=this.items.length-1;B>=0;B--){this.items[B].item.removeData("sortable-item")}},createPlaceholder:function(B){(B||this).placeholderElement=this.options.placeholderElement?A(this.options.placeholderElement,(B||this).currentItem):(B||this).currentItem;(B||this).placeholder=A("<div></div>").addClass(this.options.placeholder).appendTo("body").css({position:"absolute"}).css((B||this).placeholderElement.offset()).css({width:(B||this).placeholderElement.outerWidth(),height:(B||this).placeholderElement.outerHeight()})},contactContainers:function(E){for(var C=this.containers.length-1;C>=0;C--){if(this.intersectsWith(this.containers[C].containerCache)){if(!this.containers[C].containerCache.over){if(this.currentContainer!=this.containers[C]){var H=10000;var G=null;var D=this.position.absolute[this.containers[C].floating?"left":"top"];for(var B=this.items.length-1;B>=0;B--){if(!this.containers[C].element[0].contains(this.items[B].item[0])){continue}var F=this.items[B][this.containers[C].floating?"left":"top"];if(Math.abs(F-D)<H){H=Math.abs(F-D);G=this.items[B]}}if(this.placeholder){this.placeholder.remove()}if(this.containers[C].options.placeholder){this.containers[C].createPlaceholder(this)}else{this.placeholder=null;this.placeholderElement=null}G?this.rearrange(E,G):this.rearrange(E,null,this.containers[C].element);this.propagate("change",E);this.containers[C].propagate("change",E,this);this.currentContainer=this.containers[C]}this.containers[C].propagate("over",E,this);this.containers[C].containerCache.over=1}}else{if(this.containers[C].containerCache.over){this.containers[C].propagate("out",E,this);this.containers[C].containerCache.over=0}}}},start:function(D,C){var E=this.options;this.refresh();this.helper=typeof E.helper=="function"?A(E.helper.apply(this.element[0],[D,this.currentItem])):this.currentItem.clone();if(!this.helper.parents("body").length){this.helper.appendTo(E.appendTo||this.currentItem[0].parentNode)}this.helper.css({position:"absolute",clear:"both"}).addClass("ui-sortable-helper");A.extend(this,{offsetParent:this.helper.offsetParent(),offsets:{absolute:this.currentItem.offset()},mouse:{start:{top:D.pageY,left:D.pageX}},margins:{top:parseInt(this.currentItem.css("marginTop"))||0,left:parseInt(this.currentItem.css("marginLeft"))||0}});this.offsets.parent=this.offsetParent.offset();this.clickOffset={left:D.pageX-this.offsets.absolute.left,top:D.pageY-this.offsets.absolute.top};this.originalPosition={left:this.offsets.absolute.left-this.offsets.parent.left-this.margins.left,top:this.offsets.absolute.top-this.offsets.parent.top-this.margins.top};this.offset={left:D.pageX-this.originalPosition.left,top:D.pageY-this.originalPosition.top};A.extend(this,{position:{current:{top:D.pageY-this.offset.top,left:D.pageX-this.offset.left},absolute:{left:D.pageX-this.clickOffset.left,top:D.pageY-this.clickOffset.top},dom:this.currentItem.prev()[0]}});if(E.placeholder){this.createPlaceholder()}this.propagate("start",D);this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()};if(E.cursorAt){if(E.cursorAt.top!=undefined||E.cursorAt.bottom!=undefined){this.offset.top-=this.clickOffset.top-(E.cursorAt.top!=undefined?E.cursorAt.top:(this.helperProportions.height-E.cursorAt.bottom));this.clickOffset.top=(E.cursorAt.top!=undefined?E.cursorAt.top:(this.helperProportions.height-E.cursorAt.bottom))}if(E.cursorAt.left!=undefined||E.cursorAt.right!=undefined){this.offset.left-=this.clickOffset.left-(E.cursorAt.left!=undefined?E.cursorAt.left:(this.helperProportions.width-E.cursorAt.right));this.clickOffset.left=(E.cursorAt.left!=undefined?E.cursorAt.left:(this.helperProportions.width-E.cursorAt.right))}}if(this.options.placeholder!="clone"){A(this.currentItem).css("visibility","hidden")}for(var B=this.containers.length-1;B>=0;B--){this.containers[B].propagate("activate",D,this)}if(A.ui.ddmanager){A.ui.ddmanager.current=this}if(A.ui.ddmanager&&!E.dropBehaviour){A.ui.ddmanager.prepareOffsets(this,D)}this.dragging=true;return false},stop:function(C){this.propagate("stop",C);if(this.position.dom!=this.currentItem.prev()[0]){this.propagate("update",C)}if(!this.element[0].contains(this.currentItem[0])){this.propagate("remove",C);for(var B=this.containers.length-1;B>=0;B--){if(this.containers[B].element[0].contains(this.currentItem[0])){this.containers[B].propagate("update",C,this);this.containers[B].propagate("receive",C,this)}}}for(var B=this.containers.length-1;B>=0;B--){this.containers[B].propagate("deactivate",C,this);if(this.containers[B].containerCache.over){this.containers[B].propagate("out",C,this);this.containers[B].containerCache.over=0}}if(A.ui.ddmanager&&!this.options.dropBehaviour){A.ui.ddmanager.drop(this,C)}this.dragging=false;if(this.cancelHelperRemoval){return false}A(this.currentItem).css("visibility","");if(this.placeholder){this.placeholder.remove()}this.helper.remove();return false},drag:function(C){this.position.current={top:C.pageY-this.offset.top,left:C.pageX-this.offset.left};this.position.absolute={left:C.pageX-this.clickOffset.left,top:C.pageY-this.clickOffset.top};for(var B=this.items.length-1;B>=0;B--){var D=this.intersectsWithEdge(this.items[B]);if(!D){continue}if(this.items[B].item[0]!=this.currentItem[0]&&this.currentItem[D==1?"next":"prev"]()[0]!=this.items[B].item[0]&&!this.currentItem[0].contains(this.items[B].item[0])&&(this.options.type=="semi-dynamic"?!this.element[0].contains(this.items[B].item[0]):true)){this.direction=D==1?"down":"up";this.rearrange(C,this.items[B]);this.propagate("change",C);break}}this.contactContainers(C);if(A.ui.ddmanager){A.ui.ddmanager.drag(this,C)}this.propagate("sort",C);this.helper.css({left:this.position.current.left+"px",top:this.position.current.top+"px"});return false},rearrange:function(D,C,B){B?B.append(this.currentItem):C.item[this.direction=="down"?"before":"after"](this.currentItem);this.refreshPositions(true);if(this.placeholderElement){this.placeholder.css(this.placeholderElement.offset())}}});A.ui.plugin.add("sortable","cursor",{start:function(D,C){var B=A("body");if(B.css("cursor")){C.options._cursor=B.css("cursor")}B.css("cursor",C.options.cursor)},stop:function(C,B){if(B.options._cursor){A("body").css("cursor",B.options._cursor)}}});A.ui.plugin.add("sortable","zIndex",{start:function(D,C){var B=C.helper;if(B.css("zIndex")){C.options._zIndex=B.css("zIndex")}B.css("zIndex",C.options.zIndex)},stop:function(C,B){if(B.options._zIndex){A(B.helper).css("zIndex",B.options._zIndex)}}});A.ui.plugin.add("sortable","opacity",{start:function(D,C){var B=C.helper;if(B.css("opacity")){C.options._opacity=B.css("opacity")}B.css("opacity",C.options.opacity)},stop:function(C,B){if(B.options._opacity){A(B.helper).css("opacity",B.options._opacity)}}});A.ui.plugin.add("sortable","revert",{stop:function(D,C){var B=C.instance;B.cancelHelperRemoval=true;var E=B.currentItem.offset();var F=B.helper.offsetParent().offset();if(C.instance.options.zIndex){C.helper.css("zIndex",C.instance.options.zIndex)}if(C.instance.placeholder){C.instance.placeholder.animate({opacity:"hide"},parseInt(C.options.revert,10)||500)}C.helper.animate({left:E.left-F.left-B.margins.left,top:E.top-F.top-B.margins.top},parseInt(C.options.revert,10)||500,function(){B.currentItem.css("visibility","visible");window.setTimeout(function(){if(B.placeholder){B.placeholder.remove()}B.helper.remove();if(C.options._zIndex){C.helper.css("zIndex",C.options._zIndex)}},50)})}});A.ui.plugin.add("sortable","containment",{start:function(D,B){var F=B.options;if((F.containment.left!=undefined||F.containment.constructor==Array)&&!F._containment){return }if(!F._containment){F._containment=F.containment}if(F._containment=="parent"){F._containment=this[0].parentNode}if(F._containment=="sortable"){F._containment=this[0]}if(F._containment=="document"){F.containment=[0,0,A(document).width(),(A(document).height()||document.body.parentNode.scrollHeight)]}else{var C=A(F._containment);var E=C.offset();F.containment=[E.left,E.top,E.left+(C.outerWidth()||C[0].scrollWidth),E.top+(C.outerHeight()||C[0].scrollHeight)]}},sort:function(E,I){var B=I.options;var D=I.helper;var H=B.containment;var K=I.instance;var F=(parseInt(K.offsetParent.css("borderLeftWidth"),10)||0);var J=(parseInt(K.offsetParent.css("borderRightWidth"),10)||0);var C=(parseInt(K.offsetParent.css("borderTopWidth"),10)||0);var G=(parseInt(K.offsetParent.css("borderBottomWidth"),10)||0);if(H.constructor==Array){if((K.position.absolute.left<H[0])){K.position.current.left=H[0]-K.offsets.parent.left-K.margins.left}if((K.position.absolute.top<H[1])){K.position.current.top=H[1]-K.offsets.parent.top-K.margins.top}if(K.position.absolute.left-H[2]+K.helperProportions.width>=0){K.position.current.left=H[2]-K.offsets.parent.left-K.helperProportions.width-K.margins.left-F-J}if(K.position.absolute.top-H[3]+K.helperProportions.height>=0){K.position.current.top=H[3]-K.offsets.parent.top-K.helperProportions.height-K.margins.top-C-G}}else{if((I.position.left<H.left)){K.position.current.left=H.left}if((I.position.top<H.top)){K.position.current.top=H.top}if(I.position.left-K.offsetParent.innerWidth()+K.helperProportions.width+H.right+F+J>=0){K.position.current.left=K.offsetParent.innerWidth()-K.helperProportions.width-H.right-F-J}if(I.position.top-K.offsetParent.innerHeight()+K.helperProportions.height+H.bottom+C+G>=0){K.position.current.top=K.offsetParent.innerHeight()-K.helperProportions.height-H.bottom-C-G}}}});A.ui.plugin.add("sortable","axis",{sort:function(C,B){var D=B.options;if(D.constraint){D.axis=D.constraint}D.axis=="x"?B.instance.position.top=B.instance.originalPosition.top:B.instance.position.left=B.instance.originalPosition.left}});A.ui.plugin.add("sortable","scroll",{start:function(C,B){var D=B.options;D.scrollSensitivity=D.scrollSensitivity||20;D.scrollSpeed=D.scrollSpeed||20;B.instance.overflowY=function(E){do{if((/auto|scroll/).test(E.css("overflow"))||(/auto|scroll/).test(E.css("overflow-y"))){return E}E=E.parent()}while(E[0].parentNode);return A(document)}(this);B.instance.overflowX=function(E){do{if((/auto|scroll/).test(E.css("overflow"))||(/auto|scroll/).test(E.css("overflow-x"))){return E}E=E.parent()}while(E[0].parentNode);return A(document)}(this);if(B.instance.overflowY[0]!=document&&B.instance.overflowY[0].tagName!="HTML"){B.instance.overflowYstart=B.instance.overflowY[0].scrollTop}if(B.instance.overflowX[0]!=document&&B.instance.overflowX[0].tagName!="HTML"){B.instance.overflowXstart=B.instance.overflowX[0].scrollLeft}},sort:function(D,C){var E=C.options;var B=C.instance;if(B.overflowY[0]!=document&&B.overflowY[0].tagName!="HTML"){if(B.overflowY[0].offsetHeight-(C.position.top-B.overflowY[0].scrollTop+B.clickOffset.top)<E.scrollSensitivity){B.overflowY[0].scrollTop=B.overflowY[0].scrollTop+E.scrollSpeed}if((C.position.top-B.overflowY[0].scrollTop+B.clickOffset.top)<E.scrollSensitivity){B.overflowY[0].scrollTop=B.overflowY[0].scrollTop-E.scrollSpeed}}else{if(D.pageY-A(document).scrollTop()<E.scrollSensitivity){A(document).scrollTop(A(document).scrollTop()-E.scrollSpeed)}if(A(window).height()-(D.pageY-A(document).scrollTop())<E.scrollSensitivity){A(document).scrollTop(A(document).scrollTop()+E.scrollSpeed)}}if(B.overflowX[0]!=document&&B.overflowX[0].tagName!="HTML"){if(B.overflowX[0].offsetWidth-(C.position.left-B.overflowX[0].scrollLeft+B.clickOffset.left)<E.scrollSensitivity){B.overflowX[0].scrollLeft=B.overflowX[0].scrollLeft+E.scrollSpeed}if((C.position.top-B.overflowX[0].scrollLeft+B.clickOffset.left)<E.scrollSensitivity){B.overflowX[0].scrollLeft=B.overflowX[0].scrollLeft-E.scrollSpeed}}else{if(D.pageX-A(document).scrollLeft()<E.scrollSensitivity){A(document).scrollLeft(A(document).scrollLeft()-E.scrollSpeed)}if(A(window).width()-(D.pageX-A(document).scrollLeft())<E.scrollSensitivity){A(document).scrollLeft(A(document).scrollLeft()+E.scrollSpeed)}}B.offset={left:B.mouse.start.left-B.originalPosition.left+(B.overflowXstart!==undefined?B.overflowXstart-B.overflowX[0].scrollLeft:0),top:B.mouse.start.top-B.originalPosition.top+(B.overflowYstart!==undefined?B.overflowYstart-B.overflowX[0].scrollTop:0)}}})})(jQuery);(function(E){E.fn.extend({accordion:function(G,H){return this.each(function(){var I=E.data(this,"accordion");if(!I){E.data(this,"accordion",new E.ui.accordion(this,G))}else{if(typeof G=="string"){I[G](H)}}})}});E.ui.accordion=function(G,H){this.options=H=E.extend({},E.ui.accordion.defaults,H);this.element=E(G);if(H.navigation){var K=this.element.find("a").filter(H.navigationFilter);if(K.length){if(K.filter(H.header).length){H.active=K}else{H.active=K.parent().parent().prev();K.addClass("current")}}}H.headers=this.element.find(H.header);H.active=C(H.headers,H.active);if(!this.element.hasClass("ui-accordion")){this.element.addClass("ui-accordion");E("<span class='ui-accordion-left'/>").insertBefore(H.headers);E("<span class='ui-accordion-right'/>").appendTo(H.headers);H.headers.addClass("ui-accordion-header").attr("tabindex","0")}if(H.fillSpace){var J=this.element.parent().height();H.headers.each(function(){J-=E(this).outerHeight()});var I=0;H.headers.next().each(function(){I=Math.max(I,E(this).innerHeight()-E(this).height())}).height(J-I)}else{if(H.autoHeight){var J=0;H.headers.next().each(function(){J=Math.max(J,E(this).outerHeight())}).height(J)}}H.headers.not(H.active||"").next().hide();H.active.parent().andSelf().addClass(H.selectedClass);if(H.event){this.element.bind((H.event)+".accordion",F)}};E.ui.accordion.prototype={activate:function(G){F.call(this.element[0],{target:C(this.options.headers,G)[0]})},enable:function(){this.options.disabled=false},disable:function(){this.options.disabled=true},destroy:function(){this.options.headers.next().css("display","");if(this.options.fillSpace||this.options.autoHeight){this.options.headers.next().css("height","")}E.removeData(this.element[0],"accordion");this.element.removeClass("ui-accordion").unbind(".accordion")}};function B(H,G){return function(){return H.apply(G,arguments)}}function D(I){if(!E.data(this,"accordion")){return }var G=E.data(this,"accordion");var H=G.options;H.running=I?0:--H.running;if(H.running){return }if(H.clearStyle){H.toShow.add(H.toHide).css({height:"",overflow:""})}E(this).triggerHandler("accordionchange",[H.data],H.change)}function A(G,K,L,J,M){var I=E.data(this,"accordion").options;I.toShow=G;I.toHide=K;I.data=L;var H=B(D,this);I.running=K.size()==0?G.size():K.size();if(I.animated){if(!I.alwaysOpen&&J){E.ui.accordion.animations[I.animated]({toShow:jQuery([]),toHide:K,complete:H,down:M,autoHeight:I.autoHeight})}else{E.ui.accordion.animations[I.animated]({toShow:G,toHide:K,complete:H,down:M,autoHeight:I.autoHeight})}}else{if(!I.alwaysOpen&&J){G.toggle()}else{K.hide();G.show()}H(true)}}function F(L){var J=E.data(this,"accordion").options;if(J.disabled){return false}if(!L.target&&!J.alwaysOpen){J.active.parent().andSelf().toggleClass(J.selectedClass);var I=J.active.next(),M={instance:this,options:J,newHeader:jQuery([]),oldHeader:J.active,newContent:jQuery([]),oldContent:I},G=J.active=E([]);A.call(this,G,I,M);return false}var K=E(L.target);if(K.parents(J.header).length){while(!K.is(J.header)){K=K.parent()}}var H=K[0]==J.active[0];if(J.running||(J.alwaysOpen&&H)){return false}if(!K.is(J.header)){return }J.active.parent().andSelf().toggleClass(J.selectedClass);if(!H){K.parent().andSelf().addClass(J.selectedClass)}var G=K.next(),I=J.active.next(),M={instance:this,options:J,newHeader:K,oldHeader:J.active,newContent:G,oldContent:I},N=J.headers.index(J.active[0])>J.headers.index(K[0]);J.active=H?E([]):K;A.call(this,G,I,M,H,N);return false}function C(H,G){return G!=undefined?typeof G=="number"?H.filter(":eq("+G+")"):H.not(H.not(G)):G===false?E([]):H.filter(":eq(0)")}E.extend(E.ui.accordion,{defaults:{selectedClass:"selected",alwaysOpen:true,animated:"slide",event:"click",header:"a",autoHeight:true,running:0,navigationFilter:function(){return this.href.toLowerCase()==location.href.toLowerCase()}},animations:{slide:function(G,I){G=E.extend({easing:"swing",duration:300},G,I);if(!G.toHide.size()){G.toShow.animate({height:"show"},G);return }var H=G.toHide.height(),J=G.toShow.height(),K=J/H;G.toShow.css({height:0,overflow:"hidden"}).show();G.toHide.filter(":hidden").each(G.complete).end().filter(":visible").animate({height:"hide"},{step:function(L){var M=(H-L)*K;if(E.browser.msie||E.browser.opera){M=Math.ceil(M)}G.toShow.height(M)},duration:G.duration,easing:G.easing,complete:function(){if(!G.autoHeight){G.toShow.css("height","auto")}G.complete()}})},bounceslide:function(G){this.slide(G,{easing:G.down?"bounceout":"swing",duration:G.down?1000:200})},easeslide:function(G){this.slide(G,{easing:"easeinout",duration:700})}}});E.fn.activate=function(G){return this.accordion("activate",G)}})(jQuery);(function(A){A.fn.extend({dialog:function(C){var B=Array.prototype.slice.call(arguments,1);return this.each(function(){if(typeof C=="string"){var E=A(this).is(".ui-dialog")?this:A(this).parents(".ui-dialog:first").find(".ui-dialog-content")[0];var D=E?A.data(E,"dialog"):{};if(D[C]){D[C].apply(D,B)}}else{if(!A(this).is(".ui-dialog-content")){new A.ui.dialog(this,C)}}})}});A.ui.dialog=function(D,L){this.options=L=A.extend({},A.ui.dialog.defaults,L);this.element=D;var K=this;A.data(this.element,"dialog",this);A(D).bind("remove",function(){K.destroy()});A(D).bind("setData.dialog",function(N,M,O){switch(M){case"draggable":J.draggable(O?"enable":"disable");break;case"dragStart":J.data("start.draggable",O);break;case"drag":J.data("drag.draggable",O);break;case"dragStop":J.data("stop.draggable",O);break;case"height":J.height(O);break;case"maxHeight":case"minHeight":case"maxWidth":case"minWidth":J.data(M+".resizable",O);break;case"position":K.position(O);break;case"resizable":J.resizable(O?"enable":"disable");break;case"resizeStart":J.data("start.resizable",O);break;case"resize":J.data("resize.resizable",O);break;case"resizeStop":J.data("stop.resizable",O);break;case"title":A(".ui-dialog-title",C).text(O);break;case"width":break}L[M]=O}).bind("getData.dialog",function(N,M){return L[M]});var E=A(D).addClass("ui-dialog-content");if(!E.parent().length){E.appendTo("body")}E.wrap(document.createElement("div")).wrap(document.createElement("div"));var H=E.parent().addClass("ui-dialog-container").css({position:"relative"});var J=this.uiDialog=H.parent().hide().addClass("ui-dialog").css({position:"absolute",width:L.width,height:L.height,overflow:"hidden"});var B=E.attr("className").split(" ");A.each(B,function(M,N){if(N!="ui-dialog-content"){J.addClass(N)}});if(A.fn.resizable){J.append('<div class="ui-resizable-n ui-resizable-handle"></div>').append('<div class="ui-resizable-s ui-resizable-handle"></div>').append('<div class="ui-resizable-e ui-resizable-handle"></div>').append('<div class="ui-resizable-w ui-resizable-handle"></div>').append('<div class="ui-resizable-ne ui-resizable-handle"></div>').append('<div class="ui-resizable-se ui-resizable-handle"></div>').append('<div class="ui-resizable-sw ui-resizable-handle"></div>').append('<div class="ui-resizable-nw ui-resizable-handle"></div>');J.resizable({maxWidth:L.maxWidth,maxHeight:L.maxHeight,minWidth:L.minWidth,minHeight:L.minHeight,start:L.resizeStart,resize:L.resize,stop:function(N,M){L.resizeStop&&L.resizeStop.apply(this,arguments);A.ui.dialog.overlay.resize()}});if(!L.resizable){J.resizable("disable")}}H.prepend('<div class="ui-dialog-titlebar"></div>');var C=A(".ui-dialog-titlebar",H);var I=(L.title)?L.title:(E.attr("title"))?E.attr("title"):"";C.append('<span class="ui-dialog-title">'+I+"</span>");C.append('<a href="#" class="ui-dialog-titlebar-close"><span>X</span></a>');this.uiDialogTitlebarClose=A(".ui-dialog-titlebar-close",C).hover(function(){A(this).addClass("ui-dialog-titlebar-close-hover")},function(){A(this).removeClass("ui-dialog-titlebar-close-hover")}).mousedown(function(M){M.stopPropagation()}).click(function(){K.close();return false}).keydown(function(M){var N=27;M.keyCode&&M.keyCode==N&&K.close()});var F=0;A.each(L.buttons,function(){F=1;return false});if(F==1){J.append('<div class="ui-dialog-buttonpane"></div>');var G=A(".ui-dialog-buttonpane",J);A.each(L.buttons,function(M,O){var N=A(document.createElement("button")).text(M).click(O);G.append(N)})}if(A.fn.draggable){J.draggable({handle:".ui-dialog-titlebar",start:function(N,M){K.activate();L.dragStart&&L.dragStart.apply(this,arguments)},drag:L.drag,stop:function(N,M){L.dragStop&&L.dragStop.apply(this,arguments);A.ui.dialog.overlay.resize()}});if(!L.draggable){J.draggable("disable")}}J.mousedown(function(){K.activate()});C.click(function(){K.activate()});L.bgiframe&&A.fn.bgiframe&&J.bgiframe();this.position=function(Q){var M=A(window),P=A(document),O=P.scrollTop(),N=P.scrollLeft();if(Q.constructor==Array){O+=Q[1];N+=Q[0]}else{switch(Q){case"center":O+=(M.height()/2)-(J.height()/2);N+=(M.width()/2)-(J.width()/2);break;case"top":O+=0;N+=(M.width()/2)-(J.width()/2);break;case"right":O+=(M.height()/2)-(J.height()/2);N+=(M.width())-(J.width());break;case"bottom":O+=(M.height())-(J.height());N+=(M.width()/2)-(J.width()/2);break;case"left":O+=(M.height()/2)-(J.height()/2);N+=0;break;default:O+=(M.height()/2)-(J.height()/2);N+=(M.width()/2)-(J.width()/2)}}O=O<P.scrollTop()?P.scrollTop():O;J.css({top:O,left:N})};this.open=function(){this.overlay=L.modal?new A.ui.dialog.overlay(K):null;J.appendTo("body");this.position(L.position);J.show();K.moveToTop();K.activate();var M=null;var N={options:L};this.uiDialogTitlebarClose.focus();A(this.element).triggerHandler("dialogopen",[M,N],L.open)};this.activate=function(){!L.modal&&this.moveToTop()};this.moveToTop=function(){var M=L.zIndex;A(".ui-dialog:visible").each(function(){M=Math.max(M,parseInt(A(this).css("z-index"),10)||L.zIndex)});this.overlay&&this.overlay.$el.css("z-index",++M);J.css("z-index",++M)};this.close=function(){this.overlay&&this.overlay.destroy();J.hide();var N=null;var M={options:L};A(this.element).triggerHandler("dialogclose",[N,M],L.close);A.ui.dialog.overlay.resize()};this.destroy=function(){this.overlay&&this.overlay.destroy();J.hide();A(D).unbind(".dialog").removeClass("ui-dialog-content").hide().appendTo("body");J.remove();A.removeData(this.element,"dialog")};if(L.autoOpen){this.open()}};A.extend(A.ui.dialog,{defaults:{autoOpen:true,bgiframe:false,buttons:[],draggable:true,height:200,minHeight:100,minWidth:150,modal:false,overlay:{},position:"center",resizable:true,width:300,zIndex:1000},overlay:function(B){this.$el=A.ui.dialog.overlay.create(B)}});A.extend(A.ui.dialog.overlay,{instances:[],events:A.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(B){return B+".dialog-overlay"}).join(" "),create:function(C){if(this.instances.length===0){A("a, :input").bind(this.events,function(){var E=false;var G=A(this).parents(".ui-dialog");if(G.length){var D=A(".ui-dialog-overlay");if(D.length){var F=parseInt(D.css("z-index"),10);D.each(function(){F=Math.max(F,parseInt(A(this).css("z-index"),10))});E=parseInt(G.css("z-index"),10)>F}else{E=true}}return E});A(document).bind("keydown.dialog-overlay",function(D){var E=27;D.keyCode&&D.keyCode==E&&C.close()});A(window).bind("resize.dialog-overlay",A.ui.dialog.overlay.resize)}var B=A("<div/>").appendTo(document.body).addClass("ui-dialog-overlay").css(A.extend({borderWidth:0,margin:0,padding:0,position:"absolute",top:0,left:0,width:this.width(),height:this.height()},C.options.overlay));C.options.bgiframe&&A.fn.bgiframe&&B.bgiframe();this.instances.push(B);return B},destroy:function(B){this.instances.splice(A.inArray(this.instances,B),1);if(this.instances.length===0){A("a, :input").add([document,window]).unbind(".dialog-overlay")}B.remove()},height:function(){if(A.browser.msie&&A.browser.version<7){var C=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);var B=Math.max(document.documentElement.offsetHeight,document.body.offsetHeight);if(C<B){return A(window).height()+"px"}else{return C+"px"}}else{return A(document).height()+"px"}},width:function(){if(A.browser.msie&&A.browser.version<7){var B=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth);var C=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth);if(B<C){return A(window).width()+"px"}else{return B+"px"}}else{return A(document).width()+"px"}},resize:function(){var B=A([]);A.each(A.ui.dialog.overlay.instances,function(){B=B.add(this)});B.css({width:0,height:0}).css({width:A.ui.dialog.overlay.width(),height:A.ui.dialog.overlay.height()})}});A.extend(A.ui.dialog.overlay.prototype,{destroy:function(){A.ui.dialog.overlay.destroy(this.$el)}})})(jQuery);(function(A){A.fn.extend({slider:function(C){var B=Array.prototype.slice.call(arguments,1);if(C=="value"){return A.data(this[0],"slider").value(arguments[1])}return this.each(function(){if(typeof C=="string"){var D=A.data(this,"slider");if(D){D[C].apply(D,B)}}else{if(!A.data(this,"slider")){new A.ui.slider(this,C)}}})}});A.ui.slider=function(D,C){var B=this;this.element=A(D);A.data(D,"slider",this);this.element.addClass("ui-slider");this.options=A.extend({},A.ui.slider.defaults,C);var E=this.options;A.extend(E,{axis:E.axis||(D.offsetWidth<D.offsetHeight?"vertical":"horizontal"),max:!isNaN(parseInt(E.max,10))?{x:parseInt(E.max,10),y:parseInt(E.max,10)}:({x:E.max&&E.max.x||100,y:E.max&&E.max.y||100}),min:!isNaN(parseInt(E.min,10))?{x:parseInt(E.min,10),y:parseInt(E.min,10)}:({x:E.min&&E.min.x||0,y:E.min&&E.min.y||0})});E.realMax={x:E.max.x-E.min.x,y:E.max.y-E.min.y};E.stepping={x:E.stepping&&E.stepping.x||parseInt(E.stepping,10)||(E.steps&&E.steps.x?E.realMax.x/E.steps.x:0),y:E.stepping&&E.stepping.y||parseInt(E.stepping,10)||(E.steps&&E.steps.y?E.realMax.y/E.steps.y:0)};A(D).bind("setData.slider",function(G,F,H){B.options[F]=H}).bind("getData.slider",function(G,F){return B.options[F]});this.handle=A(E.handle,D);if(!this.handle.length){B.handle=B.generated=A(E.handles||[0]).map(function(){var F=A("<div/>").addClass("ui-slider-handle").appendTo(D);if(this.id){F.attr("id",this.id)}return F[0]})}A(this.handle).mouseInteraction({executor:this,delay:E.delay,distance:E.distance!=undefined?E.distance:1,dragPrevention:E.prevention?E.prevention.toLowerCase().split(","):["input","textarea","button","select","option"],start:this.start,stop:this.stop,drag:this.drag,condition:function(G,F){if(!this.disabled){if(this.currentHandle){this.blur(this.currentHandle)}this.focus(F,1);return !this.disabled}}}).wrap('<a href="javascript:void(0)" style="cursor:default;"></a>').parent().bind("focus",function(F){B.focus(this.firstChild)}).bind("blur",function(F){B.blur(this.firstChild)}).bind("keydown",function(F){if(/(37|38|39|40)/.test(F.keyCode)){B.moveTo({x:/(37|39)/.test(F.keyCode)?(F.keyCode==37?"-":"+")+"="+B.oneStep(1):null,y:/(38|40)/.test(F.keyCode)?(F.keyCode==38?"-":"+")+"="+B.oneStep(2):null},this.firstChild)}});this.actualSize={width:this.element.outerWidth(),height:this.element.outerHeight()};this.element.bind("mousedown.slider",function(F){B.click.apply(B,[F]);B.currentHandle.data("ui-mouse").trigger(F);B.firstValue=B.firstValue+1});A.each(E.handles||[],function(F,G){B.moveTo(G.start,F,true)});if(!isNaN(E.startValue)){this.moveTo(E.startValue,0,true)}if(this.handle.length==1){this.previousHandle=this.handle}if(this.handle.length==2&&E.range){this.createRange()}};A.extend(A.ui.slider.prototype,{plugins:{},createRange:function(){this.rangeElement=A("<div></div>").addClass("ui-slider-range").css({position:"absolute"}).appendTo(this.element);this.updateRange()},updateRange:function(){var C=this.options.axis=="vertical"?"top":"left";var B=this.options.axis=="vertical"?"height":"width";this.rangeElement.css(C,parseInt(A(this.handle[0]).css(C),10)+this.handleSize(0,this.options.axis=="vertical"?2:1)/2);this.rangeElement.css(B,parseInt(A(this.handle[1]).css(C),10)-parseInt(A(this.handle[0]).css(C),10))},getRange:function(){return this.rangeElement?this.convertValue(parseInt(this.rangeElement.css(this.options.axis=="vertical"?"height":"width"),10)):null},ui:function(B){return{instance:this,options:this.options,handle:this.currentHandle,value:this.options.axis!="both"||!this.options.axis?Math.round(this.value(null,this.options.axis=="vertical"?2:1)):{x:Math.round(this.value(null,1)),y:Math.round(this.value(null,2))},range:this.getRange()}},propagate:function(C,B){A.ui.plugin.call(this,C,[B,this.ui()]);this.element.triggerHandler(C=="slide"?C:"slide"+C,[B,this.ui()],this.options[C])},destroy:function(){this.element.removeClass("ui-slider ui-slider-disabled").removeData("slider").unbind(".slider");this.handle.removeMouseInteraction();this.generated&&this.generated.remove()},enable:function(){this.element.removeClass("ui-slider-disabled");this.disabled=false},disable:function(){this.element.addClass("ui-slider-disabled");this.disabled=true},focus:function(B,C){this.currentHandle=A(B).addClass("ui-slider-handle-active");if(C){this.currentHandle.parent()[0].focus()}},blur:function(B){A(B).removeClass("ui-slider-handle-active");if(this.currentHandle&&this.currentHandle[0]==B){this.previousHandle=this.currentHandle;this.currentHandle=null}},value:function(D,B){if(this.handle.length==1){this.currentHandle=this.handle}if(!B){B=this.options.axis=="vertical"?2:1}var C=((parseInt(A(D!=undefined&&D!==null?this.handle[D]||D:this.currentHandle).css(B==1?"left":"top"),10)/(this.actualSize[B==1?"width":"height"]-this.handleSize(null,B)))*this.options.realMax[B==1?"x":"y"])+this.options.min[B==1?"x":"y"];var E=this.options;if(E.stepping[B==1?"x":"y"]){C=Math.round(C/E.stepping[B==1?"x":"y"])*E.stepping[B==1?"x":"y"]}return C},convertValue:function(C,B){if(!B){B=this.options.axis=="vertical"?2:1}return this.options.min[B==1?"x":"y"]+(C/(this.actualSize[B==1?"width":"height"]-this.handleSize(null,B)))*this.options.realMax[B==1?"x":"y"]},translateValue:function(C,B){if(!B){B=this.options.axis=="vertical"?2:1}return((C-this.options.min[B==1?"x":"y"])/this.options.realMax[B==1?"x":"y"])*(this.actualSize[B==1?"width":"height"]-this.handleSize(null,B))},handleSize:function(C,B){if(!B){B=this.options.axis=="vertical"?2:1}return A(C!=undefined&&C!==null?this.handle[C]:this.currentHandle)[B==1?"outerWidth":"outerHeight"]()},click:function(C){var D=[C.pageX,C.pageY];var B=false;this.handle.each(function(){if(this==C.target){B=true}});if(B||this.disabled||!(this.currentHandle||this.previousHandle)){return }if(this.previousHandle){this.focus(this.previousHandle,1)}this.offset=this.element.offset();this.moveTo({y:this.convertValue(C.pageY-this.offset.top-this.currentHandle.outerHeight()/2),x:this.convertValue(C.pageX-this.offset.left-this.currentHandle.outerWidth()/2)},null,true)},start:function(C,B){var D=this.options;if(!this.currentHandle){this.focus(this.previousHandle,true)}this.offset=this.element.offset();this.handleOffset=this.currentHandle.offset();this.clickOffset={top:C.pageY-this.handleOffset.top,left:C.pageX-this.handleOffset.left};this.firstValue=this.value();this.propagate("start",C);return false},stop:function(B){this.propagate("stop",B);if(this.firstValue!=this.value()){this.propagate("change",B)}this.focus(this.currentHandle,true);return false},oneStep:function(B){if(!B){B=this.options.axis=="vertical"?2:1}return this.options.stepping[B==1?"x":"y"]?this.options.stepping[B==1?"x":"y"]:(this.options.realMax[B==1?"x":"y"]/this.actualSize[B==1?"width":"height"])*5},translateRange:function(D,B){if(this.rangeElement){if(this.currentHandle[0]==this.handle[0]&&D>=this.translateValue(this.value(1),B)){D=this.translateValue(this.value(1,B)-this.oneStep(B),B)}if(this.currentHandle[0]==this.handle[1]&&D<=this.translateValue(this.value(0),B)){D=this.translateValue(this.value(0,B)+this.oneStep(B))}}if(this.options.handles){var C=this.options.handles[this.handleIndex()];if(D<this.translateValue(C.min,B)){D=this.translateValue(C.min,B)}else{if(D>this.translateValue(C.max,B)){D=this.translateValue(C.max,B)}}}return D},handleIndex:function(){return this.handle.index(this.currentHandle[0])},translateLimits:function(C,B){if(!B){B=this.options.axis=="vertical"?2:1}if(C>=this.actualSize[B==1?"width":"height"]-this.handleSize(null,B)){C=this.actualSize[B==1?"width":"height"]-this.handleSize(null,B)}if(C<=0){C=0}return C},drag:function(E,D){var F=this.options;var B={top:E.pageY-this.offset.top-this.clickOffset.top,left:E.pageX-this.offset.left-this.clickOffset.left};if(!this.currentHandle){this.focus(this.previousHandle,true)}B.left=this.translateLimits(B.left,1);B.top=this.translateLimits(B.top,2);if(F.stepping.x){var C=this.convertValue(B.left,1);C=Math.round(C/F.stepping.x)*F.stepping.x;B.left=this.translateValue(C,1)}if(F.stepping.y){var C=this.convertValue(B.top,2);C=Math.round(C/F.stepping.y)*F.stepping.y;B.top=this.translateValue(C,2)}B.left=this.translateRange(B.left,1);B.top=this.translateRange(B.top,2);if(F.axis!="vertical"){this.currentHandle.css({left:B.left})}if(F.axis!="horizontal"){this.currentHandle.css({top:B.top})}if(this.rangeElement){this.updateRange()}this.propagate("slide",E);return false},moveTo:function(F,E,G){var H=this.options;if(E==undefined&&!this.currentHandle&&this.handle.length!=1){return false}if(E==undefined&&!this.currentHandle){E=0}if(E!=undefined){this.currentHandle=this.previousHandle=A(this.handle[E]||E)}if(F.x!==undefined&&F.y!==undefined){var B=F.x;var I=F.y}else{var B=F,I=F}if(B&&B.constructor!=Number){var D=/^\-\=/.test(B),C=/^\+\=/.test(B);if(D){B=this.value(null,1)-parseInt(B.replace("-=",""),10)}else{if(C){B=this.value(null,1)+parseInt(B.replace("+=",""),10)}}}if(I&&I.constructor!=Number){var D=/^\-\=/.test(I),C=/^\+\=/.test(I);if(D){I=this.value(null,2)-parseInt(I.replace("-=",""),10)}else{if(C){I=this.value(null,2)+parseInt(I.replace("+=",""),10)}}}if(H.axis!="vertical"&&B){if(H.stepping.x){B=Math.round(B/H.stepping.x)*H.stepping.x}B=this.translateValue(B,1);B=this.translateLimits(B,1);B=this.translateRange(B,1);this.currentHandle.css({left:B})}if(H.axis!="horizontal"&&I){if(H.stepping.y){I=Math.round(I/H.stepping.y)*H.stepping.y}I=this.translateValue(I,2);I=this.translateLimits(I,2);I=this.translateRange(I,2);this.currentHandle.css({top:I})}if(this.rangeElement){this.updateRange()}if(!G){this.propagate("start",null);this.propagate("stop",null);this.propagate("change",null);this.propagate("slide",null)}}});A.ui.slider.defaults={handle:".ui-slider-handle"}})(jQuery);(function(A){A.fn.tabs=function(){var C=typeof arguments[0]=="string"&&arguments[0];var B=C&&Array.prototype.slice.call(arguments,1)||arguments;return C=="length"?A.data(this[0],"tabs").$tabs.length:this.each(function(){if(C){var D=A.data(this,"tabs");if(D){D[C].apply(D,B)}}else{new A.ui.tabs(this,B[0]||{})}})};A.ui.tabs=function(D,C){var B=this;this.options=A.extend({},A.ui.tabs.defaults,C);this.element=D;if(C.selected===null){this.options.selected=null}this.options.event+=".tabs";A(D).bind("setData.tabs",function(F,E,G){if((/^selected/).test(E)){B.select(G)}else{B.options[E]=G;B.tabify()}}).bind("getData.tabs",function(F,E){return B.options[E]});A.data(D,"tabs",this);this.tabify(true)};A.ui.tabs.defaults={selected:0,unselect:false,event:"click",disabled:[],cookie:null,spinner:"Loading&#8230;",cache:false,idPrefix:"ui-tabs-",ajaxOptions:{},fx:null,tabTemplate:'<li><a href="#{href}"><span>#{label}</span></a></li>',panelTemplate:"<div></div>",navClass:"ui-tabs-nav",selectedClass:"ui-tabs-selected",unselectClass:"ui-tabs-unselect",disabledClass:"ui-tabs-disabled",panelClass:"ui-tabs-panel",hideClass:"ui-tabs-hide",loadingClass:"ui-tabs-loading"};A.extend(A.ui.tabs.prototype,{tabId:function(B){return B.title&&B.title.replace(/\s/g,"_").replace(/[^A-Za-z0-9\-_:\.]/g,"")||this.options.idPrefix+A.data(B)},ui:function(C,B){return{instance:this,options:this.options,tab:C,panel:B}},tabify:function(N){this.$lis=A("li:has(a[href])",this.element);this.$tabs=this.$lis.map(function(){return A("a",this)[0]});this.$panels=A([]);var O=this,E=this.options;this.$tabs.each(function(Q,P){if(P.hash&&P.hash.replace("#","")){O.$panels=O.$panels.add(P.hash)}else{if(A(P).attr("href")!="#"){A.data(P,"href.tabs",P.href);A.data(P,"load.tabs",P.href);var S=O.tabId(P);P.href="#"+S;var R=A("#"+S);if(!R.length){R=A(E.panelTemplate).attr("id",S).addClass(E.panelClass).insertAfter(O.$panels[Q-1]||O.element);R.data("destroy.tabs",true)}O.$panels=O.$panels.add(R)}else{E.disabled.push(Q+1)}}});if(N){A(this.element).hasClass(E.navClass)||A(this.element).addClass(E.navClass);this.$panels.each(function(){var P=A(this);P.hasClass(E.panelClass)||P.addClass(E.panelClass)});this.$tabs.each(function(S,P){if(location.hash){if(P.hash==location.hash){E.selected=S;if(A.browser.msie||A.browser.opera){var R=A(location.hash),T=R.attr("id");R.attr("id","");setTimeout(function(){R.attr("id",T)},500)}scrollTo(0,0);return false}}else{if(E.cookie){var Q=parseInt(A.cookie("ui-tabs"+A.data(O.element)),10);if(Q&&O.$tabs[Q]){E.selected=Q;return false}}else{if(O.$lis.eq(S).hasClass(E.selectedClass)){E.selected=S;return false}}}});this.$panels.addClass(E.hideClass);this.$lis.removeClass(E.selectedClass);if(E.selected!==null){this.$panels.eq(E.selected).show().removeClass(E.hideClass);this.$lis.eq(E.selected).addClass(E.selectedClass)}var D=E.selected!==null&&A.data(this.$tabs[E.selected],"load.tabs");if(D){this.load(E.selected)}E.disabled=A.unique(E.disabled.concat(A.map(this.$lis.filter("."+E.disabledClass),function(Q,P){return O.$lis.index(Q)}))).sort();A(window).bind("unload",function(){O.$tabs.unbind(".tabs");O.$lis=O.$tabs=O.$panels=null})}for(var H=0,M;M=this.$lis[H];H++){A(M)[A.inArray(H,E.disabled)!=-1&&!A(M).hasClass(E.selectedClass)?"addClass":"removeClass"](E.disabledClass)}if(E.cache===false){this.$tabs.removeData("cache.tabs")}var C,J,B={"min-width":0,duration:1},F="normal";if(E.fx&&E.fx.constructor==Array){C=E.fx[0]||B,J=E.fx[1]||B}else{C=J=E.fx||B}var I={display:"",overflow:"",height:""};if(!A.browser.msie){I.opacity=""}function L(Q,P,R){P.animate(C,C.duration||F,function(){P.addClass(E.hideClass).css(I);if(A.browser.msie&&C.opacity){P[0].style.filter=""}if(R){K(Q,R,P)}})}function K(Q,R,P){if(J===B){R.css("display","block")}R.animate(J,J.duration||F,function(){R.removeClass(E.hideClass).css(I);if(A.browser.msie&&J.opacity){R[0].style.filter=""}A(O.element).triggerHandler("tabsshow",[O.ui(Q,R[0])],E.show)})}function G(Q,S,P,R){S.addClass(E.selectedClass).siblings().removeClass(E.selectedClass);L(Q,P,R)}this.$tabs.unbind(".tabs").bind(E.event,function(){var S=A(this).parents("li:eq(0)"),P=O.$panels.filter(":visible"),R=A(this.hash);if((S.hasClass(E.selectedClass)&&!E.unselect)||S.hasClass(E.disabledClass)||A(this).hasClass(E.loadingClass)||A(O.element).triggerHandler("tabsselect",[O.ui(this,R[0])],E.select)===false){this.blur();return false}O.options.selected=O.$tabs.index(this);if(E.unselect){if(S.hasClass(E.selectedClass)){O.options.selected=null;S.removeClass(E.selectedClass);O.$panels.stop();L(this,P);this.blur();return false}else{if(!P.length){O.$panels.stop();var Q=this;O.load(O.$tabs.index(this),function(){S.addClass(E.selectedClass).addClass(E.unselectClass);K(Q,R)});this.blur();return false}}}if(E.cookie){A.cookie("ui-tabs"+A.data(O.element),O.options.selected,E.cookie)}O.$panels.stop();if(R.length){var Q=this;O.load(O.$tabs.index(this),P.length?function(){G(Q,S,P,R)}:function(){S.addClass(E.selectedClass);K(Q,R)})}else{throw"jQuery UI Tabs: Mismatching fragment identifier."}if(A.browser.msie){this.blur()}return false});if(!(/^click/).test(E.event)){this.$tabs.bind("click.tabs",function(){return false})}},add:function(E,D,C){if(C==undefined){C=this.$tabs.length}var G=this.options;var I=A(G.tabTemplate.replace(/#\{href\}/,E).replace(/#\{label\}/,D));I.data("destroy.tabs",true);var H=E.indexOf("#")==0?E.replace("#",""):this.tabId(A("a:first-child",I)[0]);var F=A("#"+H);if(!F.length){F=A(G.panelTemplate).attr("id",H).addClass(G.panelClass).addClass(G.hideClass);F.data("destroy.tabs",true)}if(C>=this.$lis.length){I.appendTo(this.element);F.appendTo(this.element.parentNode)}else{I.insertBefore(this.$lis[C]);F.insertBefore(this.$panels[C])}G.disabled=A.map(G.disabled,function(K,J){return K>=C?++K:K});this.tabify();if(this.$tabs.length==1){I.addClass(G.selectedClass);F.removeClass(G.hideClass);var B=A.data(this.$tabs[0],"load.tabs");if(B){this.load(C,B)}}A(this.element).triggerHandler("tabsadd",[this.ui(this.$tabs[C],this.$panels[C])],G.add)},remove:function(B){var D=this.options,E=this.$lis.eq(B).remove(),C=this.$panels.eq(B).remove();if(E.hasClass(D.selectedClass)&&this.$tabs.length>1){this.select(B+(B+1<this.$tabs.length?1:-1))}D.disabled=A.map(A.grep(D.disabled,function(G,F){return G!=B}),function(G,F){return G>=B?--G:G});this.tabify();A(this.element).triggerHandler("tabsremove",[this.ui(E.find("a")[0],C[0])],D.remove)},enable:function(B){var C=this.options;if(A.inArray(B,C.disabled)==-1){return }var D=this.$lis.eq(B).removeClass(C.disabledClass);if(A.browser.safari){D.css("display","inline-block");setTimeout(function(){D.css("display","block")},0)}C.disabled=A.grep(C.disabled,function(F,E){return F!=B});A(this.element).triggerHandler("tabsenable",[this.ui(this.$tabs[B],this.$panels[B])],C.enable)},disable:function(C){var B=this,D=this.options;if(C!=D.selected){this.$lis.eq(C).addClass(D.disabledClass);D.disabled.push(C);D.disabled.sort();A(this.element).triggerHandler("tabsdisable",[this.ui(this.$tabs[C],this.$panels[C])],D.disable)}},select:function(B){if(typeof B=="string"){B=this.$tabs.index(this.$tabs.filter("[href$="+B+"]")[0])}this.$tabs.eq(B).trigger(this.options.event)},load:function(F,K){var L=this,C=this.options,D=this.$tabs.eq(F),J=D[0],G=K==undefined||K===false,B=D.data("load.tabs");K=K||function(){};if(!B||(A.data(J,"cache.tabs")&&!G)){K();return }if(C.spinner){var H=A("span",J);H.data("label.tabs",H.html()).html("<em>"+C.spinner+"</em>")}var I=function(){L.$tabs.filter("."+C.loadingClass).each(function(){A(this).removeClass(C.loadingClass);if(C.spinner){var M=A("span",this);M.html(M.data("label.tabs")).removeData("label.tabs")}});L.xhr=null};var E=A.extend({},C.ajaxOptions,{url:B,success:function(N,M){A(J.hash).html(N);I();K();if(C.cache){A.data(J,"cache.tabs",true)}A(L.element).triggerHandler("tabsload",[L.ui(L.$tabs[F],L.$panels[F])],C.load);C.ajaxOptions.success&&C.ajaxOptions.success(N,M)}});if(this.xhr){this.xhr.abort();I()}D.addClass(C.loadingClass);setTimeout(function(){L.xhr=A.ajax(E)},0)},url:function(C,B){this.$tabs.eq(C).removeData("cache.tabs").data("load.tabs",B)},destroy:function(){var B=this.options;A(this.element).unbind(".tabs").removeClass(B.navClass).removeData("tabs");this.$tabs.each(function(){var C=A.data(this,"href.tabs");if(C){this.href=C}var D=A(this).unbind(".tabs");A.each(["href","load","cache"],function(E,F){D.removeData(F+".tabs")})});this.$lis.add(this.$panels).each(function(){if(A.data(this,"destroy.tabs")){A(this).remove()}else{A(this).removeClass([B.selectedClass,B.unselectClass,B.disabledClass,B.panelClass,B.hideClass].join(" "))}})}});A.extend(A.ui.tabs.prototype,{rotation:null,rotate:function(C,F){F=F||false;var B=this,E=this.options.selected;function G(){B.rotation=setInterval(function(){E=++E<B.$tabs.length?E:0;B.select(E)},C)}function D(H){if(!H||H.clientX){clearInterval(B.rotation)}}if(C){G();if(!F){this.$tabs.bind(this.options.event,D)}else{this.$tabs.bind(this.options.event,function(){D();E=B.options.selected;G()})}}else{D();this.$tabs.unbind(this.options.event,D)}}})})(jQuery);(function($){function Datepicker(){this.debug=false;this._nextId=0;this._inst=[];this._curInst=null;this._disabledInputs=[];this._datepickerShowing=false;this._inDialog=false;this.regional=[];this.regional[""]={clearText:"Clear",clearStatus:"Erase the current date",closeText:"Close",closeStatus:"Close without change",prevText:"&#x3c;Prev",prevStatus:"Show the previous month",nextText:"Next&#x3e;",nextStatus:"Show the next month",currentText:"Today",currentStatus:"Show the current month",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],monthStatus:"Show a different month",yearStatus:"Show a different year",weekHeader:"Wk",weekStatus:"Week of the year",dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],dayStatus:"Set DD as first week day",dateStatus:"Select DD, M d",dateFormat:"mm/dd/yy",firstDay:0,initStatus:"Select a date",isRTL:false};this._defaults={showOn:"focus",showAnim:"show",defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:false,closeAtTop:true,mandatory:false,hideIfNoPrevNext:false,changeMonth:true,changeYear:true,yearRange:"-10:+10",changeFirstDay:true,showOtherMonths:false,showWeeks:false,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",showStatus:false,statusForDate:this.dateStatus,minDate:null,maxDate:null,speed:"normal",beforeShowDay:null,beforeShow:null,onSelect:null,onClose:null,numberOfMonths:1,stepMonths:1,rangeSelect:false,rangeSeparator:" - "};$.extend(this._defaults,this.regional[""]);this._datepickerDiv=$('<div id="datepicker_div">')}$.extend(Datepicker.prototype,{markerClassName:"hasDatepicker",log:function(){if(this.debug){console.log.apply("",arguments)}},_register:function(inst){var id=this._nextId++;this._inst[id]=inst;return id},_getInst:function(id){return this._inst[id]||id},setDefaults:function(settings){extendRemove(this._defaults,settings||{});return this},_attachDatepicker:function(target,settings){var inlineSettings=null;for(attrName in this._defaults){var attrValue=target.getAttribute("date:"+attrName);if(attrValue){inlineSettings=inlineSettings||{};try{inlineSettings[attrName]=eval(attrValue)}catch(err){inlineSettings[attrName]=attrValue}}}var nodeName=target.nodeName.toLowerCase();var instSettings=(inlineSettings?$.extend(settings||{},inlineSettings||{}):settings);if(nodeName=="input"){var inst=(inst&&!inlineSettings?inst:new DatepickerInstance(instSettings,false));this._connectDatepicker(target,inst)}else{if(nodeName=="div"||nodeName=="span"){var inst=new DatepickerInstance(instSettings,true);this._inlineDatepicker(target,inst)}}},_destroyDatepicker:function(target){var nodeName=target.nodeName.toLowerCase();var calId=target._calId;target._calId=null;var $target=$(target);if(nodeName=="input"){$target.siblings(".datepicker_append").replaceWith("").end().siblings(".datepicker_trigger").replaceWith("").end().removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress);var wrapper=$target.parents(".datepicker_wrap");if(wrapper){wrapper.replaceWith(wrapper.html())}}else{if(nodeName=="div"||nodeName=="span"){$target.removeClass(this.markerClassName).empty()}}if($("input[_calId="+calId+"]").length==0){this._inst[calId]=null}},_enableDatepicker:function(target){target.disabled=false;$(target).siblings("button.datepicker_trigger").each(function(){this.disabled=false}).end().siblings("img.datepicker_trigger").css({opacity:"1.0",cursor:""});this._disabledInputs=$.map(this._disabledInputs,function(value){return(value==target?null:value)})},_disableDatepicker:function(target){target.disabled=true;$(target).siblings("button.datepicker_trigger").each(function(){this.disabled=true}).end().siblings("img.datepicker_trigger").css({opacity:"0.5",cursor:"default"});this._disabledInputs=$.map($.datepicker._disabledInputs,function(value){return(value==target?null:value)});this._disabledInputs[$.datepicker._disabledInputs.length]=target},_isDisabledDatepicker:function(target){if(!target){return false}for(var i=0;i<this._disabledInputs.length;i++){if(this._disabledInputs[i]==target){return true}}return false},_changeDatepicker:function(target,name,value){var settings=name||{};if(typeof name=="string"){settings={};settings[name]=value}if(inst=this._getInst(target._calId)){extendRemove(inst._settings,settings);this._updateDatepicker(inst)}},_setDateDatepicker:function(target,date,endDate){if(inst=this._getInst(target._calId)){inst._setDate(date,endDate);this._updateDatepicker(inst)}},_getDateDatepicker:function(target){var inst=this._getInst(target._calId);return(inst?inst._getDate():null)},_doKeyDown:function(e){var inst=$.datepicker._getInst(this._calId);if($.datepicker._datepickerShowing){switch(e.keyCode){case 9:$.datepicker._hideDatepicker(null,"");break;case 13:$.datepicker._selectDay(inst,inst._selectedMonth,inst._selectedYear,$("td.datepicker_daysCellOver",inst._datepickerDiv)[0]);return false;break;case 27:$.datepicker._hideDatepicker(null,inst._get("speed"));break;case 33:$.datepicker._adjustDate(inst,(e.ctrlKey?-1:-inst._get("stepMonths")),(e.ctrlKey?"Y":"M"));break;case 34:$.datepicker._adjustDate(inst,(e.ctrlKey?+1:+inst._get("stepMonths")),(e.ctrlKey?"Y":"M"));break;case 35:if(e.ctrlKey){$.datepicker._clearDate(inst)}break;case 36:if(e.ctrlKey){$.datepicker._gotoToday(inst)}break;case 37:if(e.ctrlKey){$.datepicker._adjustDate(inst,-1,"D")}break;case 38:if(e.ctrlKey){$.datepicker._adjustDate(inst,-7,"D")}break;case 39:if(e.ctrlKey){$.datepicker._adjustDate(inst,+1,"D")}break;case 40:if(e.ctrlKey){$.datepicker._adjustDate(inst,+7,"D")}break}}else{if(e.keyCode==36&&e.ctrlKey){$.datepicker._showDatepicker(this)}}},_doKeyPress:function(e){var inst=$.datepicker._getInst(this._calId);var chars=$.datepicker._possibleChars(inst._get("dateFormat"));var chr=String.fromCharCode(e.charCode==undefined?e.keyCode:e.charCode);return e.ctrlKey||(chr<" "||!chars||chars.indexOf(chr)>-1)},_connectDatepicker:function(target,inst){var input=$(target);if(input.is("."+this.markerClassName)){return }var appendText=inst._get("appendText");var isRTL=inst._get("isRTL");if(appendText){if(isRTL){input.before('<span class="datepicker_append">'+appendText)}else{input.after('<span class="datepicker_append">'+appendText)}}var showOn=inst._get("showOn");if(showOn=="focus"||showOn=="both"){input.focus(this._showDatepicker)}if(showOn=="button"||showOn=="both"){input.wrap('<span class="datepicker_wrap">');var buttonText=inst._get("buttonText");var buttonImage=inst._get("buttonImage");var trigger=$(inst._get("buttonImageOnly")?$("<img>").addClass("datepicker_trigger").attr({src:buttonImage,alt:buttonText,title:buttonText}):$("<button>").addClass("datepicker_trigger").attr({type:"button"}).html(buttonImage!=""?$("<img>").attr({src:buttonImage,alt:buttonText,title:buttonText}):buttonText));if(isRTL){input.before(trigger)}else{input.after(trigger)}trigger.click(function(){if($.datepicker._datepickerShowing&&$.datepicker._lastInput==target){$.datepicker._hideDatepicker()}else{$.datepicker._showDatepicker(target)}})}input.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).bind("setData.datepicker",function(event,key,value){inst._settings[key]=value}).bind("getData.datepicker",function(event,key){return inst._get(key)});input[0]._calId=inst._id},_inlineDatepicker:function(target,inst){var input=$(target);if(input.is("."+this.markerClassName)){return }input.addClass(this.markerClassName).append(inst._datepickerDiv).bind("setData.datepicker",function(event,key,value){inst._settings[key]=value}).bind("getData.datepicker",function(event,key){return inst._get(key)});input[0]._calId=inst._id;this._updateDatepicker(inst)},_inlineShow:function(inst){var numMonths=inst._getNumberOfMonths();inst._datepickerDiv.width(numMonths[1]*$(".datepicker",inst._datepickerDiv[0]).width())},_dialogDatepicker:function(input,dateText,onSelect,settings,pos){var inst=this._dialogInst;if(!inst){inst=this._dialogInst=new DatepickerInstance({},false);this._dialogInput=$('<input type="text" size="1" style="position: absolute; top: -100px;"/>');this._dialogInput.keydown(this._doKeyDown);$("body").append(this._dialogInput);this._dialogInput[0]._calId=inst._id}extendRemove(inst._settings,settings||{});this._dialogInput.val(dateText);this._pos=(pos?(pos.length?pos:[pos.pageX,pos.pageY]):null);if(!this._pos){var browserWidth=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth;var browserHeight=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight;var scrollX=document.documentElement.scrollLeft||document.body.scrollLeft;var scrollY=document.documentElement.scrollTop||document.body.scrollTop;this._pos=[(browserWidth/2)-100+scrollX,(browserHeight/2)-150+scrollY]}this._dialogInput.css("left",this._pos[0]+"px").css("top",this._pos[1]+"px");inst._settings.onSelect=onSelect;this._inDialog=true;this._datepickerDiv.addClass("datepicker_dialog");this._showDatepicker(this._dialogInput[0]);if($.blockUI){$.blockUI(this._datepickerDiv)}return this},_showDatepicker:function(input){input=input.target||input;if(input.nodeName.toLowerCase()!="input"){input=$("input",input.parentNode)[0]}if($.datepicker._isDisabledDatepicker(input)||$.datepicker._lastInput==input){return }var inst=$.datepicker._getInst(input._calId);var beforeShow=inst._get("beforeShow");extendRemove(inst._settings,(beforeShow?beforeShow.apply(input,[input,inst]):{}));$.datepicker._hideDatepicker(null,"");$.datepicker._lastInput=input;inst._setDateFromField(input);if($.datepicker._inDialog){input.value=""}if(!$.datepicker._pos){$.datepicker._pos=$.datepicker._findPos(input);$.datepicker._pos[1]+=input.offsetHeight}var isFixed=false;$(input).parents().each(function(){isFixed|=$(this).css("position")=="fixed"});if(isFixed&&$.browser.opera){$.datepicker._pos[0]-=document.documentElement.scrollLeft;$.datepicker._pos[1]-=document.documentElement.scrollTop}inst._datepickerDiv.css("position",($.datepicker._inDialog&&$.blockUI?"static":(isFixed?"fixed":"absolute"))).css({left:$.datepicker._pos[0]+"px",top:$.datepicker._pos[1]+"px"});$.datepicker._pos=null;inst._rangeStart=null;$.datepicker._updateDatepicker(inst);if(!inst._inline){var speed=inst._get("speed");var postProcess=function(){$.datepicker._datepickerShowing=true;$.datepicker._afterShow(inst)};var showAnim=inst._get("showAnim")||"show";inst._datepickerDiv[showAnim](speed,postProcess);if(speed==""){postProcess()}if(inst._input[0].type!="hidden"){inst._input[0].focus()}$.datepicker._curInst=inst}},_updateDatepicker:function(inst){inst._datepickerDiv.empty().append(inst._generateDatepicker());var numMonths=inst._getNumberOfMonths();if(numMonths[0]!=1||numMonths[1]!=1){inst._datepickerDiv.addClass("datepicker_multi")}else{inst._datepickerDiv.removeClass("datepicker_multi")}if(inst._get("isRTL")){inst._datepickerDiv.addClass("datepicker_rtl")}else{inst._datepickerDiv.removeClass("datepicker_rtl")}if(inst._input&&inst._input[0].type!="hidden"){inst._input[0].focus()}},_afterShow:function(inst){var numMonths=inst._getNumberOfMonths();inst._datepickerDiv.width(numMonths[1]*$(".datepicker",inst._datepickerDiv[0])[0].offsetWidth);if($.browser.msie&&parseInt($.browser.version)<7){$("#datepicker_cover").css({width:inst._datepickerDiv.width()+4,height:inst._datepickerDiv.height()+4})}var isFixed=inst._datepickerDiv.css("position")=="fixed";var pos=inst._input?$.datepicker._findPos(inst._input[0]):null;var browserWidth=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth;var browserHeight=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight;var scrollX=(isFixed?0:document.documentElement.scrollLeft||document.body.scrollLeft);var scrollY=(isFixed?0:document.documentElement.scrollTop||document.body.scrollTop);if((inst._datepickerDiv.offset().left+inst._datepickerDiv.width()-(isFixed&&$.browser.msie?document.documentElement.scrollLeft:0))>(browserWidth+scrollX)){inst._datepickerDiv.css("left",Math.max(scrollX,pos[0]+(inst._input?$(inst._input[0]).width():null)-inst._datepickerDiv.width()-(isFixed&&$.browser.opera?document.documentElement.scrollLeft:0))+"px")}if((inst._datepickerDiv.offset().top+inst._datepickerDiv.height()-(isFixed&&$.browser.msie?document.documentElement.scrollTop:0))>(browserHeight+scrollY)){inst._datepickerDiv.css("top",Math.max(scrollY,pos[1]-(this._inDialog?0:inst._datepickerDiv.height())-(isFixed&&$.browser.opera?document.documentElement.scrollTop:0))+"px")}},_findPos:function(obj){while(obj&&(obj.type=="hidden"||obj.nodeType!=1)){obj=obj.nextSibling}var position=$(obj).offset();return[position.left,position.top]},_hideDatepicker:function(input,speed){var inst=this._curInst;if(!inst){return }var rangeSelect=inst._get("rangeSelect");if(rangeSelect&&this._stayOpen){this._selectDate(inst,inst._formatDate(inst._currentDay,inst._currentMonth,inst._currentYear))}this._stayOpen=false;if(this._datepickerShowing){speed=(speed!=null?speed:inst._get("speed"));var showAnim=inst._get("showAnim");inst._datepickerDiv[(showAnim=="slideDown"?"slideUp":(showAnim=="fadeIn"?"fadeOut":"hide"))](speed,function(){$.datepicker._tidyDialog(inst)});if(speed==""){this._tidyDialog(inst)}var onClose=inst._get("onClose");if(onClose){onClose.apply((inst._input?inst._input[0]:null),[inst._getDate(),inst])}this._datepickerShowing=false;this._lastInput=null;inst._settings.prompt=null;if(this._inDialog){this._dialogInput.css({position:"absolute",left:"0",top:"-100px"});if($.blockUI){$.unblockUI();$("body").append(this._datepickerDiv)}}this._inDialog=false}this._curInst=null},_tidyDialog:function(inst){inst._datepickerDiv.removeClass("datepicker_dialog").unbind(".datepicker");$(".datepicker_prompt",inst._datepickerDiv).remove()},_checkExternalClick:function(event){if(!$.datepicker._curInst){return }var $target=$(event.target);if(($target.parents("#datepicker_div").length==0)&&($target.attr("class")!="datepicker_trigger")&&$.datepicker._datepickerShowing&&!($.datepicker._inDialog&&$.blockUI)){$.datepicker._hideDatepicker(null,"")}},_adjustDate:function(id,offset,period){var inst=this._getInst(id);inst._adjustDate(offset,period);this._updateDatepicker(inst)},_gotoToday:function(id){var date=new Date();var inst=this._getInst(id);inst._selectedDay=date.getDate();inst._drawMonth=inst._selectedMonth=date.getMonth();inst._drawYear=inst._selectedYear=date.getFullYear();this._adjustDate(inst)},_selectMonthYear:function(id,select,period){var inst=this._getInst(id);inst._selectingMonthYear=false;inst[period=="M"?"_drawMonth":"_drawYear"]=select.options[select.selectedIndex].value-0;this._adjustDate(inst)},_clickMonthYear:function(id){var inst=this._getInst(id);if(inst._input&&inst._selectingMonthYear&&!$.browser.msie){inst._input[0].focus()}inst._selectingMonthYear=!inst._selectingMonthYear},_changeFirstDay:function(id,day){var inst=this._getInst(id);inst._settings.firstDay=day;this._updateDatepicker(inst)},_selectDay:function(id,month,year,td){if($(td).is(".datepicker_unselectable")){return }var inst=this._getInst(id);var rangeSelect=inst._get("rangeSelect");if(rangeSelect){if(!this._stayOpen){$(".datepicker td").removeClass("datepicker_currentDay");$(td).addClass("datepicker_currentDay")}this._stayOpen=!this._stayOpen}inst._selectedDay=inst._currentDay=$("a",td).html();inst._selectedMonth=inst._currentMonth=month;inst._selectedYear=inst._currentYear=year;this._selectDate(id,inst._formatDate(inst._currentDay,inst._currentMonth,inst._currentYear));if(this._stayOpen){inst._endDay=inst._endMonth=inst._endYear=null;inst._rangeStart=new Date(inst._currentYear,inst._currentMonth,inst._currentDay);this._updateDatepicker(inst)}else{if(rangeSelect){inst._endDay=inst._currentDay;inst._endMonth=inst._currentMonth;inst._endYear=inst._currentYear;inst._selectedDay=inst._currentDay=inst._rangeStart.getDate();inst._selectedMonth=inst._currentMonth=inst._rangeStart.getMonth();inst._selectedYear=inst._currentYear=inst._rangeStart.getFullYear();inst._rangeStart=null;if(inst._inline){this._updateDatepicker(inst)}}}},_clearDate:function(id){var inst=this._getInst(id);if(inst._get("mandatory")){return }this._stayOpen=false;inst._endDay=inst._endMonth=inst._endYear=inst._rangeStart=null;this._selectDate(inst,"")},_selectDate:function(id,dateStr){var inst=this._getInst(id);dateStr=(dateStr!=null?dateStr:inst._formatDate());if(inst._rangeStart){dateStr=inst._formatDate(inst._rangeStart)+inst._get("rangeSeparator")+dateStr}if(inst._input){inst._input.val(dateStr)}var onSelect=inst._get("onSelect");if(onSelect){onSelect.apply((inst._input?inst._input[0]:null),[dateStr,inst])}else{if(inst._input){inst._input.trigger("change")}}if(inst._inline){this._updateDatepicker(inst)}else{if(!this._stayOpen){this._hideDatepicker(null,inst._get("speed"));this._lastInput=inst._input[0];if(typeof (inst._input[0])!="object"){inst._input[0].focus()}this._lastInput=null}}},noWeekends:function(date){var day=date.getDay();return[(day>0&&day<6),""]},iso8601Week:function(date){var checkDate=new Date(date.getFullYear(),date.getMonth(),date.getDate(),(date.getTimezoneOffset()/-60));var firstMon=new Date(checkDate.getFullYear(),1-1,4);var firstDay=firstMon.getDay()||7;firstMon.setDate(firstMon.getDate()+1-firstDay);if(firstDay<4&&checkDate<firstMon){checkDate.setDate(checkDate.getDate()-3);return $.datepicker.iso8601Week(checkDate)}else{if(checkDate>new Date(checkDate.getFullYear(),12-1,28)){firstDay=new Date(checkDate.getFullYear()+1,1-1,4).getDay()||7;if(firstDay>4&&(checkDate.getDay()||7)<firstDay-3){checkDate.setDate(checkDate.getDate()+3);return $.datepicker.iso8601Week(checkDate)}}}return Math.floor(((checkDate-firstMon)/86400000)/7)+1},dateStatus:function(date,inst){return $.datepicker.formatDate(inst._get("dateStatus"),date,inst._getFormatConfig())},parseDate:function(format,value,settings){if(format==null||value==null){throw"Invalid arguments"}value=(typeof value=="object"?value.toString():value+"");if(value==""){return null}var shortYearCutoff=(settings?settings.shortYearCutoff:null)||this._defaults.shortYearCutoff;var dayNamesShort=(settings?settings.dayNamesShort:null)||this._defaults.dayNamesShort;var dayNames=(settings?settings.dayNames:null)||this._defaults.dayNames;var monthNamesShort=(settings?settings.monthNamesShort:null)||this._defaults.monthNamesShort;var monthNames=(settings?settings.monthNames:null)||this._defaults.monthNames;var year=-1;var month=-1;var day=-1;var literal=false;var lookAhead=function(match){var matches=(iFormat+1<format.length&&format.charAt(iFormat+1)==match);if(matches){iFormat++}return matches};var getNumber=function(match){lookAhead(match);var size=(match=="y"?4:2);var num=0;while(size>0&&iValue<value.length&&value.charAt(iValue)>="0"&&value.charAt(iValue)<="9"){num=num*10+(value.charAt(iValue++)-0);size--}if(size==(match=="y"?4:2)){throw"Missing number at position "+iValue}return num};var getName=function(match,shortNames,longNames){var names=(lookAhead(match)?longNames:shortNames);var size=0;for(var j=0;j<names.length;j++){size=Math.max(size,names[j].length)}var name="";var iInit=iValue;while(size>0&&iValue<value.length){name+=value.charAt(iValue++);for(var i=0;i<names.length;i++){if(name==names[i]){return i+1}}size--}throw"Unknown name at position "+iInit};var checkLiteral=function(){if(value.charAt(iValue)!=format.charAt(iFormat)){throw"Unexpected literal at position "+iValue}iValue++};var iValue=0;for(var iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)=="'"&&!lookAhead("'")){literal=false}else{checkLiteral()}}else{switch(format.charAt(iFormat)){case"d":day=getNumber("d");break;case"D":getName("D",dayNamesShort,dayNames);break;case"m":month=getNumber("m");break;case"M":month=getName("M",monthNamesShort,monthNames);break;case"y":year=getNumber("y");break;case"'":if(lookAhead("'")){checkLiteral()}else{literal=true}break;default:checkLiteral()}}}if(year<100){year+=new Date().getFullYear()-new Date().getFullYear()%100+(year<=shortYearCutoff?0:-100)}var date=new Date(year,month-1,day);if(date.getFullYear()!=year||date.getMonth()+1!=month||date.getDate()!=day){throw"Invalid date"}return date},formatDate:function(format,date,settings){if(!date){return""}var dayNamesShort=(settings?settings.dayNamesShort:null)||this._defaults.dayNamesShort;var dayNames=(settings?settings.dayNames:null)||this._defaults.dayNames;var monthNamesShort=(settings?settings.monthNamesShort:null)||this._defaults.monthNamesShort;var monthNames=(settings?settings.monthNames:null)||this._defaults.monthNames;var lookAhead=function(match){var matches=(iFormat+1<format.length&&format.charAt(iFormat+1)==match);if(matches){iFormat++}return matches};var formatNumber=function(match,value){return(lookAhead(match)&&value<10?"0":"")+value};var formatName=function(match,value,shortNames,longNames){return(lookAhead(match)?longNames[value]:shortNames[value])};var output="";var literal=false;if(date){for(var iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)=="'"&&!lookAhead("'")){literal=false}else{output+=format.charAt(iFormat)}}else{switch(format.charAt(iFormat)){case"d":output+=formatNumber("d",date.getDate());break;case"D":output+=formatName("D",date.getDay(),dayNamesShort,dayNames);break;case"m":output+=formatNumber("m",date.getMonth()+1);break;case"M":output+=formatName("M",date.getMonth(),monthNamesShort,monthNames);break;case"y":output+=(lookAhead("y")?date.getFullYear():(date.getYear()%100<10?"0":"")+date.getYear()%100);break;case"'":if(lookAhead("'")){output+="'"}else{literal=true}break;default:output+=format.charAt(iFormat)}}}}return output},_possibleChars:function(format){var chars="";var literal=false;for(var iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)=="'"&&!lookAhead("'")){literal=false}else{chars+=format.charAt(iFormat)}}else{switch(format.charAt(iFormat)){case"d"||"m"||"y":chars+="0123456789";break;case"D"||"M":return null;case"'":if(lookAhead("'")){chars+="'"}else{literal=true}break;default:chars+=format.charAt(iFormat)}}}return chars}});function DatepickerInstance(settings,inline){this._id=$.datepicker._register(this);this._selectedDay=0;this._selectedMonth=0;this._selectedYear=0;this._drawMonth=0;this._drawYear=0;this._input=null;this._inline=inline;this._datepickerDiv=(!inline?$.datepicker._datepickerDiv:$('<div id="datepicker_div_'+this._id+'" class="datepicker_inline">'));this._settings=extendRemove(settings||{});if(inline){this._setDate(this._getDefaultDate())}}$.extend(DatepickerInstance.prototype,{_get:function(name){return this._settings[name]||$.datepicker._defaults[name]},_setDateFromField:function(input){this._input=$(input);var dateFormat=this._get("dateFormat");var dates=this._input?this._input.val().split(this._get("rangeSeparator")):null;this._endDay=this._endMonth=this._endYear=null;var date=defaultDate=this._getDefaultDate();if(dates.length>0){var settings=this._getFormatConfig();if(dates.length>1){date=$.datepicker.parseDate(dateFormat,dates[1],settings)||defaultDate;this._endDay=date.getDate();this._endMonth=date.getMonth();this._endYear=date.getFullYear()}try{date=$.datepicker.parseDate(dateFormat,dates[0],settings)||defaultDate}catch(e){$.datepicker.log(e);date=defaultDate}}this._selectedDay=date.getDate();this._drawMonth=this._selectedMonth=date.getMonth();this._drawYear=this._selectedYear=date.getFullYear();this._currentDay=(dates[0]?date.getDate():0);this._currentMonth=(dates[0]?date.getMonth():0);this._currentYear=(dates[0]?date.getFullYear():0);this._adjustDate()},_getDefaultDate:function(){var date=this._determineDate("defaultDate",new Date());var minDate=this._getMinMaxDate("min",true);var maxDate=this._getMinMaxDate("max");date=(minDate&&date<minDate?minDate:date);date=(maxDate&&date>maxDate?maxDate:date);return date},_determineDate:function(name,defaultDate){var offsetNumeric=function(offset){var date=new Date();date.setDate(date.getDate()+offset);return date};var offsetString=function(offset,getDaysInMonth){var date=new Date();var matches=/^([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?$/.exec(offset);if(matches){var year=date.getFullYear();var month=date.getMonth();var day=date.getDate();switch(matches[2]||"d"){case"d":case"D":day+=(matches[1]-0);break;case"w":case"W":day+=(matches[1]*7);break;case"m":case"M":month+=(matches[1]-0);day=Math.min(day,getDaysInMonth(year,month));break;case"y":case"Y":year+=(matches[1]-0);day=Math.min(day,getDaysInMonth(year,month));break}date=new Date(year,month,day)}return date};var date=this._get(name);return(date==null?defaultDate:(typeof date=="string"?offsetString(date,this._getDaysInMonth):(typeof date=="number"?offsetNumeric(date):date)))},_setDate:function(date,endDate){this._selectedDay=this._currentDay=date.getDate();this._drawMonth=this._selectedMonth=this._currentMonth=date.getMonth();this._drawYear=this._selectedYear=this._currentYear=date.getFullYear();if(this._get("rangeSelect")){if(endDate){this._endDay=endDate.getDate();this._endMonth=endDate.getMonth();this._endYear=endDate.getFullYear()}else{this._endDay=this._currentDay;this._endMonth=this._currentMonth;this._endYear=this._currentYear}}this._adjustDate()},_getDate:function(){var startDate=(!this._currentYear||(this._input&&this._input.val()=="")?null:new Date(this._currentYear,this._currentMonth,this._currentDay));if(this._get("rangeSelect")){return[startDate,(!this._endYear?null:new Date(this._endYear,this._endMonth,this._endDay))]}else{return startDate}},_generateDatepicker:function(){var today=new Date();today=new Date(today.getFullYear(),today.getMonth(),today.getDate());var showStatus=this._get("showStatus");var isRTL=this._get("isRTL");var clear=(this._get("mandatory")?"":'<div class="datepicker_clear"><a onclick="jQuery.datepicker._clearDate('+this._id+');"'+(showStatus?this._addStatus(this._get("clearStatus")||"&#xa0;"):"")+">"+this._get("clearText")+"</a></div>");var controls='<div class="datepicker_control">'+(isRTL?"":clear)+'<div class="datepicker_close"><a onclick="jQuery.datepicker._hideDatepicker();"'+(showStatus?this._addStatus(this._get("closeStatus")||"&#xa0;"):"")+">"+this._get("closeText")+"</a></div>"+(isRTL?clear:"")+"</div>";var prompt=this._get("prompt");var closeAtTop=this._get("closeAtTop");var hideIfNoPrevNext=this._get("hideIfNoPrevNext");var numMonths=this._getNumberOfMonths();var stepMonths=this._get("stepMonths");var isMultiMonth=(numMonths[0]!=1||numMonths[1]!=1);var minDate=this._getMinMaxDate("min",true);var maxDate=this._getMinMaxDate("max");var drawMonth=this._drawMonth;var drawYear=this._drawYear;if(maxDate){var maxDraw=new Date(maxDate.getFullYear(),maxDate.getMonth()-numMonths[1]+1,maxDate.getDate());maxDraw=(minDate&&maxDraw<minDate?minDate:maxDraw);while(new Date(drawYear,drawMonth,1)>maxDraw){drawMonth--;if(drawMonth<0){drawMonth=11;drawYear--}}}var prev='<div class="datepicker_prev">'+(this._canAdjustMonth(-1,drawYear,drawMonth)?'<a onclick="jQuery.datepicker._adjustDate('+this._id+", -"+stepMonths+", 'M');\""+(showStatus?this._addStatus(this._get("prevStatus")||"&#xa0;"):"")+">"+this._get("prevText")+"</a>":(hideIfNoPrevNext?"":"<label>"+this._get("prevText")+"</label>"))+"</div>";var next='<div class="datepicker_next">'+(this._canAdjustMonth(+1,drawYear,drawMonth)?'<a onclick="jQuery.datepicker._adjustDate('+this._id+", +"+stepMonths+", 'M');\""+(showStatus?this._addStatus(this._get("nextStatus")||"&#xa0;"):"")+">"+this._get("nextText")+"</a>":(hideIfNoPrevNext?">":"<label>"+this._get("nextText")+"</label>"))+"</div>";var html=(prompt?'<div class="datepicker_prompt">'+prompt+"</div>":"")+(closeAtTop&&!this._inline?controls:"")+'<div class="datepicker_links">'+(isRTL?next:prev)+(this._isInRange(today)?'<div class="datepicker_current"><a onclick="jQuery.datepicker._gotoToday('+this._id+');"'+(showStatus?this._addStatus(this._get("currentStatus")||"&#xa0;"):"")+">"+this._get("currentText")+"</a></div>":"")+(isRTL?prev:next)+"</div>";var showWeeks=this._get("showWeeks");for(var row=0;row<numMonths[0];row++){for(var col=0;col<numMonths[1];col++){var selectedDate=new Date(drawYear,drawMonth,this._selectedDay);html+='<div class="datepicker_oneMonth'+(col==0?" datepicker_newRow":"")+'">'+this._generateMonthYearHeader(drawMonth,drawYear,minDate,maxDate,selectedDate,row>0||col>0)+'<table class="datepicker" cellpadding="0" cellspacing="0"><thead><tr class="datepicker_titleRow">'+(showWeeks?"<td>"+this._get("weekHeader")+"</td>":"");var firstDay=this._get("firstDay");var changeFirstDay=this._get("changeFirstDay");var dayNames=this._get("dayNames");var dayNamesShort=this._get("dayNamesShort");var dayNamesMin=this._get("dayNamesMin");for(var dow=0;dow<7;dow++){var day=(dow+firstDay)%7;var status=this._get("dayStatus")||"&#xa0;";status=(status.indexOf("DD")>-1?status.replace(/DD/,dayNames[day]):status.replace(/D/,dayNamesShort[day]));html+="<td"+((dow+firstDay+6)%7>=5?' class="datepicker_weekEndCell"':"")+">"+(!changeFirstDay?"<span":'<a onclick="jQuery.datepicker._changeFirstDay('+this._id+", "+day+');"')+(showStatus?this._addStatus(status):"")+' title="'+dayNames[day]+'">'+dayNamesMin[day]+(changeFirstDay?"</a>":"</span>")+"</td>"}html+="</tr></thead><tbody>";var daysInMonth=this._getDaysInMonth(drawYear,drawMonth);if(drawYear==this._selectedYear&&drawMonth==this._selectedMonth){this._selectedDay=Math.min(this._selectedDay,daysInMonth)}var leadDays=(this._getFirstDayOfMonth(drawYear,drawMonth)-firstDay+7)%7;var currentDate=(!this._currentDay?new Date(9999,9,9):new Date(this._currentYear,this._currentMonth,this._currentDay));var endDate=this._endDay?new Date(this._endYear,this._endMonth,this._endDay):currentDate;var printDate=new Date(drawYear,drawMonth,1-leadDays);var numRows=(isMultiMonth?6:Math.ceil((leadDays+daysInMonth)/7));var beforeShowDay=this._get("beforeShowDay");var showOtherMonths=this._get("showOtherMonths");var calculateWeek=this._get("calculateWeek")||$.datepicker.iso8601Week;var dateStatus=this._get("statusForDate")||$.datepicker.dateStatus;for(var dRow=0;dRow<numRows;dRow++){html+='<tr class="datepicker_daysRow">'+(showWeeks?'<td class="datepicker_weekCol">'+calculateWeek(printDate)+"</td>":"");for(var dow=0;dow<7;dow++){var daySettings=(beforeShowDay?beforeShowDay.apply((this._input?this._input[0]:null),[printDate]):[true,""]);var otherMonth=(printDate.getMonth()!=drawMonth);var unselectable=otherMonth||!daySettings[0]||(minDate&&printDate<minDate)||(maxDate&&printDate>maxDate);html+='<td class="datepicker_daysCell'+((dow+firstDay+6)%7>=5?" datepicker_weekEndCell":"")+(otherMonth?" datepicker_otherMonth":"")+(printDate.getTime()==selectedDate.getTime()&&drawMonth==this._selectedMonth?" datepicker_daysCellOver":"")+(unselectable?" datepicker_unselectable":"")+(otherMonth&&!showOtherMonths?"":" "+daySettings[1]+(printDate.getTime()>=currentDate.getTime()&&printDate.getTime()<=endDate.getTime()?" datepicker_currentDay":"")+(printDate.getTime()==today.getTime()?" datepicker_today":""))+'"'+(unselectable?"":" onmouseover=\"jQuery(this).addClass('datepicker_daysCellOver');"+(!showStatus||(otherMonth&&!showOtherMonths)?"":"jQuery('#datepicker_status_"+this._id+"').html('"+(dateStatus.apply((this._input?this._input[0]:null),[printDate,this])||"&#xa0;")+"');")+"\" onmouseout=\"jQuery(this).removeClass('datepicker_daysCellOver');"+(!showStatus||(otherMonth&&!showOtherMonths)?"":"jQuery('#datepicker_status_"+this._id+"').html('&#xa0;');")+'" onclick="jQuery.datepicker._selectDay('+this._id+","+drawMonth+","+drawYear+', this);"')+">"+(otherMonth?(showOtherMonths?printDate.getDate():"&#xa0;"):(unselectable?printDate.getDate():"<a>"+printDate.getDate()+"</a>"))+"</td>";printDate.setDate(printDate.getDate()+1)}html+="</tr>"}drawMonth++;if(drawMonth>11){drawMonth=0;drawYear++}html+="</tbody></table></div>"}}html+=(showStatus?'<div id="datepicker_status_'+this._id+'" class="datepicker_status">'+(this._get("initStatus")||"&#xa0;")+"</div>":"")+(!closeAtTop&&!this._inline?controls:"")+'<div style="clear: both;"></div>'+($.browser.msie&&parseInt($.browser.version)<7&&!this._inline?'<iframe src="javascript:false;" class="datepicker_cover"></iframe>':"");return html},_generateMonthYearHeader:function(drawMonth,drawYear,minDate,maxDate,selectedDate,secondary){minDate=(this._rangeStart&&minDate&&selectedDate<minDate?selectedDate:minDate);var showStatus=this._get("showStatus");var html='<div class="datepicker_header">';var monthNames=this._get("monthNames");if(secondary||!this._get("changeMonth")){html+=monthNames[drawMonth]+"&#xa0;"}else{var inMinYear=(minDate&&minDate.getFullYear()==drawYear);var inMaxYear=(maxDate&&maxDate.getFullYear()==drawYear);html+='<select class="datepicker_newMonth" onchange="jQuery.datepicker._selectMonthYear('+this._id+", this, 'M');\" onclick=\"jQuery.datepicker._clickMonthYear("+this._id+');"'+(showStatus?this._addStatus(this._get("monthStatus")||"&#xa0;"):"")+">";for(var month=0;month<12;month++){if((!inMinYear||month>=minDate.getMonth())&&(!inMaxYear||month<=maxDate.getMonth())){html+='<option value="'+month+'"'+(month==drawMonth?' selected="selected"':"")+">"+monthNames[month]+"</option>"}}html+="</select>"}if(secondary||!this._get("changeYear")){html+=drawYear}else{var years=this._get("yearRange").split(":");var year=0;var endYear=0;if(years.length!=2){year=drawYear-10;endYear=drawYear+10}else{if(years[0].charAt(0)=="+"||years[0].charAt(0)=="-"){year=drawYear+parseInt(years[0],10);endYear=drawYear+parseInt(years[1],10)}else{year=parseInt(years[0],10);endYear=parseInt(years[1],10)}}year=(minDate?Math.max(year,minDate.getFullYear()):year);endYear=(maxDate?Math.min(endYear,maxDate.getFullYear()):endYear);html+='<select class="datepicker_newYear" onchange="jQuery.datepicker._selectMonthYear('+this._id+", this, 'Y');\" onclick=\"jQuery.datepicker._clickMonthYear("+this._id+');"'+(showStatus?this._addStatus(this._get("yearStatus")||"&#xa0;"):"")+">";for(;year<=endYear;year++){html+='<option value="'+year+'"'+(year==drawYear?' selected="selected"':"")+">"+year+"</option>"}html+="</select>"}html+="</div>";return html},_addStatus:function(text){return" onmouseover=\"jQuery('#datepicker_status_"+this._id+"').html('"+text+"');\" onmouseout=\"jQuery('#datepicker_status_"+this._id+"').html('&#xa0;');\""},_adjustDate:function(offset,period){var year=this._drawYear+(period=="Y"?offset:0);var month=this._drawMonth+(period=="M"?offset:0);var day=Math.min(this._selectedDay,this._getDaysInMonth(year,month))+(period=="D"?offset:0);var date=new Date(year,month,day);var minDate=this._getMinMaxDate("min",true);var maxDate=this._getMinMaxDate("max");date=(minDate&&date<minDate?minDate:date);date=(maxDate&&date>maxDate?maxDate:date);this._selectedDay=date.getDate();this._drawMonth=this._selectedMonth=date.getMonth();this._drawYear=this._selectedYear=date.getFullYear()},_getNumberOfMonths:function(){var numMonths=this._get("numberOfMonths");return(numMonths==null?[1,1]:(typeof numMonths=="number"?[1,numMonths]:numMonths))},_getMinMaxDate:function(minMax,checkRange){var date=this._determineDate(minMax+"Date",null);if(date){date.setHours(0);date.setMinutes(0);date.setSeconds(0);date.setMilliseconds(0)}return date||(checkRange?this._rangeStart:null)},_getDaysInMonth:function(year,month){return 32-new Date(year,month,32).getDate()},_getFirstDayOfMonth:function(year,month){return new Date(year,month,1).getDay()},_canAdjustMonth:function(offset,curYear,curMonth){var numMonths=this._getNumberOfMonths();var date=new Date(curYear,curMonth+(offset<0?offset:numMonths[1]),1);if(offset<0){date.setDate(this._getDaysInMonth(date.getFullYear(),date.getMonth()))}return this._isInRange(date)},_isInRange:function(date){var newMinDate=(!this._rangeStart?null:new Date(this._selectedYear,this._selectedMonth,this._selectedDay));newMinDate=(newMinDate&&this._rangeStart<newMinDate?this._rangeStart:newMinDate);var minDate=newMinDate||this._getMinMaxDate("min");var maxDate=this._getMinMaxDate("max");return((!minDate||date>=minDate)&&(!maxDate||date<=maxDate))},_getFormatConfig:function(){var shortYearCutoff=this._get("shortYearCutoff");shortYearCutoff=(typeof shortYearCutoff!="string"?shortYearCutoff:new Date().getFullYear()%100+parseInt(shortYearCutoff,10));return{shortYearCutoff:shortYearCutoff,dayNamesShort:this._get("dayNamesShort"),dayNames:this._get("dayNames"),monthNamesShort:this._get("monthNamesShort"),monthNames:this._get("monthNames")}},_formatDate:function(day,month,year){if(!day){this._currentDay=this._selectedDay;this._currentMonth=this._selectedMonth;this._currentYear=this._selectedYear}var date=(day?(typeof day=="object"?day:new Date(year,month,day)):new Date(this._currentYear,this._currentMonth,this._currentDay));return $.datepicker.formatDate(this._get("dateFormat"),date,this._getFormatConfig())}});function extendRemove(target,props){$.extend(target,props);for(var name in props){if(props[name]==null){target[name]=null}}return target}$.fn.datepicker=function(options){var otherArgs=Array.prototype.slice.call(arguments,1);if(typeof options=="string"&&(options=="isDisabled"||options=="getDate")){return $.datepicker["_"+options+"Datepicker"].apply($.datepicker,[this[0]].concat(otherArgs))}return this.each(function(){typeof options=="string"?$.datepicker["_"+options+"Datepicker"].apply($.datepicker,[this].concat(otherArgs)):$.datepicker._attachDatepicker(this,options)})};$(document).ready(function(){$(document.body).append($.datepicker._datepickerDiv).mousedown($.datepicker._checkExternalClick)});$.datepicker=new Datepicker()})(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-12-20 08:43:48 -0600 (Thu, 20 Dec 2007) $
 * $Rev: 4257 $
 *
 * Version: 1.2
 *
 * Requires: jQuery 1.2+
 */
(function($){$.dimensions={version:'1.2'};$.each(['Height','Width'],function(i,name){$.fn['inner'+name]=function(){if(!this[0])return;var torl=name=='Height'?'Top':'Left',borr=name=='Height'?'Bottom':'Right';return this.is(':visible')?this[0]['client'+name]:num(this,name.toLowerCase())+num(this,'padding'+torl)+num(this,'padding'+borr);};$.fn['outer'+name]=function(options){if(!this[0])return;var torl=name=='Height'?'Top':'Left',borr=name=='Height'?'Bottom':'Right';options=$.extend({margin:false},options||{});var val=this.is(':visible')?this[0]['offset'+name]:num(this,name.toLowerCase())+num(this,'border'+torl+'Width')+num(this,'border'+borr+'Width')+num(this,'padding'+torl)+num(this,'padding'+borr);return val+(options.margin?(num(this,'margin'+torl)+num(this,'margin'+borr)):0);};});$.each(['Left','Top'],function(i,name){$.fn['scroll'+name]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(name=='Left'?val:$(window)['scrollLeft'](),name=='Top'?val:$(window)['scrollTop']()):this['scroll'+name]=val;}):this[0]==window||this[0]==document?self[(name=='Left'?'pageXOffset':'pageYOffset')]||$.boxModel&&document.documentElement['scroll'+name]||document.body['scroll'+name]:this[0]['scroll'+name];};});$.fn.extend({position:function(){var left=0,top=0,elem=this[0],offset,parentOffset,offsetParent,results;if(elem){offsetParent=this.offsetParent();offset=this.offset();parentOffset=offsetParent.offset();offset.top-=num(elem,'marginTop');offset.left-=num(elem,'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)&&$.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return $(offsetParent);}});function num(el,prop){return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;};})(jQuery);


/* Copyright (c) 2006 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.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * $LastChangedDate: 2007-06-20 16:25:35 -0500 (Wed, 20 Jun 2007) $
 * $Rev: 2125 $
 *
 * Version: 2.2
 */
(function($){$.fn.extend({mousewheel:function(f){if(!f.guid)f.guid=$.event.guid++;if(!$.event._mwCache)$.event._mwCache=[];return this.each(function(){if(this._mwHandlers)return this._mwHandlers.push(f);else this._mwHandlers=[];this._mwHandlers.push(f);var s=this;this._mwHandler=function(e){e=$.event.fix(e||window.event);$.extend(e,this._mwCursorPos||{});var delta=0,returnValue=true;if(e.wheelDelta)delta=e.wheelDelta/120;if(e.detail)delta=-e.detail/3;if(window.opera)delta=-e.wheelDelta;for(var i=0;i<s._mwHandlers.length;i++)if(s._mwHandlers[i])if(s._mwHandlers[i].call(s,e,delta)===false){returnValue=false;e.preventDefault();e.stopPropagation();}return returnValue;};if($.browser.mozilla&&!this._mwFixCursorPos){this._mwFixCursorPos=function(e){this._mwCursorPos={pageX:e.pageX,pageY:e.pageY,clientX:e.clientX,clientY:e.clientY};};$(this).bind('mousemove',this._mwFixCursorPos);}if(this.addEventListener)if($.browser.mozilla)this.addEventListener('DOMMouseScroll',this._mwHandler,false);else this.addEventListener('mousewheel',this._mwHandler,false);else
this.onmousewheel=this._mwHandler;$.event._mwCache.push($(this));});},unmousewheel:function(f){return this.each(function(){if(f&&this._mwHandlers){for(var i=0;i<this._mwHandlers.length;i++)if(this._mwHandlers[i]&&this._mwHandlers[i].guid==f.guid)delete this._mwHandlers[i];}else{if($.browser.mozilla&&!this._mwFixCursorPos)$(this).unbind('mousemove',this._mwFixCursorPos);if(this.addEventListener)if($.browser.mozilla)this.removeEventListener('DOMMouseScroll',this._mwHandler,false);else this.removeEventListener('mousewheel',this._mwHandler,false);else
this.onmousewheel=null;this._mwHandlers=this._mwHandler=this._mwFixCursorPos=this._mwCursorPos=null;}});}});$(window).one('unload',function(){var els=$.event._mwCache||[];for(var i=0;i<els.length;i++)els[i].unmousewheel();});})(jQuery);

/*
 * 
 * TableSorter 2.0 - Client-side table sorting with ease!
 * Version 2.0.3
 * @requires jQuery v1.2.3
 * 
 * Copyright (c) 2007 Christian Bach
 * Examples and docs at: http://tablesorter.com
 * 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({tablesorter:new function(){var parsers=[],widgets=[];this.defaults={cssHeader:"header",cssAsc:"headerSortUp",cssDesc:"headerSortDown",sortInitialOrder:"asc",sortMultiSortKey:"shiftKey",sortForce:null,sortAppend:null,textExtraction:"simple",parsers:{},widgets:[],widgetZebra:{css:["even","odd"]},headers:{},widthFixed:false,cancelSelection:true,sortList:[],headerList:[],dateFormat:"us",decimal:'.',debug:false};function benchmark(s,d){log(s+","+(new Date().getTime()-d.getTime())+"ms");}this.benchmark=benchmark;function log(s){if(typeof console!="undefined"&&typeof console.debug!="undefined"){console.log(s);}else{alert(s);}}function buildParserCache(table,$headers){if(table.config.debug){var parsersDebug="";}var rows=table.tBodies[0].rows;if(table.tBodies[0].rows[0]){var list=[],cells=rows[0].cells,l=cells.length;for(var i=0;i<l;i++){var p=false;if($.metadata&&($($headers[i]).metadata()&&$($headers[i]).metadata().sorter)){p=getParserById($($headers[i]).metadata().sorter);}else if((table.config.headers[i]&&table.config.headers[i].sorter)){p=getParserById(table.config.headers[i].sorter);}if(!p){p=detectParserForColumn(table,cells[i]);}if(table.config.debug){parsersDebug+="column:"+i+" parser:"+p.id+"\n";}list.push(p);}}if(table.config.debug){log(parsersDebug);}return list;};function detectParserForColumn(table,node){var l=parsers.length;for(var i=1;i<l;i++){if(parsers[i].is($.trim(getElementText(table.config,node)),table,node)){return parsers[i];}}return parsers[0];}function getParserById(name){var l=parsers.length;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==name.toLowerCase()){return parsers[i];}}return false;}function buildCache(table){if(table.config.debug){var cacheTime=new Date();}var totalRows=(table.tBodies[0]&&table.tBodies[0].rows.length)||0,totalCells=(table.tBodies[0].rows[0]&&table.tBodies[0].rows[0].cells.length)||0,parsers=table.config.parsers,cache={row:[],normalized:[]};for(var i=0;i<totalRows;++i){var c=table.tBodies[0].rows[i],cols=[];cache.row.push($(c));for(var j=0;j<totalCells;++j){cols.push(parsers[j].format(getElementText(table.config,c.cells[j]),table,c.cells[j]));}cols.push(i);cache.normalized.push(cols);cols=null;};if(table.config.debug){benchmark("Building cache for "+totalRows+" rows:",cacheTime);}return cache;};function getElementText(config,node){if(!node)return"";var t="";if(config.textExtraction=="simple"){if(node.childNodes[0]&&node.childNodes[0].hasChildNodes()){t=node.childNodes[0].innerHTML;}else{t=node.innerHTML;}}else{if(typeof(config.textExtraction)=="function"){t=config.textExtraction(node);}else{t=$(node).text();}}return t;}function appendToTable(table,cache){if(table.config.debug){var appendTime=new Date()}var c=cache,r=c.row,n=c.normalized,totalRows=n.length,checkCell=(n[0].length-1),tableBody=$(table.tBodies[0]),rows=[];for(var i=0;i<totalRows;i++){rows.push(r[n[i][checkCell]]);if(!table.config.appender){var o=r[n[i][checkCell]];var l=o.length;for(var j=0;j<l;j++){tableBody[0].appendChild(o[j]);}}}if(table.config.appender){table.config.appender(table,rows);}rows=null;if(table.config.debug){benchmark("Rebuilt table:",appendTime);}applyWidget(table);setTimeout(function(){$(table).trigger("sortEnd");},0);};function buildHeaders(table){if(table.config.debug){var time=new Date();}var meta=($.metadata)?true:false,tableHeadersRows=[];for(var i=0;i<table.tHead.rows.length;i++){tableHeadersRows[i]=0;};$tableHeaders=$("thead th",table);$tableHeaders.each(function(index){this.count=0;this.column=index;this.order=formatSortingOrder(table.config.sortInitialOrder);if(checkHeaderMetadata(this)||checkHeaderOptions(table,index))this.sortDisabled=true;if(!this.sortDisabled){$(this).addClass(table.config.cssHeader);}table.config.headerList[index]=this;});if(table.config.debug){benchmark("Built headers:",time);log($tableHeaders);}return $tableHeaders;};function checkCellColSpan(table,rows,row){var arr=[],r=table.tHead.rows,c=r[row].cells;for(var i=0;i<c.length;i++){var cell=c[i];if(cell.colSpan>1){arr=arr.concat(checkCellColSpan(table,headerArr,row++));}else{if(table.tHead.length==1||(cell.rowSpan>1||!r[row+1])){arr.push(cell);}}}return arr;};function checkHeaderMetadata(cell){if(($.metadata)&&($(cell).metadata().sorter===false)){return true;};return false;}function checkHeaderOptions(table,i){if((table.config.headers[i])&&(table.config.headers[i].sorter===false)){return true;};return false;}function applyWidget(table){var c=table.config.widgets;var l=c.length;for(var i=0;i<l;i++){getWidgetById(c[i]).format(table);}}function getWidgetById(name){var l=widgets.length;for(var i=0;i<l;i++){if(widgets[i].id.toLowerCase()==name.toLowerCase()){return widgets[i];}}};function formatSortingOrder(v){if(typeof(v)!="Number"){i=(v.toLowerCase()=="desc")?1:0;}else{i=(v==(0||1))?v:0;}return i;}function isValueInArray(v,a){var l=a.length;for(var i=0;i<l;i++){if(a[i][0]==v){return true;}}return false;}function setHeadersCss(table,$headers,list,css){$headers.removeClass(css[0]).removeClass(css[1]);var h=[];$headers.each(function(offset){if(!this.sortDisabled){h[this.column]=$(this);}});var l=list.length;for(var i=0;i<l;i++){h[list[i][0]].addClass(css[list[i][1]]);}}function fixColumnWidth(table,$headers){var c=table.config;if(c.widthFixed){var colgroup=$('<colgroup>');$("tr:first td",table.tBodies[0]).each(function(){colgroup.append($('<col>').css('width',$(this).width()));});$(table).prepend(colgroup);};}function updateHeaderSortCount(table,sortList){var c=table.config,l=sortList.length;for(var i=0;i<l;i++){var s=sortList[i],o=c.headerList[s[0]];o.count=s[1];o.count++;}}function multisort(table,sortList,cache){if(table.config.debug){var sortTime=new Date();}var dynamicExp="var sortWrapper = function(a,b) {",l=sortList.length;for(var i=0;i<l;i++){var c=sortList[i][0];var order=sortList[i][1];var s=(getCachedSortType(table.config.parsers,c)=="text")?((order==0)?"sortText":"sortTextDesc"):((order==0)?"sortNumeric":"sortNumericDesc");var e="e"+i;dynamicExp+="var "+e+" = "+s+"(a["+c+"],b["+c+"]); ";dynamicExp+="if("+e+") { return "+e+"; } ";dynamicExp+="else { ";}var orgOrderCol=cache.normalized[0].length-1;dynamicExp+="return a["+orgOrderCol+"]-b["+orgOrderCol+"];";for(var i=0;i<l;i++){dynamicExp+="}; ";}dynamicExp+="return 0; ";dynamicExp+="}; ";eval(dynamicExp);cache.normalized.sort(sortWrapper);if(table.config.debug){benchmark("Sorting on "+sortList.toString()+" and dir "+order+" time:",sortTime);}return cache;};function sortText(a,b){return((a<b)?-1:((a>b)?1:0));};function sortTextDesc(a,b){return((b<a)?-1:((b>a)?1:0));};function sortNumeric(a,b){return a-b;};function sortNumericDesc(a,b){return b-a;};function getCachedSortType(parsers,i){return parsers[i].type;};this.construct=function(settings){return this.each(function(){if(!this.tHead||!this.tBodies)return;var $this,$document,$headers,cache,config,shiftDown=0,sortOrder;this.config={};config=$.extend(this.config,$.tablesorter.defaults,settings);$this=$(this);$headers=buildHeaders(this);this.config.parsers=buildParserCache(this,$headers);cache=buildCache(this);var sortCSS=[config.cssDesc,config.cssAsc];fixColumnWidth(this);$headers.click(function(e){$this.trigger("sortStart");var totalRows=($this[0].tBodies[0]&&$this[0].tBodies[0].rows.length)||0;if(!this.sortDisabled&&totalRows>0){var $cell=$(this);var i=this.column;this.order=this.count++%2;if(!e[config.sortMultiSortKey]){config.sortList=[];if(config.sortForce!=null){var a=config.sortForce;for(var j=0;j<a.length;j++){if(a[j][0]!=i){config.sortList.push(a[j]);}}}config.sortList.push([i,this.order]);}else{if(isValueInArray(i,config.sortList)){for(var j=0;j<config.sortList.length;j++){var s=config.sortList[j],o=config.headerList[s[0]];if(s[0]==i){o.count=s[1];o.count++;s[1]=o.count%2;}}}else{config.sortList.push([i,this.order]);}};setTimeout(function(){setHeadersCss($this[0],$headers,config.sortList,sortCSS);appendToTable($this[0],multisort($this[0],config.sortList,cache));},1);return false;}}).mousedown(function(){if(config.cancelSelection){this.onselectstart=function(){return false};return false;}});$this.bind("update",function(){this.config.parsers=buildParserCache(this,$headers);cache=buildCache(this);}).bind("sorton",function(e,list){$(this).trigger("sortStart");config.sortList=list;var sortList=config.sortList;updateHeaderSortCount(this,sortList);setHeadersCss(this,$headers,sortList,sortCSS);appendToTable(this,multisort(this,sortList,cache));}).bind("appendCache",function(){appendToTable(this,cache);}).bind("applyWidgetId",function(e,id){getWidgetById(id).format(this);}).bind("applyWidgets",function(){applyWidget(this);});if($.metadata&&($(this).metadata()&&$(this).metadata().sortlist)){config.sortList=$(this).metadata().sortlist;}if(config.sortList.length>0){$this.trigger("sorton",[config.sortList]);}applyWidget(this);});};this.addParser=function(parser){var l=parsers.length,a=true;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==parser.id.toLowerCase()){a=false;}}if(a){parsers.push(parser);};};this.addWidget=function(widget){widgets.push(widget);};this.formatFloat=function(s){var i=parseFloat(s);return(isNaN(i))?0:i;};this.formatInt=function(s){var i=parseInt(s);return(isNaN(i))?0:i;};this.isDigit=function(s,config){var DECIMAL='\\'+config.decimal;var exp='/(^[+]?0('+DECIMAL+'0+)?$)|(^([-+]?[1-9][0-9]*)$)|(^([-+]?((0?|[1-9][0-9]*)'+DECIMAL+'(0*[1-9][0-9]*)))$)|(^[-+]?[1-9]+[0-9]*'+DECIMAL+'0+$)/';return RegExp(exp).test($.trim(s));};this.clearTableBody=function(table){if($.browser.msie){function empty(){while(this.firstChild)this.removeChild(this.firstChild);}empty.apply(table.tBodies[0]);}else{table.tBodies[0].innerHTML="";}};}});$.fn.extend({tablesorter:$.tablesorter.construct});var ts=$.tablesorter;ts.addParser({id:"text",is:function(s){return true;},format:function(s){return $.trim(s.toLowerCase());},type:"text"});ts.addParser({id:"digit",is:function(s,table){var c=table.config;return $.tablesorter.isDigit(s,c);},format:function(s){return $.tablesorter.formatFloat(s);},type:"numeric"});ts.addParser({id:"currency",is:function(s){return/^[£$€?.]/.test(s);},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/[^0-9.]/g),""));},type:"numeric"});ts.addParser({id:"ipAddress",is:function(s){return/^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s);},format:function(s){var a=s.split("."),r="",l=a.length;for(var i=0;i<l;i++){var item=a[i];if(item.length==2){r+="0"+item;}else{r+=item;}}return $.tablesorter.formatFloat(r);},type:"numeric"});ts.addParser({id:"url",is:function(s){return/^(https?|ftp|file):\/\/$/.test(s);},format:function(s){return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//),''));},type:"text"});ts.addParser({id:"isoDate",is:function(s){return/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(s);},format:function(s){return $.tablesorter.formatFloat((s!="")?new Date(s.replace(new RegExp(/-/g),"/")).getTime():"0");},type:"numeric"});ts.addParser({id:"percent",is:function(s){return/\%$/.test($.trim(s));},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/%/g),""));},type:"numeric"});ts.addParser({id:"usLongDate",is:function(s){return s.match(new RegExp(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/));},format:function(s){return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"shortDate",is:function(s){return/\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);},format:function(s,table){var c=table.config;s=s.replace(/\-/g,"/");if(c.dateFormat=="us"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$1/$2");}else if(c.dateFormat=="uk"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$2/$1");}else if(c.dateFormat=="dd/mm/yy"||c.dateFormat=="dd-mm-yy"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/,"$1/$2/$3");}return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"time",is:function(s){return/^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s);},format:function(s){return $.tablesorter.formatFloat(new Date("2000/01/01 "+s).getTime());},type:"numeric"});ts.addParser({id:"metadata",is:function(s){return false;},format:function(s,table,cell){var c=table.config,p=(!c.parserMetadataName)?'sortValue':c.parserMetadataName;return $(cell).metadata()[p];},type:"numeric"});ts.addWidget({id:"zebra",format:function(table){if(table.config.debug){var time=new Date();}$("tr:visible",table.tBodies[0]).filter(':even').removeClass(table.config.widgetZebra.css[1]).addClass(table.config.widgetZebra.css[0]).end().filter(':odd').removeClass(table.config.widgetZebra.css[0]).addClass(table.config.widgetZebra.css[1]);if(table.config.debug){$.tablesorter.benchmark("Applying Zebra widget",time);}}});})(jQuery);

/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Date: 2/19/2008
 * @author Ariel Flesler
 * @version 1.3.3
 */
(function($){var o=$.scrollTo=function(a,b,c){o.window().scrollTo(a,b,c)};o.defaults={axis:'y',duration:1};o.window=function(){return $($.browser.safari?'body':'html')};$.fn.scrollTo=function(l,m,n){if(typeof m=='object'){n=m;m=0}n=$.extend({},o.defaults,n);m=m||n.speed||n.duration;n.queue=n.queue&&n.axis.length>1;if(n.queue)m/=2;n.offset=j(n.offset);n.over=j(n.over);return this.each(function(){var a=this,b=$(a),t=l,c,d={},w=b.is('html,body');switch(typeof t){case'number':case'string':if(/^([+-]=)?\d+(px)?$/.test(t)){t=j(t);break}t=$(t,this);case'object':if(t.is||t.style)c=(t=$(t)).offset()}$.each(n.axis.split(''),function(i,f){var P=f=='x'?'Left':'Top',p=P.toLowerCase(),k='scroll'+P,e=a[k],D=f=='x'?'Width':'Height';if(c){d[k]=c[p]+(w?0:e-b.offset()[p]);if(n.margin){d[k]-=parseInt(t.css('margin'+P))||0;d[k]-=parseInt(t.css('border'+P+'Width'))||0}d[k]+=n.offset[p]||0;if(n.over[p])d[k]+=t[D.toLowerCase()]()*n.over[p]}else d[k]=t[p];if(/^\d+$/.test(d[k]))d[k]=d[k]<=0?0:Math.min(d[k],h(D));if(!i&&n.queue){if(e!=d[k])g(n.onAfterFirst);delete d[k]}});g(n.onAfter);function g(a){b.animate(d,m,n.easing,a&&function(){a.call(this,l)})};function h(D){var b=w?$.browser.opera?document.body:document.documentElement:a;return b['scroll'+D]-b['client'+D]}})};function j(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);

/* Copyright (c) 2006 Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * See http://kelvinluck.com/assets/jquery/jScrollPane/
 * $Id: jScrollPane.js 4765 2008-02-17 21:14:59Z kelvinluck $
 */

/**
 * Replace the vertical scroll bars on any matched elements with a fancy
 * styleable (via CSS) version. With JS disabled the elements will
 * gracefully degrade to the browsers own implementation of overflow:auto.
 * If the mousewheel plugin has been included on the page then the scrollable areas will also
 * respond to the mouse wheel.
 *
 * @example jQuery(".scroll-pane").jScrollPane();
 *
 * @name jScrollPane
 * @type jQuery
 * @param Object	settings	hash with options, described below.
 *								scrollbarWidth	-	The width of the generated scrollbar in pixels
 *								scrollbarMargin	-	The amount of space to leave on the side of the scrollbar in pixels
 *								wheelSpeed		-	The speed the pane will scroll in response to the mouse wheel in pixels
 *								showArrows		-	Whether to display arrows for the user to scroll with
 *								arrowSize		-	The height of the arrow buttons if showArrows=true
 *								animateTo		-	Whether to animate when calling scrollTo and scrollBy
 *								dragMinHeight	-	The minimum height to allow the drag bar to be
 *								dragMaxHeight	-	The maximum height to allow the drag bar to be
 *								animateInterval	-	The interval in milliseconds to update an animating scrollPane (default 100)
 *								animateStep		-	The amount to divide the remaining scroll distance by when animating (default 3)
 *								maintainPosition-	Whether you want the contents of the scroll pane to maintain it's position when you re-initialise it - so it doesn't scroll as you add more content (default true)
 *								scrollbarOnLeft	-	Display the scrollbar on the left side?  (needs stylesheet changes, see examples.html)
 * @return jQuery
 * @cat Plugins/jScrollPane
 * @author Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 */
jQuery.jScrollPane={active:[]};jQuery.fn.jScrollPane=function(settings){settings=jQuery.extend({scrollbarWidth:10,scrollbarMargin:5,wheelSpeed:18,showArrows:false,arrowSize:0,animateTo:false,dragMinHeight:1,dragMaxHeight:99999,animateInterval:100,animateStep:3,maintainPosition:true,scrollbarOnLeft:false},settings);return this.each(function(){var $this=jQuery(this);if(jQuery(this).parent().is('.jScrollPaneContainer')){var currentScrollPosition=settings.maintainPosition?$this.offset({relativeTo:jQuery(this).parent()[0]}).top:0;var $c=jQuery(this).parent();var paneWidth=$c.innerWidth();var paneHeight=$c.outerHeight();var trackHeight=paneHeight;if($c.unmousewheel){$c.unmousewheel();}jQuery('>.jScrollPaneTrack, >.jScrollArrowUp, >.jScrollArrowDown',$c).remove();$this.css({'top':0});}else{var currentScrollPosition=0;this.originalPadding=$this.css('paddingTop')+' '+$this.css('paddingRight')+' '+$this.css('paddingBottom')+' '+$this.css('paddingLeft');this.originalSidePaddingTotal=(parseInt($this.css('paddingLeft'))||0)+(parseInt($this.css('paddingRight'))||0);var paneWidth=$this.innerWidth();var paneHeight=$this.innerHeight();var trackHeight=paneHeight;$this.wrap(jQuery('<div></div>').attr({'className':'jScrollPaneContainer'}).css({'height':paneHeight+'px','width':paneWidth+'px'}));jQuery(document).bind('emchange',function(e,cur,prev){$this.jScrollPane(settings);});}var p=this.originalSidePaddingTotal;var cssToApply={'height':'auto','width':paneWidth-settings.scrollbarWidth-settings.scrollbarMargin-p+'px'};if(settings.scrollbarOnLeft){cssToApply.paddingLeft=settings.scrollbarMargin+settings.scrollbarWidth+'px';}else{cssToApply.paddingRight=settings.scrollbarMargin+'px';}$this.css(cssToApply);var contentHeight=$this.outerHeight();var percentInView=paneHeight/contentHeight;if(percentInView<.99){var $container=$this.parent();$container.append(jQuery('<div></div>').attr({'className':'jScrollPaneTrack'}).css({'width':settings.scrollbarWidth+'px'}).append(jQuery('<div></div>').attr({'className':'jScrollPaneDrag'}).css({'width':settings.scrollbarWidth+'px'}).append(jQuery('<div></div>').attr({'className':'jScrollPaneDragTop'}).css({'width':settings.scrollbarWidth+'px'}),jQuery('<div></div>').attr({'className':'jScrollPaneDragBottom'}).css({'width':settings.scrollbarWidth+'px'}))));var $track=jQuery('>.jScrollPaneTrack',$container);var $drag=jQuery('>.jScrollPaneTrack .jScrollPaneDrag',$container);if(settings.showArrows){var currentArrowButton;var currentArrowDirection;var currentArrowInterval;var currentArrowInc;var whileArrowButtonDown=function(){if(currentArrowInc>4||currentArrowInc%4==0){positionDrag(dragPosition+currentArrowDirection*mouseWheelMultiplier);}currentArrowInc++;};var onArrowMouseUp=function(event){jQuery('html').unbind('mouseup',onArrowMouseUp);currentArrowButton.removeClass('jScrollActiveArrowButton');clearInterval(currentArrowInterval);};var onArrowMouseDown=function(){jQuery('html').bind('mouseup',onArrowMouseUp);currentArrowButton.addClass('jScrollActiveArrowButton');currentArrowInc=0;whileArrowButtonDown();currentArrowInterval=setInterval(whileArrowButtonDown,100);};$container.append(jQuery('<a></a>').attr({'href':'javascript:;','className':'jScrollArrowUp'}).css({'width':settings.scrollbarWidth+'px'}).html('Scroll up').bind('mousedown',function(){currentArrowButton=jQuery(this);currentArrowDirection=-1;onArrowMouseDown();this.blur();return false;}),jQuery('<a></a>').attr({'href':'javascript:;','className':'jScrollArrowDown'}).css({'width':settings.scrollbarWidth+'px'}).html('Scroll down').bind('mousedown',function(){currentArrowButton=jQuery(this);currentArrowDirection=1;onArrowMouseDown();this.blur();return false;}));var $upArrow=jQuery('>.jScrollArrowUp',$container);var $downArrow=jQuery('>.jScrollArrowDown',$container);if(settings.arrowSize){trackHeight=paneHeight-settings.arrowSize-settings.arrowSize;$track.css({'height':trackHeight+'px',top:settings.arrowSize+'px'})}else{var topArrowHeight=$upArrow.height();settings.arrowSize=topArrowHeight;trackHeight=paneHeight-topArrowHeight-$downArrow.height();$track.css({'height':trackHeight+'px',top:topArrowHeight+'px'})}}var $pane=jQuery(this).css({'position':'absolute','overflow':'visible'});var currentOffset;var maxY;var mouseWheelMultiplier;var dragPosition=0;var dragMiddle=percentInView*paneHeight/2;var getPos=function(event,c){var p=c=='X'?'Left':'Top';return event['page'+c]||(event['client'+c]+(document.documentElement['scroll'+p]||document.body['scroll'+p]))||0;};var ignoreNativeDrag=function(){return false;};var initDrag=function(){ceaseAnimation();currentOffset=$drag.offset(false);currentOffset.top-=dragPosition;maxY=trackHeight-$drag[0].offsetHeight;mouseWheelMultiplier=2*settings.wheelSpeed*maxY/contentHeight;};var onStartDrag=function(event){initDrag();dragMiddle=getPos(event,'Y')-dragPosition-currentOffset.top;jQuery('html').bind('mouseup',onStopDrag).bind('mousemove',updateScroll);if(jQuery.browser.msie){jQuery('html').bind('dragstart',ignoreNativeDrag).bind('selectstart',ignoreNativeDrag);}return false;};var onStopDrag=function(){jQuery('html').unbind('mouseup',onStopDrag).unbind('mousemove',updateScroll);dragMiddle=percentInView*paneHeight/2;if(jQuery.browser.msie){jQuery('html').unbind('dragstart',ignoreNativeDrag).unbind('selectstart',ignoreNativeDrag);}};var positionDrag=function(destY){destY=destY<0?0:(destY>maxY?maxY:destY);dragPosition=destY;$drag.css({'top':destY+'px'});var p=destY/maxY;$pane.css({'top':((paneHeight-contentHeight)*p)+'px'});$this.trigger('scroll');if(settings.showArrows){$upArrow[destY==0?'addClass':'removeClass']('disabled');$downArrow[destY==maxY?'addClass':'removeClass']('disabled');}};var updateScroll=function(e){positionDrag(getPos(e,'Y')-currentOffset.top-dragMiddle);};var dragH=Math.max(Math.min(percentInView*(paneHeight-settings.arrowSize*2),settings.dragMaxHeight),settings.dragMinHeight);$drag.css({'height':dragH+'px'}).bind('mousedown',onStartDrag);var trackScrollInterval;var trackScrollInc;var trackScrollMousePos;var doTrackScroll=function(){if(trackScrollInc>8||trackScrollInc%4==0){positionDrag((dragPosition-((dragPosition-trackScrollMousePos)/2)));}trackScrollInc++;};var onStopTrackClick=function(){clearInterval(trackScrollInterval);jQuery('html').unbind('mouseup',onStopTrackClick).unbind('mousemove',onTrackMouseMove);};var onTrackMouseMove=function(event){trackScrollMousePos=getPos(event,'Y')-currentOffset.top-dragMiddle;};var onTrackClick=function(event){initDrag();onTrackMouseMove(event);trackScrollInc=0;jQuery('html').bind('mouseup',onStopTrackClick).bind('mousemove',onTrackMouseMove);trackScrollInterval=setInterval(doTrackScroll,100);doTrackScroll();};$track.bind('mousedown',onTrackClick);if($container.mousewheel){$container.mousewheel(function(event,delta){initDrag();ceaseAnimation();var d=dragPosition;positionDrag(dragPosition-delta*mouseWheelMultiplier);var dragOccured=d!=dragPosition;return!dragOccured;},false);}var _animateToPosition;var _animateToInterval;function animateToPosition(){var diff=(_animateToPosition-dragPosition)/settings.animateStep;if(diff>1||diff<-1){positionDrag(dragPosition+diff);}else{positionDrag(_animateToPosition);ceaseAnimation();}}var ceaseAnimation=function(){if(_animateToInterval){clearInterval(_animateToInterval);delete _animateToPosition;}};var scrollTo=function(pos,preventAni){if(typeof pos=="string"){$e=jQuery(pos,this);if(!$e.length)return;pos=$e.offset().top-$this.offset().top;}ceaseAnimation();var destDragPosition=-pos/(paneHeight-contentHeight)*maxY;if(!preventAni||settings.animateTo){_animateToPosition=destDragPosition;_animateToInterval=setInterval(animateToPosition,settings.animateInterval);}else{positionDrag(destDragPosition);}};$this[0].scrollTo=scrollTo;$this[0].scrollBy=function(delta){var currentPos=-parseInt($pane.css('top'))||0;scrollTo(currentPos+delta);};initDrag();scrollTo(-currentScrollPosition,true);jQuery.jScrollPane.active.push($this[0]);}else{$this.css({'height':paneHeight+'px','width':paneWidth-this.originalSidePaddingTotal+'px','padding':this.originalPadding});}})};jQuery(window).bind('unload',function(){var els=jQuery.jScrollPane.active;for(var i=0;i<els.length;i++){els[i].scrollTo=els[i].scrollBy=null;}});

/*
 * jQuery ifixpng plugin
 * (previously known as pngfix)
 * Version 2.1  (23/04/2008)
 * @requires jQuery v1.1.3 or above
 *
 * Examples at: http://jquery.khurshid.com
 * Copyright (c) 2007 Kush M.
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */

 /**
  *
  * @example
  *
  * optional if location of pixel.gif if different to default which is images/pixel.gif
  * $.ifixpng('media/pixel.gif');
  *
  * $('img[@src$=.png], #panel').ifixpng();
  *
  * @apply hack to all png images and #panel which icluded png img in its css
  *
  * @name ifixpng
  * @type jQuery
  * @cat Plugins/Image
  * @return jQuery
  * @author jQuery Community
  */
	/*
	 * jQuery ifixpng plugin
	 * (previously known as pngfix)
	 * Version 2.1  (23/04/2008)
	 * @requires jQuery v1.1.3 or above
	 *
	 * Examples at: http://jquery.khurshid.com
	 * Copyright (c) 2007 Kush M.
	 * Dual licensed under the MIT and GPL licenses:
	 * http://www.opensource.org/licenses/mit-license.php
	 * http://www.gnu.org/licenses/gpl.html
	 */

	 /**
	  *
	  * @example
	  *
	  * optional if location of pixel.gif if different to default which is images/pixel.gif
	  * $.ifixpng('media/pixel.gif');
	  *
	  * $('img[@src$=.png], #panel').ifixpng();
	  *
	  * @apply hack to all png images and #panel which icluded png img in its css
	  *
	  * @name ifixpng
	  * @type jQuery
	  * @cat Plugins/Image
	  * @return jQuery
	  * @author jQuery Community
	  */

	(function($) {

		/**
		 * helper variables and function
		 */
		$.ifixpng = function(customPixel) {
			$.ifixpng.pixel = customPixel;
		};

		$.ifixpng.getPixel = function() {
			return $.ifixpng.pixel || 'images/pixel.gif';
		};

		var hack = {
			ltie7  : $.browser.msie && $.browser.version < 7,
			filter : function(src) {
				return "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=crop,src='"+src+"')";
			}
		};

		/**
		 * Applies ie png hack to selected dom elements
		 *
		 * $('img[@src$=.png]').ifixpng();
		 * @desc apply hack to all images with png extensions
		 *
		 * $('#panel, img[@src$=.png]').ifixpng();
		 * @desc apply hack to element #panel and all images with png extensions
		 *
		 * @name ifixpng
		 */

		$.fn.ifixpng = hack.ltie7 ? function() {
	    	return this.each(function() {
				var $$ = $(this);
				// in case rewriting urls
				var base = $('base').attr('href');
				if (base) {
					// remove anything after the last '/'
					base = base.replace(/\/[^\/]+$/,'/');
				}
				if ($$.is('img') || $$.is('input')) { // hack image tags present in dom
					if ($$.attr('src')) {
						if ($$.attr('src').match(/.*\.png([?].*)?$/i)) { // make sure it is png image
							// use source tag value if set 
							var source = (base && $$.attr('src').search(/^(\/|http:)/i)) ? base + $$.attr('src') : $$.attr('src');
							// apply filter
							$$.css({filter:hack.filter(source), width:$$.width(), height:$$.height()})
							  .attr({src:$.ifixpng.getPixel()})
							  .positionFix();
						}
					}
				} else { // hack png css properties present inside css
					var image = $$.css('backgroundImage');
					if (image.match(/^url\(["']?(.*\.png([?].*)?)["']?\)$/i)) {
						image = RegExp.$1;
						image = (base && image.substring(0,1)!='/') ? base + image : image;
						$$.css({backgroundImage:'none', filter:hack.filter(image)})
						  .children().children().positionFix();
					}
				}
			});
		} : function() { return this; };

		/**
		 * Removes any png hack that may have been applied previously
		 *
		 * $('img[@src$=.png]').iunfixpng();
		 * @desc revert hack on all images with png extensions
		 *
		 * $('#panel, img[@src$=.png]').iunfixpng();
		 * @desc revert hack on element #panel and all images with png extensions
		 *
		 * @name iunfixpng
		 */

		$.fn.iunfixpng = hack.ltie7 ? function() {
	    	return this.each(function() {
				var $$ = $(this);
				var src = $$.css('filter');
				if (src.match(/src=["']?(.*\.png([?].*)?)["']?/i)) { // get img source from filter
					src = RegExp.$1;
					if ($$.is('img') || $$.is('input')) {
						$$.attr({src:src}).css({filter:''});
					} else {
						$$.css({filter:'', background:'url('+src+')'});
					}
				}
			});
		} : function() { return this; };

		/**
		 * positions selected item relatively
		 */

		$.fn.positionFix = function() {
			return this.each(function() {
				var $$ = $(this);
				var position = $$.css('position');
				if (position != 'absolute' && position != 'relative') {
					$$.css({position:'relative'});
				}
			});
		};

	})(jQuery);

$(document).ready(function() {
	$('div, span, p, a, h3, ul').each(
		function() {
			if($(this).css('background-image').indexOf('.png') != -1) {
				$(this).ifixpng();
			}
		}
	)
	$('img[@src$=.png]').ifixpng();
});


/*
 * Date Format 1.2.2
 * (c) 2007-2008 Steven Levithan <stevenlevithan.com>
 * MIT license
 * Includes enhancements by Scott Trenda <scott.trenda.net> and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat=function(){var token=/d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,timezone=/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,timezoneClip=/[^-+\dA-Z]/g,pad=function(val,len){val=String(val);len=len||2;while(val.length<len)val="0"+val;return val;};return function(date,mask,utc){var dF=dateFormat;if(arguments.length==1&&(typeof date=="string"||date instanceof String)&&!/\d/.test(date)){mask=date;date=undefined;}
date=date?new Date(date):new Date();if(isNaN(date))throw new SyntaxError("invalid date");mask=String(dF.masks[mask]||mask||dF.masks["default"]);if(mask.slice(0,4)=="UTC:"){mask=mask.slice(4);utc=true;}
var _=utc?"getUTC":"get",d=date[_+"Date"](),D=date[_+"Day"](),m=date[_+"Month"](),y=date[_+"FullYear"](),H=date[_+"Hours"](),M=date[_+"Minutes"](),s=date[_+"Seconds"](),L=date[_+"Milliseconds"](),o=utc?0:date.getTimezoneOffset(),flags={d:d,dd:pad(d),ddd:dF.i18n.dayNames[D],dddd:dF.i18n.dayNames[D+7],m:m+1,mm:pad(m+1),mmm:dF.i18n.monthNames[m],mmmm:dF.i18n.monthNames[m+12],yy:String(y).slice(2),yyyy:y,h:H%12||12,hh:pad(H%12||12),H:H,HH:pad(H),M:M,MM:pad(M),s:s,ss:pad(s),l:pad(L,3),L:pad(L>99?Math.round(L/10):L),t:H<12?"a":"p",tt:H<12?"am":"pm",T:H<12?"A":"P",TT:H<12?"AM":"PM",Z:utc?"UTC":(String(date).match(timezone)||[""]).pop().replace(timezoneClip,""),o:(o>0?"-":"+")+pad(Math.floor(Math.abs(o)/60)*100+Math.abs(o)%60,4),S:["th","st","nd","rd"][d%10>3?0:(d%100-d%10!=10)*d%10]};return mask.replace(token,function($0){return $0 in flags?flags[$0]:$0.slice(1,$0.length-1);});};}();dateFormat.masks={"default":"ddd mmm dd yyyy HH:MM:ss",shortDate:"m/d/yy",mediumDate:"mmm d, yyyy",longDate:"mmmm d, yyyy",fullDate:"dddd, mmmm d, yyyy",shortTime:"h:MM TT",mediumTime:"h:MM:ss TT",longTime:"h:MM:ss TT Z",isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:ss",isoUtcDateTime:"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"};dateFormat.i18n={dayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"]};Date.prototype.format=function(mask,utc){return dateFormat(this,mask,utc);};




/* ---------- ADD CUSTOM JAVASCRIPT BELOW THIS LINE ---------- */

try {
    /* DO NOT REMOVE - fix for IE background flicker */
    document.execCommand('BackgroundImageCache', false, true);
} 
catch (e) {
}
		
jQuery.pem = {

	//"constants" for dragging functionality
	RECIPE_DRAG_COLLECTION 	: "dragRecipeIntoCollection",
	RECIPE_DRAG_BOX 	: "dragRecipeIntoRecipeBox",
			
	init: function(type, config){
 
			
		return this.each(function(i){
			var init = $.pem[type];
			if ($.isFunction(init)) {
				init(this, config);
			}
		});
	
			
	},// end init
	
	rbMainInit: function(el,config){
		
		//initialize recipe box control panel
		// $("#rbmenu").pem('toggleStates');
		 
		// initialize simplified/expand buttons
		$(".view").pem('toggleStates');
		$(".view-bot").pem('toggleStates');
		
		// initialize		
		$("#recipe-box").pem('toggleViews');
		
		// initalize links that trigger dialog
		$.pem.initDialogLink(".dialoglink");

		// initialize dialog to create collection
		$(".interstitial").pem('interstitial',{});	
		
	}, // end recipe manage init
	
	//this sets the toolbar download CTAs in the snackbar and preinstall page
	initToolbarDownload: function(){

		//fill in all the version text
		$(".version").text("Version "+BrowserDetect.version+" "+BrowserDetect.browser);
		
		//change download link
		if( BrowserDetect.browser=="Firefox" ){

			$("a.BrowserPush").click( function(){
				window.location = "/opt/bea/install_root/pem/toolbar/snackbar.xpi"
			});

		}else if( BrowserDetect.browser=="Explorer" ){

			$("a.BrowserPush").click( function(){
				window.location = "/opt/bea/install_root/pem/toolbar/FoodToolBarSetup.msi"
			});

		}else{
			InterstitialController.config(
				{
					instance:"BrowserPush",
					trigger:"a.BrowserPush",
					url:"jsp/interstitial_browser_push.jsp",
					type:"error"
				}
			)
		}	
		
		//hide badges if not needed
		if( $('#isToolbarLoggedIn').val()=="true" ){
			$('.toolbarBadge-sm').hide();
			$('.toolbarBadge-lg').hide();
		}		
		
	},
	
	//initializes the menu for the recipe box
	rbMenuInit: function(){
		/*
		//this is to expand and collapse the menu
		$(".sys-collections li#your-sys-collections, .cust-collections li#your-custom-collections").bind(
			'click',
			function()
			{
				$(this).parent().children("li.action").css("visibility") == "visible" ?
					$(this).parent().children("li.action").slideUp('slow',function(){
						$(this).parent().children("li.action").css("visibility","hidden")
					}) :
					$(this).parent().children("li.action").slideDown('slow',function(){
						$(this).parent().children("li.action").css("visibility","visible")
					});
			}
		);

		//explicitly set the children's visibility for IE
		$(".sys-collections li#your-sys-collections").parent().children("li.action").css("visibility", "visible");
		$(".cust-collections li#your-custom-collections").parent().children("li.action").css("visibility", "visible");
		*/
		
		var IE = false;
		if(window.ActiveXObject)
		{
			IE	= true
		}
		
		var system	= ".sys-collections .collapsable"
		var custom	= ".cust-collections .collapsable"
		
		$(".sys-collections li#your-sys-collections").toggle(
			function()
			{
				IE ? $(system + " li").hide() : $(system).slideUp() ;
				
				if(IE)
				{
					if($(custom + " li").css("dislpay") == "none")
					{
						$(custom + " li").css(
							{
								display:"block"
							}
						)
						$(custom + " li").css(
							{
								display:"none"
							}
						)						
					}
					else
					{
						$(custom + " li").css(
							{
								display:"none"
							}
						)
						$(custom + " li").css(
							{
								display:"block"
							}
						)						
					}
				}
				 
			},
			function()
			{
				IE ? $(system + " li").show() : $(system).slideDown() ;
				
				if(IE)
				{
					if($(custom + " li").css("dislpay") == "none")
					{
						$(custom + " li").css(
							{
								display:"block"
							}
						)
						$(custom + " li").css(
							{
								display:"none"
							}
						)						
					}
					else
					{
						$(custom + " li").css(
							{
								display:"none"
							}
						)
						$(custom + " li").css(
							{
								display:"block"
							}
						)						
					}
				}				
			}
		)	
		
		$(".cust-collections li#your-custom-collections").toggle(
			function()
			{
				IE ? $(custom + " li").hide() : $(custom).slideUp() ; 
				
				if(IE)
				{
					if($(custom + " li").css("dislpay") == "none")
					{
						$(system + " li").css(
							{
								display:"block"
							}
						)
						$(system + " li").css(
							{
								display:"none"
							}
						)						
					}
					else
					{
						$(system + " li").css(
							{
								display:"none"
							}
						)
						$(system + " li").css(
							{
								display:"block"
							}
						)						
					}
				}				
			},
			function()
			{
				IE ? $(custom + " li").show() : $(custom).slideDown() ; 
				
				if(IE)
				{
					if($(system + " li").css("dislpay") == "none")
					{
						$(system + " li").css(
							{
								display:"block"
							}
						)
						$(system + " li").css(
							{
								display:"none"
							}
						)						
					}
					else
					{
						$(system + " li").css(
							{
								display:"none"
							}
						)
						$(system + " li").css(
							{
								display:"block"
							}
						)						
					}
				}				
			}
		)	
		
	},//end recipe box menu init	
	
	rbManagerInit: function(el,config){

         // confirm create  collections

		$(el).find("#tbl-rb-collections tbody tr").each(function(){
			
			$(this).find(".dialoglink").attr("href",$(this).find("th").html());
		});
		
         //$("#rbmenu").pem('toggleStates');
 

		 
		$(el).find("#tbl-rb-collections").tablesorter({
		 	headers: { 
                1: { sorter:'usLongDate'} 
            }		 	
		 }); 


		$(el).find("#tbl-rb-collections tbody tr").hover(
			function(){
				$(this).addClass("over");
			},
			function(){
				$(this).removeClass("over");
				
			}
		);

		 			
	},  // end rb Collections Init
	
	
	initUploadRecipe: function(el,config){
		
		var resetFacts = function(){
			var frmSections = $("#uploadRecipe > ul > li");
			var facts = $(".rrail ul > li");
			
			for (i=0; i<facts.length;i++){
				$(facts[i]).css("height",($(frmSections[i]).height()-24)+"px");
				
				if (($.browser.msie)&&(($.browser.version)==6)){
					$(facts[i]).css("height",($(frmSections[i]).height()-86)+"px");
				}
			}
		}
		
		var initTabindex = function(){
			// reset tab index 
			
			$("#rb-upload :input,:text,:checkbox,.btn-text").each(function(i){
				var $this = $(this);
				$this.attr("tabindex",i);
			})
			
		}
		
		initTabindex();
		resetFacts();

		// initialize dialog to create collection
		$(".interstitial").pem('interstitial',{});	
		
  			$("#addMoreSteps").click(function(){
				$(this).pem('cloneFields',{
						source:'.step', 
						target:'#ur-instructions'}
				),
				initTabindex();
			})

            $("#addMoreIng").click(function(){
				$(this).pem('cloneFields',{
						source:'.frm-ingredient', 
						target:'#ur-ingredients'}
				),
				initTabindex();
			})		

	},  // end initUploadRecipe
	
	/**
	 * Initializes all links that trigger interstitial. 
	 *  Links will require class="dialoglink"
	 *  Depending on which type of 
	 
	 * Interstitials are based off the ui.jquery
	 * 
	 * @name initDialogLink
	 * @param 
	 *
	 * @example 
	 * 
	 */		
	initDialogLink: function(el,config){

		$(el).each(function(i){
							
			var $this = $(this);
			var target;
			
			$(this).click(function(){

				if ($this.hasClass("link-deleteCol")){
					target = "#rb-deleteCol";
					args = {
						id: $this.attr("rel"),
						name: $this.attr("title")
					}
					$(target).find("p>em").html(args['name']);
					
				} else if ($this.hasClass("link-addRecipe")){
					target = "#rb-addRecipe";
					args = {
						id: $this.attr("rel"),
						name: $this.attr("title")
					}
					$(target).find(".close").click(function(){
						$(target).dialog("close");
						return false;
					});
					$(target).find("p>em").html(args['name']);
					
				} else if ($this.hasClass("link-renameCol")){
					target = "#rb-renameCol";
					args = {
						id: $this.attr("rel"),
						name: $this.attr("title"),
						tmpName: $this.attr("title")
					}
					$(target).find("p>em").html(args['name']);
					
				} else if ($this.hasClass("createCol")){
					target = "#rb-createCol";
					args = {
						id: $this.attr("rel"),
						name: $this.attr("title"),
						tmpName: $this.attr("title")
					}
					
					$(target).find("p>em").html(args['name']);
					
				}  else if ($this.hasClass("link-deleteRec")){
					target = "#rb-deleteRec";
					args = {
						id: $this.attr("rel"),
						name: $this.attr("title"),
						// /*Commented for integration*/colName: currentCollection,
						colName: $this.attr("collectionName")
//						colID: currentCollectionID

					}
					
					
					$(target).find("label>em").html(args['name']);
					$(target).find("label em.rb-colName").html(args['colName']);
					
				} else if ($this.hasClass("termsConditions")){
					//target = ;
					$("body").append($(document.createElement("div")).attr("id","termsConditions"));
					
					
					target = "#termsConditions";
					$(target).addClass("interstitial");
					$(target).attr("title","Terms and conditions");
					// /*Commented for integration*/$(target).load("pem-terms.html .grid-c");
					$(target).load("pem-terms.jsp .grid-c");
					//$(.grid-c").removeClass("grid-c");
					$(target).pem('interstitial',{});	
					
				}
				else if ($this.hasClass("link-deleteRecFromRB")){
					target = "#rb-deleteRecFromRB";
					args = {
						id: $this.attr("rel"),
						name: $this.attr("title"),
						colName: $this.attr("collectionName"),
						recipeUrl:$this.attr("url")						
					}
					
					
					$(target).find("label>em").html(args['name']);
					$(target).find("label em.rb-colName").html(args['colName']);
					
				}
				
			//Start-----Added By Stalin for deleting recipe from BookMark
					else if ($this.hasClass("link-deleteBookMarkRecFromRB")){
					target = "#rb-deleteBookMarkRecFromRB";
					args = {
						id: $this.attr("rel"),
						name: $this.attr("title"),
						colName: $this.attr("collectionName")						
					}
					
					
					$(target).find("label>em").html(args['name']);
					$(target).find("label em.rb-colName").html(args['colName']);
					
				}
            //End-----Added By Stalin for deleting recipe from BookMark
				$(target).dialog("open");
				
                return false;

			})

		});
	},  // end initDialogLink
	

	interstitial: function(el, config){

		var $this = $(el);
		var _timeout;
	
		var config = $.extend({
			timer:null,
			clone:null,
			autoOpen:false,
			modal: true,
			resizable: false,
			draggable:false,
			width:425,
			overlay: { backgroundColor: '#333', opacity: 0.1 },
			// /*Commented for integration - This is the one added in the new JS*/overlay: { backgroundColor: 'white', opacity: 0.1 },
			buttons: null
		}, config);
	
		config["open"] = function(ev, ui) {
		
			$(".ui-dialog-overlay").fadeTo("1","0.5",function(){
				$(".ui-dialog").fadeTo("1","1");
			});
	
			resetHeight(ev,ui,$(this));
			
			if (config["timer"] != null){
			
				_timeout = setTimeout(function(){
					$(el).dialog('close')
				}, config["timer"]);
				
			}
        };

			
		
		if ($this.hasClass("dialog-success")){
			// if confirmation module
			
			config["timer"] = ($this.hasClass("addRecipe"))? null : ($this.hasClass("createCol"))?7000:5000;
			
			if ($this.hasClass("addRecipe")){
				config["buttons"] = {            
					
				};
				
			}else{
				config["buttons"] = {
					"Okay": function(){
						closeDialog($this);
					}
				}
			}
			
		}
		else {
			
			var dialogid = $this.attr("id");
			switch (dialogid){
				case "rb-deleteCol":
					// delete collection	
					config["buttons"] = {
		                    "Delete":  function(ev,ui){
		                        deleteCollection(ev,ui,$this)
		                    },
		                    "Cancel": function(){
		                        closeDialog($this)
		                    }
		            };
				break;
				
				case "rb-renameCol":
				case "rb-renameCol-error":
				case "rb-renameCol-error-blank":
					// rename collection	
					config["buttons"] = {
		                    "Rename":  function(ev,ui){
		                        renameCollection(ev,ui,$this)
		                    },
		                    "Cancel": function(){
		                        closeDialog($this)
		                    }
		            };
				break;

				case "rb-createCol":
				case "rb-createCol-error":
				case "rb-createCol-error-blank":
					// rename collection	
					config["buttons"] = {
		                    "Create":  function(ev,ui){
		                        createCollection(ev,ui,$this)
		                    },
		                    "Cancel": function(){
		                        closeDialog($this)
		                    }
		            };
				break;

				case "rb-deleteRec":
					// delete recipe from RB or Collection
					config["buttons"] = {
		                    "Delete":  function(ev,ui){
		                        deleteRecipe(ev,ui,$this)
		                    },
		                    "Cancel": function(){
		                        closeDialog($this)
		                    }
		            };
				break;
				case "rb-deleteRecFromRB":
					// delete recipe from RB
					config["buttons"] = {
		                    "Delete":  function(ev,ui){
		                        deleteRecipeFromRB(ev,ui,$this)
		                    },
		                    "Cancel": function(){
		                        closeDialog($this)
		                    }
		            };
				break;	
				
				case "rb-deleteBookMarkRecFromRB":
					// delete recipe from BookMark
					config["buttons"] = {
		                    "Delete":  function(ev,ui){
		                        deleteBookMarkRecipeFromRB(ev,ui,$this)
		                    },
		                    "Cancel": function(){
		                        closeDialog($this)
		                    }
		            };
				break;								
				default : 
				
				break;
			}
		}
		
		
		var closeDialog = function(el){

			$(".ui-dialog").fadeOut("fast");
		
			$(el).dialog("close");
			clearTimeout(_timeout);
		} // end close dialog
		
		var resetHeight = function(ev,ui,el){
			var target = $(el);
			    // reset dialog height
				var  height = 20;
				height += target.parent(".ui-dialog-container").outerHeight();
				height += target.parent(".ui-dialog-container").siblings(".ui-dialog-buttonpane").outerHeight();
                target.data("height.dialog", height);
				
		}  // end reset Height
		
		var renameCollection = function(ev,ui,el){
			var newName = $(el).find("input:text").val();
				// collect details
			//Added By stalin for Renaming start
				var _args = {
					newCollectionName:newName,
					oldCollectionName:args["name"],
					collectionID:args["id"],
					collectionBox:$(el).find("input:hidden").val()
				}	

			// close current dialog
			closeDialog(el);
				
			// set url
             var _url	= "manageCollection.do"
			$.ajax(
				{
					url:_url,
					cache:false,
					data:_args,
					dataType:"json",
					type:"POST",
					success:function(json){
						var _success = json.response.success;
													
						// success
						if (_success=='true'){

							//open confirmation
							$("#rb-renameCol-success").find("p").html("<em>"+ _args["oldCollectionName"] +"</em> collection is now called <em>"+ newName+"</em>.");
							$("#rb-renameCol-success").dialog("open");	

							//rename collection on page
							$("tr[id='"+args.id+"'] th").html(newName);
							$("tr[id='"+args.id+"'] .dialoglink").attr("title",newName);
							$("tr[id='"+args.id+"'] .dialoglink").attr("href",newName);
							$("#rbmenu li[id='rbmenu-"+args.id+"'] em").html(newName);
							
							
						
						}else if(_success=='blank'){
						 
						    $("#rb-renameCol-error-blank").find("p>em").html(newName);
							$("#rb-renameCol-error-blank").dialog("open");
						
						}
						
						
						else{
							// error
							$("#rb-renameCol-error").find("p>em").html(newName);
							$("#rb-renameCol-error").dialog("open");			
						
						}						
					},
					error:function(json) {						
						window.location = "exceptionController.do";
					}
				}
			)
//Added By stalin for Renaming Ends
					
		} // end rename collection

		var createCollection = function(ev,ui,el){
			var newName		= $(el).find("input:text").val();

			// close current dialog
			closeDialog(el);
			
			/*
				------------------------------------------------------
					submit the collection name
				------------------------------------------------------				
			*/
			
				// collect details
				var _args		= {
					collectionName:newName,
					collectionBox:$(el).find("input:hidden").val()
				}	
				
				// set url
				var _url	= "manageCollection.do"
				$.ajax(
					{
						url:_url,
						cache:false,
						data:_args,
						dataType:"json",
						type:"POST",
						success:function(json){
							var _id		= json.response.id;
							var _href	= json.response.href;
							var _date	= json.response.date;
							var _success = json.response.success;
														
							// success
							if (_success=='true'){
								// on success it creates the row under the collections table
								//open confirmation
								$("#rb-createCol-confirm").find("p>em").html(newName);
								$("#rb-createCol-confirm").dialog("open");	

								//add collection to page

								// add to collections table
								// var today = new Date()
								//today = today.getMonth()+1+"/"+today.getDate()+"/"+(today.getYear() + 1900)
								 var today = new Date()
								today = (today.getYear() + 1900)+"-"+(today.getMonth()+1)+"-"+today.getDate()

								var newRow;
								// clone an existing row
								newRow = $("#tbl-rb-collections tbody tr:first").clone();
								if(newRow.length == 0){
									newRow = '<tr id="'+ _id +'"><th>' + newName 
									+'</th><td>'+ _date +'</td><td>0</td><td><ul><li><a href="#" class="dialoglink link-renameCol" rel="'+ _id 
									+'" title="'+ newName +'" >Rename</a></li><li class="last"><a href="#" class="dialoglink link-deleteCol" rel="'+ _id 
									+'" title="'+ newName +'" >Remove</a></li></ul></td></tr>';
								}
								$(newRow).attr("id",_id);
								$(newRow).find("th").html(newName);
								$(newRow).find("td:nth-child(2)").html(_date);
								$(newRow).find("td:nth-child(3)").html("0");
								$(newRow).find("td:nth-child(4) a").attr("title",newName);
								$(newRow).find("td:nth-child(4) a").attr("rel",_id);  // need to add ID here
								$(newRow).find("td:nth-child(4) a").attr("href",_href);

								// bind click events to Rename and remove
								 $(newRow).find("td:nth-child(4) a").pem("initDialogLink");

								// add row to the table
								$("#tbl-rb-collections tbody").append(newRow);

								// add to RBmenu	
								var newMenuLi = $("#rbmenu li.added").clone(true);
								$(newMenuLi).attr("id", "rbmenu-"+_id);  // add ID
								$(newMenuLi).removeClass().addClass("custom")
								$(newMenuLi).find("a span em").html(newName).append(" <b>(0)</b>");
								$(newMenuLi).find("a").attr("href", _href);  // add custom URl
								$("#rbmenu ul>li#rbmenu-create").before(newMenuLi);
								

								// drag and drop
								// call drag and drop again
								$().pem(
									"RecipeDragger",
									{
										source:["#rb-table-clone tbody", "#rb-table tbody"],
										// /*Commented for integration*/target:"#rbmenu li.action",
										target:"#rbmenu li.custom",
										item:"tr",
										resize:{
											available:false
										}
									}
								)	
							}else if(_success=='blank'){
							     $("#rb-createCol-error-blank").find("p>em").html(newName);
								 $("#rb-createCol-error-blank").dialog("open");	
							
							}
							
							 else {
							
								// error
								$("#rb-createCol-error").find("p>em").html(newName);
								$("#rb-createCol-error").dialog("open");	
							}													
						},
						error:function(json) {	
							window.location = "exceptionController.do";
						}						
					}
				)
					
		} // end create Collection
		
		var deleteCollection = function(ev,ui,el){

			// collect details
			var _args		= {
								collectionBox:$(el).find("input:hidden").val(),
				collectionName:args["name"],
				collectionID:args["id"]
			}	

 			// close current dialog
			closeDialog(el);
// set url
              var _url	= "manageCollection.do"
	
			// set url
			// /*Commented for integration*/var _url	= "data-rb-main.html"
			$.ajax(
				{
					url:_url,
					cache:false,
					data:_args,
					dataType:"json",
					type:"POST",
					success:function(json){
						var _success = json.response.success;
													
						// success
						if (_success=='true'){

							//remove collection from page
							$("tr[id='"+args.id+"']").hide();
							$("#rbmenu li[id='rbmenu-"+args.id+"']").hide();
					
							//open confirmation
							$("#rb-deleteCol-success").find("p>em").html(args['name']);
							$("#rb-deleteCol-success").dialog("open");	
		
						

						} else {
						
							// error
						}													
					},
					error:function(json) {						
						window.location = "exceptionController.do";
					}					
				}
			)

		} // end delete Collection
		
		var addToRB = function(){
		} // end add to RB
		//Start delete Recipe
		var deleteRecipe = function(ev,ui,el){
			var deleteAll = $(el).find("input:checkbox")[0].checked;  
			var deleteCol = $(el).find("input:checkbox")[1].checked;  						
									

			// collect details
			var _args		= {
				collectionName:args["colName"],
				collectionID:args["colID"],
				recipeName:args["name"],
				recipeID:args["id"],
				deleteAll:deleteAll,
				deleteCol:deleteCol
			}				
			
			// close current dialog
			closeDialog(el);
			
			var _url = "deleteRecipe.do";

			$.ajax(
				{
					url:_url,
					cache:false,
					data:_args,
					dataType:"json",
					type:"POST",
					success:function(json){
						var _success = json.response.success;
											
						// success
						if (_success=='true'){

							if (deleteAll){
								$("#rb-deleteRec-confirm").find("p").html(args['name']+" has been permanently removed from your recipe box.");
							}else if (deleteCol){
								$("#rb-deleteRec-confirm").find("p").html(args['name']+" has been removed from your "+args['colName']+" collection.");
							}
							
							if (deleteAll || deleteCol){
								$("#rb-deleteRec-confirm").dialog("open");
									
								//if(document.location.href.indexOf("rb-main")>-1){
								
									$("#rb-table tr#recipe_"+args["id"]+",#rb-table-clone tr#recipe_"+args["id"]).hide();
									
								//}
								window.location=json.response.url;
							}
						

						} else {
						
							// error
						}													
					},
					error:function(json) {						
						window.location = "exceptionController.do";
					}					
				}
			)
			
		} // end delete Recipe
		
//Start delete BookMarkRecipe 
		var deleteBookMarkRecipeFromRB = function(ev,ui,el){
			var deleteAll = $(el).find("input:checkbox")[0].checked;  
			var deleteCol = $(el).find("input:checkbox")[1].checked;  						
									

			// collect details
			var _args		= {
				collectionName:args["colName"],
				collectionID:args["colID"],
				recipeName:args["name"],
				recipeUrl:args["id"],
				deleteAll:deleteAll,
				deleteCol:deleteCol
			}				
			
			// close current dialog
			closeDialog(el);
			
			var _url = "deleteRecipe.do";

			$.ajax(
				{
					url:_url,
					cache:false,
					data:_args,
					dataType:"json",
					type:"POST",
					success:function(json){
						var _success = json.response.success;
											
						// success
						if (_success=='true'){

							if (deleteAll){
								$("#rb-deleteRec-confirm").find("p").html(args['name']+" has been permanently removed from your recipe box.");
							}else if (deleteCol){
								$("#rb-deleteRec-confirm").find("p").html(args['name']+" has been removed from your "+args['colName']+" collection.");
							}
							
							if (deleteAll || deleteCol){
								$("#rb-deleteRec-confirm").dialog("open");
									
								//if(document.location.href.indexOf("rb-main")>-1){
								
									$("#rb-table tr#recipe_"+args["id"]+",#rb-table-clone tr#recipe_"+args["id"]).hide();
									
								//}
								window.location=json.response.url;
							}
						

						} else {
						
							// error
						}													
					},
					error:function(json) {
						window.location = "exceptionController.do";
					}					
				}
			)
			
		} // end delete BookmarkRecipe		
		
		
		
		
		//Strt delete Recipe from Recipe Box only
		var deleteRecipeFromRB = function(ev,ui,el){
		    	
			var onlyRB	  =$(el).find("input:hidden").val();					

			// collect details
			var _args		= {
				collectionName:args["colName"],
				collectionID:args["colID"],
				recipeName:args["name"],
				recipeID:args["id"],
				recipeUrl:args["recipeUrl"],
				onlyRB:onlyRB
			}				
			
			// close current dialog
			closeDialog(el);
			
			var _url = "deleteRecipe.do";
			
			$.ajax(
				{
					url:_url,
					cache:false,
					data:_args,
					dataType:"json",
					type:"POST",
					success:function(json){
						var _success = json.response.success;
													
						// success
						if (_success=='true'){

							if (onlyRB=='true'){
								$("#rb-deleteRec-confirm").find("p").html(args['name']+" has been permanently removed from your recipe box.");
							}
							
							if (onlyRB=='true'){
								$("#rb-deleteRec-confirm").dialog("open");
									
//								if(document.location.href.indexOf("rb-main")>-1){
									$("#rb-table tr#recipe_"+args["id"]+",#rb-table-clone tr#recipe_"+args["id"]).hide();
									
//								}
							}
						
                         window.location=json.response.url;
						} else {
						
							// error
						}													
					},
					error:function(json) {
						window.location = "exceptionController.do";
					}					
				}
			)
			
		}

	//End delete Recipe from Recipe Box only
	
		// INITIALIZE THE DIALOG
		$(el).dialog(config);


	}, // end interstitial
	
	initFacetMenu: function(el, config){
		config = $.extend({
			
		}, config);

		var animSpeed = 1500;
		var pause = 2500;

		var hd = $(el).find(".hd"); // header div container 
		var bd = $(el).find(".bd"); // body div container
		var ft = $(el).find(".ft"); // footer div container
		
		var sourcesUL = $(el).find("li#sources > ul");  // ul for sources to be displayed in default
		var parentUL = $(el).find("ul:first");
		var categories = $(parentUL).find("h3");
		
		//$("#"+el.id).find('li:eq(0)').addClass('selected');
		$(categories).each(function(){
			$(this).click(function(){
				//hide the old scollbar
				$(bd).find("li.openCat .jScrollPaneContainer").hide();
				$(bd).find("li.openCat").removeClass('openCat');
				$(this).parents('li').addClass('openCat').find(".panel").slideDown(); 
				//When the user selects a dimension, we'll save that in the hidden variable, to have it selected when the page refreshes.
				document.getElementById("dimensionName").value = $(this).text();	
				
				//init scroll for facet only if first time open
				if ($(bd).find("li.openCat .jScrollPaneContainer").length == 0){
					$(bd).find("li.openCat .panel").jScrollPane({showArrows:true, scrollbarWidth: 8, arrowSize: 2, dragMinHeight: 20});
				}
				else{
					$(bd).find("li.openCat .jScrollPaneContainer").show();
				}
				$(bd).find("li.openCat .jScrollPaneContainer").css("margin","5px 0");
			});	


			 // Recipes from dimension open on default
			 if ((document.getElementById("dimensionName").value=="") && ($(this).html() == "Recipes from")){
               $(this).parents('li').addClass('openCat'); 
			   //show the scroll container
				//init scroll for recent history
				$(bd).find("li.openCat .panel").jScrollPane({showArrows:true, scrollbarWidth: 8, arrowSize: 2, dragMinHeight: 20});
				$(bd).find("li.openCat .jScrollPaneContainer").css("margin","5px 0");

             } 
			 if (document.getElementById("dimensionName").value == $(this).html()){
				//init scroll for recent history
				$(bd).find("li.openCat .panel").jScrollPane({showArrows:true, scrollbarWidth: 8, arrowSize: 2, dragMinHeight: 20});
				$(bd).find("li.openCat .jScrollPaneContainer").css("margin","5px 0");

             } 				
			// Recipes from dimension open on default
			//if ($(this).html() == "Recipes from"){
			//COMMENTING THIS DEV LINE FOR INTEGRATION//if ($(this).html() == "Recipes from"){
			//$(this).parents('li').addClass('openCat');
			//}
			
			
		});
		
		
		//$(el).css("height",$(ft).outerHeight() +  $(bd).outerHeight() + $(hd).height());
		
		
		$(bd).find(".panel li").each(function(){
	
			var $this = $(this);
			
			$this.hover(function(){
				$this.addClass("liover");
			},
			function(){
				$this.removeClass("liover");
			});
			
			$this.mousedown(function(){
				if($this.hasClass('liover')){
					$this.addClass("lipress").removeClass("liover");
				}
			}).mouseup(function(){
			
				$this.removeClass("lipress");
			
			}).click(function(){
				//click event for each facet
				//$this.removeClass().addClass("selected");
				var $parentUL = $this.parent();
				var $parentLI = $parentUL.find("li"); // all sibling li
				
				//$this.removeClass("off").addClass("selected");
				
				 if (($parentUL.find("li:not('.more')").length)==($parentUL.find("li.off:not('.more')").length)){
					// check if all facets are deselected, if so return facets to neutral state
					$parentUL.find("li:not('.more')").removeClass().find("a").removeClass();
				} 
				
				//return false;
			});
		
		});
	
		$(el).find(".reset-facets").click(function(){
			// reset ALL facets to the neutral state
			$(el).find("li:not('.openCat'):not('.last')").removeClass();
		
		})

		

	},  // end init facet
	
	searchResults: function(el, config){
		// all search  results javascript goes here

		// find last item in result list
		$(el).find(".result-list").children("li:last").addClass("last");

		// apply hover event to each result item
		$(el).find(".result-detail").each(function(){
			
			$(this).hover(function(){
				$(this).addClass("result-detail_over");
				
			},function(){
				
				$(this).removeClass("result-detail_over");
				
			})

		});
		
		// reposition drop box for IE6
		function  positionDropBox()
		{
			/*
			$("#search-results-cn").css(
				{
					height:$(window).height()-$("#recipe-drop-box").outerHeight()
				}
			)
			*/	
			
			var yPos	= $(window).height() - $("#recipe-drop-box").outerHeight();
			if(document.documentElement.scrollTop != 0)
			{
				yPos += document.documentElement.scrollTop
			}			
			
			$("#recipe-drop-box").css(
				{
					top:yPos
				}
			)
			
			//window.status = yPos
			
		}
		
		if (($.browser.msie)&&(($.browser.version)==6))
		{
			$(window).bind('resize', positionDropBox);
			$(window).scroll(
				function()
				{
					positionDropBox();
				}
			)			
			positionDropBox();
		}

		$(".pill").animate({opacity: 1.0}, 3000).fadeOut(800);
		$(".refined").animate({opacity: 1.0}, 4000).fadeIn(800);
		
		// applying snapshot to 3rd party logo
		$("div.partnerlogo>a.external>img.logo").each(function(){
			var parentDiv = $(this).parents("div.partnerlogo");
			// adjust position of snapshot overlay
			// required - be sure to set the height and width of the img and logo withing the markup
			$(parentDiv).find("div.snapshot").css("left",$(this).outerWidth()-61);
			$(parentDiv).find("div.snapshot").css("top",$(this).position()["top"]+14);
		
			// display snapshot for hover event applied to 3rd party logo
			$(this).hover(
				function(){
					$(parentDiv).find("div.snapshot").toggle("fade");
				}, 
				function(){
					
					$snapshot = $(parentDiv).find("div.snapshot");
					

					if ($snapshot.is(':visible')) {
					
						$snapshot.hover(function(){
							$snapshot.show();
						}, function(){
							$snapshot.hide();
						
						});
						$snapshot.hide();
					}
					
			});
		});
		
		// initalize links that trigger dialog
		$.pem.initDialogLink(".dialoglink");

		// initialize dialog to create collection
		$(".interstitial").pem('interstitial',{timer:0});

		$(".btn-addto, #sbAddBoxLink").click(function(){

			recipe_id = $(this).parents(".result-detail").attr("rel");			
			var title = $(this).parents(".result-detail").attr("title");
			var recipeURL = $(this).parents(".result-detail").attr("url");
			var recipeSource = $(this).parents(".result-detail").attr("source");
			
			var triggerID = $(this).attr("id");
			
			if( recipe_id == null ){	recipe_id = $(this).attr("rel");}
			if( title == null ){	title = $(this).attr("title");}
			if(recipeSource == null){ recipeSource = $(this).attr("source");}
			if(recipeURL == null){ recipeURL = $(this).attr("url");}

			$("#rb-confirm").dialog("open");
			$("#rb-confirm").data("height.dialog", "225px");

			var args	=	{
				recipe_id: recipe_id,
				title: title,
				recipeSource: recipeSource,
				recipeURL: recipeURL,
				action:"addToRecipeBox"
			}


			$.ajax({
				url: "addRecipe.do",
				cache: false,
				data: args,
				dataType: "json",
				type:"POST", 
				success:function(json){
					var _success = json.response.success;	
					
					switch(_success){
						case "success" :
							var url = "jsp/interstitial_add_recipe_confirm.jsp";
							
							if( triggerID=="sbAddBoxLink" ){
								url = "jsp/interstitial_third_party_recipe.jsp";
							}
							else
							{
								setTimeout( 
								function(){
									$(InterstitialController.interstitial.lightbox).fadeOut("fast");
								},
								5000
								)
							}//end of else block							
							// load interstitial
							$.ajax({
									url:url+"?title="+title,
									cache: false,
									data:{},
									dataType:"text",
									type:"GET",
									success:function(html)
									{
										InterstitialController.clearContent();
										InterstitialController.display(html)								
									}
							})							
							break;

						case "error" :
							url = "jsp/interstitial_recipe_already_exists.jsp";
							// load interstitial
							$.ajax({
								url:url,
								cache: false,
								data:{},
								dataType:"text",
								type:"GET",
								success:function(html)
								{
									InterstitialController.clearContent();
									InterstitialController.display(html)								
								}
							})

							break;
						case "critical" :
							var copy = {
								title:json.response.title,
								message:json.response.message
							}

							InterstitialController.clearContent();
							InterstitialController.error(copy);
							break;
					}
				},
				error:function(json) {						
					window.location = "exceptionController.do";
				}						
			})

			return false;			
		});
		
		
		// more ingredients
		$(el).find(".ingredients > ul").each(function(){
				$(this).children(":gt(1):not('.more)").hide();
		})
		
	
		$(el).find(".ingredients li.more").toggle(function(){
				$(this).parents("ul:first").children(":gt(1):not('.more)").slideDown("slow");
				//Commented this DEV work for Integration$(this).parents("ul:first").children(":gt(1):not('.more)").show();
				$(this).removeClass("more").addClass("less");
				var moreText =  $(this).html();

				$(this).html(moreText.replace(/More/,"Less"));
				
				
			},function(){
				
				$(this).removeClass("less").addClass("more");
				$(this).parents("ul:first").children(":gt(1):not('.more)").slideUp("slow");
				//Commented DEV work for Integration$(this).parents("ul:first").children(":gt(1):not('.more)").hide();
				var moreText =  $(this).html();
				$(this).html(moreText.replace(/Less/,"More"));
				
			});
		
		
		
		
		
	},  //end search results
	
	toggleStates: function(el, config){
		// on and off states
		// recipe box menu
		$(el).find('li:not(".action")').each(
			function(i)
			{
				var $this = $(this);
				$this.click(
					function()
					{
						$(el).find("li.selected").removeClass("selected");
						$this.addClass("selected");
						
						return false;
					}
				);
			}
		);
		
		
	}, //end toggleStates button
	
	toggleViews: function(el, config){				
		// simplified and expanded page views
		$(el).find('.view li, .view-bot li').each(
			function(i)
			{
				var $this = $(this);
				$this.click(
					function()
					{			
						//remove the selected classes from top and bottom
						$(".view").find("li a.selected").removeClass("selected");	
						$(".view-bot").find("li a.selected").removeClass("selected");	

						//figure out what to show/hide
						var parent = $(this).parent().parent()
						var otherToggle;
						if($(parent).attr("class") == "view")
						{ 				
							otherToggle = ".view-bot";
						}
						else{
							otherToggle = ".view";
						}
						
						if($(this).hasClass("simplified")){
							//if we're going to simplified view, make sure we collapse ingredients
							$(".moreIngredients span").each(function(i){

								if( $(this).text()==RBUpdater.LESS_INGRED_TEXT ){	
									var ingredElem = $(this).parents("div").children(".ingredients");

									$(this).parent("div").children("img").attr({"src":"images/icn-more-ingredients.gif"});
									ingredElem.css("height", "" );
									$(this).parent("div").children("span").html(RBUpdater.MORE_INGRED_TEXT);
									
									$(this).parents("tr").css("height", "" );
								}
										
							})
							
							//only show simplfied data
							$("#rb-table tbody tr").children("td").children().hide();
							$("#rb-table tbody tr .simpleData").show();
							$("#rb-table tbody tr").children("td").children(".moreData").parent().append("<span class=\"moreDataEllipse\">...</span>");
							
							$(el).find("#recipebox .name-w, #recipebox .name-e, #recipebox .ingredients, #recipebox .moreIngredients").hide();

							//make heights of all tr's auto for simplified view
							$("#rb-table-clone tbody tr").css("height", "");
							$("#rb-table tbody tr").css("height", "");
						
							$(this).find("a").addClass("selected");
							$(otherToggle + " li.simplified a").addClass("selected");						
						}
						else{
							//show all data
							$("#rb-table tbody tr").children("td").children().show();
							$("#rb-table tbody tr").children("td").children(".moreDataEllipse").remove();
							
							$(el).find("#recipebox .name-w, #recipebox .name-e, #recipebox .ingredients, #recipebox .moreIngredients").show();
							$(this).find("a").addClass("selected");
							$(otherToggle + " li.expanded a").addClass("selected");
						}

						Table._fixRowHeight()
						if( Table._current==0 && BrowserDetect.browser=="Firefox" && BrowserDetect.version=="2" ){ Table.pagination(-1) }					
						Table._pageHeight();
										
					}					
				);
			}
		);
		// first time run
		$(".view .simplified").trigger("click")
	}, // end toggleStates page view
	
	/**
	 * Function called to add the tags to generate the dropcap for the first letter of the first paragraph.
	 *
	 * @name dropCap
	 * @param Pass in the parent DIV
	 *
	 * @example $(".grid-home").pem('dropCap');
	 * 
	 */	
	dropCap: function(el, config){
	
		var firstPar = $(el).find('p')[0];
 	 	if (!firstPar){
			return false;
		};
		//test to make sure the first character is alphanumeric, if not, don't do dropcap
		var regEx = /\w/;
		
  		var text = $.trim(firstPar.firstChild.nodeValue);
		var firstLetter = text.substr(0,1);
		var isValidDropCapChar = regEx.test(firstLetter);
		if ( isValidDropCapChar ) {
			firstPar.firstChild.nodeValue = text.slice(1);
			$(el).find('p:first').prepend("<span class='dropcap'>"+firstLetter+"</span>");
		};
	}, // end dropCap
	
	
	/*
		abstracted drag / drop
		source	= draggables container
		target	= droppable target
		item	= draggable item
	*/
	RecipeDragger: function (el, config)
	{
		// object 
		var source		= config.source;
		var target		= config.target;
		var item 		= config.item;
		var resize		= config.resize;
		var instruction	= config.instruction;
		var title		= "";
		var dragFunc		= config.dragFunction;
	
		// fix recipe box size
		if(resize.available)
		{			
			// initial positioning and roll up
			/*
			$(target).css(
				{
					bottom:"-87px"
				}
			);
			$(target).animate(
				{
					bottom:0
				},
				{
					duration:1500
				}
			)
			*/
			
			// get image, resize, move
			var image	= $(config.resize.image);


			// var for scaling
			var xD		= $('body').width()/2
			var delta	= xD - (image.width()/2)


			// image base properties
			//image.width(51);			
			//image.height(69);
			image.css(
				{
					//top:"5px",
					left:(($('body').width()/2) - (image.width()/2))
				}
			)

			// get plus hide and center
			var instruction	= $(config.resize.instruction);
			instruction.css(
				{
					left:(($('body').width()/2) - (instruction.width()/2) - 15)
				}
			)
						
			// get plus hide and center
			var plus	= $(config.resize.plus);
			plus.hide();			
			plus.css(
				{
					left:(delta + (plus.width()/2) + 6),
					top: 24
				}
			)
			
			// get success hide and center
			var success	= $(config.resize.success);
			success.hide();
			success.css(
				{
					left:(($('body').width()/2) - (success.width()/2))
				}
			)
			
			// get error hide and center
			var error	= $(config.resize.error);
			error.hide();
			error.css(
				{
					left:(($('body').width()/2) - (error.width()/2))
				}
			)			
			
		}
		
		// draggable
		for(prop in source)
		{
			// draggable
			$(source[prop]).find(item).draggable
			(
				{
					revert:false,
					cursorAt:($('#search-results').length > 0) ? [19,54] : [0,0],
					helper:function()
					{				
						//Set a flag to determine if this is the search results page or not
						var isSearchResults = false;
						
						if ($('#search-results').length > 0) {
							isSearchResults = true;
						}
						
						var id		= !$(this).attr("rel") ? $(this).find("div:contains('rel')").attr("rel") : $(this).attr("rel") ;
						var title	= $(this).find("h3").length != 0 ? $(this).find("h3").text() : $(this).find("h2 span").text();

						var recipeURL = !$(this).attr("url") ? $(this).find("div:contains('url')").attr("url") : $(this).attr("url") ;
						var recipeSource = !$(this).attr("source") ? $(this).find("div:contains('source')").attr("source") : $(this).attr("source") ;
				
						var dragBox	= $(document.createElement("div"));								
						
						//The drag visual is different on the search results page (represented as an image) than on other pages (represented by the recipe's title)
						if (isSearchResults) {
							
							var img = $(this).find(".result-w img");
							var imgSizeString = "";
							
							//Determine the new size for the image
							if (img.height() > img.width()) {
								//Size based on width becasue the width is the smaller value, and center the image vertically
								imgSizeString = ' width="42" style="position: relative; top: '+((42 - ((img.height() * 42) / img.width())) / 2)+'px;" ';
							}
							else if (img.width() > img.height()) {
								//Size based on height becasue the height is the smaller value, and center the image horizontally
								imgSizeString = ' height="42" style="position: relative; left: '+((42 - ((img.width() * 42) / img.height())) / 2)+'px;" ';
							}
							else {
								//Size both, because the image is a square. Don't worry about positioning.
								imgSizeString = ' width="42" height="42" ';
							}
							
							//dragBox.html(title)
							if (img.length) {
								dragBox.html('<img src="'+$(this).find(".result-w img").attr("src")+'" '+imgSizeString+'/>');
								dragBox.css(
									{
										"width": "42px",
										"height": "42px",
										"border": "2px solid #FFF",
										"background": "#dedede",
										"overflow": "hidden",
										"z-index": "999"
									}
								);
							}
							else {
								dragBox.html(title);
							}
						}
						else {
							dragBox.html(title);
						}
						
						dragBox.attr(
							{
								id:"recipe-drag-box",
								value:id,
								title:title,
								recipeURL:recipeURL,
								recipeSource:recipeSource,
								"z-index":"999"
							}
						);
						return dragBox.appendTo("body")[0];
					}
				}
			)
		}
		
		// droppable
		$(target).droppable(
			{
				accept: function(draggable) {
					return $(draggable).children();
				},
				tolerance:"pointer",
				over: function(ev, ui)
				{
					if(resize.available)
					{
						// scale image
						image.animate(
							{
								top:"0"
							},
							{
								duration:"fast"
							}
						)
						$("#recipe-drop-box").animate(
							{
								height: 55
							}
						)

						// hide instructions
						instruction.fadeOut("fast");

						// show plus	
						plus.fadeIn("fast");
				
					}
					else{
						$("#recipe-drag-box").append("<img class=\"drag-plus\" src=\"images/drag-plus.png\" />");
					}
					
				},
				out: function(ev, ui)
				{
					if(resize.available)
					{
						// scale image					
						image.animate(
							{
								top:"10"
							},
							{
								duration:"fast"
							}
						)
						$("#recipe-drop-box").animate(
							{
								height: 26
							}
						)
						
					
						// show instructions
						instruction.fadeIn("fast");
					
						// hide plus
						plus.fadeOut("fast");						
					}
					else{
						$("#recipe-drag-box .drag-plus").remove();
					}								
				},
				drop: function(ev, ui)
				{				
					// send data
					var _id		= $("#recipe-drag-box").attr("value");					
					var _bucket	= $(this).attr("id");
					var _cId	= $(this).attr("rel");
					
					var title = $("#recipe-drag-box").attr("title");
					var recipeURL = $("#recipe-drag-box").attr("recipeURL");
					var recipeSource = $("#recipe-drag-box").attr("recipeSource");
					
					var args	= {
						recipe_id: _id,
						bucket: _bucket,
						title:title, 
						recipeSource:recipeSource, 
						recipeURL:recipeURL,
						collectionID : _cId,
						action : dragFunc
					}
									
					$.ajax( 
						{
							url: "addRecipe.do",
							cache: false,
							data: args,
							dataType: "json",
							type:"POST", 
							success:function(json){
								switch(json.response.success){
									case "success":
										if(resize.available){
											// hide plus
											plus.fadeOut("fast");

											// show added and fade
											success.fadeIn("fast",function(){	$.pem.animateOnDrop(image, success, instruction)  })
										}
										
										//only update page if we're adding to a collection
										if(dragFunc==jQuery.pem.RECIPE_DRAG_COLLECTION){
											var post = {"id":_id};
											RBUpdater.updatePage(post, RBUpdater.ADD_TO_COLLECTION_UPDATE, json);
										}
										break;
									case "error":
										if(resize.available){
											// hide plus
											plus.fadeOut("fast");

											// show added and fade
											error.fadeIn("fast",function(){	$.pem.animateOnDrop(image, error, instruction)  })
										}									
									
										break;
									case "critical":
										var copy = {
											title:json.response.title,
											message:json.response.message
										}

										InterstitialController.clearContent();
										InterstitialController.error(copy);
										break;
								}
							},
							error:function(json) {								
								window.location = "exceptionController.do";
							}							
						}
					);												
				}//end of drop function
			}
		)
	}, // end RecipeDragger page view
	
	
	animateOnDrop: function( image, success, instruction){
		// scale image
		image.animate(
			{
				top:"0"
			},
			{
				duration:"fast"
			}								
		)
		success.animate(
			{
				opacity: 1.0
			},
			3000,
			function()
			{
				success.fadeOut("fast")
			}
		)
		image.animate(
			{
				top: 0
			},
			3000,
			function()
			{
				image.animate(
					{
						top:"10"
					},
					{
						duration:"fast"
					}
				)
			}
		)
		$("#recipe-drop-box").animate(
			{
				height: 55
			},
			3000,
			function()
			{
				$("#recipe-drop-box").animate(
					{
						height: 26
					},
					{
						duration:"fast"
					}
				)
			}
		)
		instruction.animate(
			{
				opacity: 1.0
			},
			3000,
			function()
			{
				instruction.fadeIn("fast")
			}
		)																		
	},
	
	
	faqActions: function(el, config)
	{
		var _que	= config.que;
		var _ans	= config.ans;
		var _on		= config.on;
		var _off	= config.off;
		
		// hide all answers
		$(_ans).hide();
		
		// add style to question		
		$(_que).parent().addClass(_off);
		
		$(_que).bind(
			'click',
			function()
			{ 
				if($(this).parent().hasClass(_off))
				{
					$(this).parent().removeClass(_off);
					$(this).parent().find(_ans).each(
					function(index,item){
						$(item).show();					
					}
					);
					$(this).parent().addClass(_on);
				}
				else
				{
					$(this).parent().removeClass(_on);
					$(this).parent().addClass(_off);
					$(this).parent().find(_ans).each(
					function(index,item){
					$(item).hide();					
					}
					);
				}
				
				//set vertical divider line height
				$(".sponsors").height($(".grid-c").height()-90);
				
				return false;
			}
		)

	},
	
	/*
		clone fields for upload recipe page
	*/
	cloneFields: function(el, config)
	{
		this._count = !this._count ? 0 : this._count
		this._count		+= 5;

		var _source		= $(config.source)[$(config.source).length - 1];
		_source			= $(_source).parent().clone(); //.html();
		
		$(_source).find(":input").each(function(){
			$(this).val("");									
		});		

		var _target		= $(config.target)
		var _ul			= $(config.target + " > ul")
		
		
		for(var n = 0; n < 5; n++)
		{
			var curID = ($(config.source).length+1);
			var prevID = new RegExp("-"+$(config.source).length,"g");
			
			if(config.target == "#ur-ingredients"){
				//$(_source).find("label").remove();
				$(_source).find("sup").remove();
				var tmp1 = _source.html();
				 _source.html(tmp1.replace("required frm-ingredient","frm-ingredient"));
				_source.html(_source.html().replace("required frm-ingredient","frm-ingredient"));
				_source.html(_source.html().replace("required frm-ingredient","frm-ingredient"));
				_source.html(_source.html().replace("required frm-ingredient","frm-ingredient"));
			}
			else
			$(_source).find("label").html("Step "+curID+":");
			
			var tmp = _source.html();

			_source.html(tmp.replace(prevID,"-"+curID));
			
			$(_source).find(":input").each(function(){
					$(this).val("");									
			});	
			$(_ul).append(_source.clone());			
		}
				
		return false;
	},
	
		/*
			home page animation
		*/
		HomePageAnimation: function(el, config)
		{
			// food intro
			var fi	= ".food-intro";

			//removed animation
			$(fi).css(
				{
					opacity:0
				}
			).animate(
				{
					opacity:0
				},
				{
					duration:500
				}
			).animate(
				{
					opacity:1
				},
				{
					duration:500
				}
			) 

	var rand1 = 0;
	var useRand = 0;

	images = new Array;
	images[1] = new Image();
	images[1].src = "images/grp-homebase1.png";
	images[2] = new Image();
	images[2].src = "images/grp-homebase2.jpg";
	images[3] = new Image();
	images[3].src = "images/grp-homebase3.jpg";
	images[4] = new Image();
	images[4].src = "images/grp-homebase4.jpg";
	images[5] = new Image();
	images[5].src = "images/grp-homebase5.jpg";
	images[6] = new Image();
	images[6].src = "images/grp-homebase6.jpg";
	images[7] = new Image();
	images[7].src = "images/grp-homebase7.jpg";
	images[8] = new Image();
	images[8].src = "images/grp-homebase8.jpg";
	images[9] = new Image();
	images[9].src = "images/grp-homebase9.jpg";
	images[10] = new Image();
	images[10].src = "images/grp-homebase10.jpg";
	images[11] = new Image();
	images[11].src = "images/grp-homebase11.jpg";
	images[12] = new Image();
	images[12].src = "images/grp-homebase12.jpg";
	images[13] = new Image();
	images[13].src = "images/grp-homebase13.jpg";
	images[14] = new Image();
	images[14].src = "images/grp-homebase14.jpg";
	images[15] = new Image();
	images[15].src = "images/grp-homebase15.jpg";
	function swapPic() {
	var imgnum = images.length - 1;
	do {
	var randnum = Math.random();
	rand1 = Math.round((imgnum - 1) * randnum) + 1;
	} while (rand1 == useRand);
	useRand = rand1;
	document.randimg.src = images[useRand].src;
	}

	var rand2 = 0;
	var useRand1 = 0;

	images1 = new Array;
	images1[0] = new Image();
	images1[0].src = "../images/icn-feature1.png";
	images1[1] = new Image();
	images1[1].src = "../images/icn-feature2.png";
	images1[2] = new Image();
	images1[2].src = "../images/icn-feature3.png";
	images1[3] = new Image();
	images1[3].src = "../images/icn-feature4.png";


	function swapPic1() {
	var imgnum1 = images1.length - 1;
	do {
	var randnum1 = Math.random();
	rand2 = Math.round((imgnum1 - 1) * randnum1) + 1;
	} while (rand2 == useRand1);
	useRand1 = rand2;
	document.randimg1.src = images1[useRand1].src;
	}

			// reccent activity
			var ra	= ".activity ul li";
			$(ra).css(
				{
					opacity:0,
					position:"relative",
					top:"5px"
				}
			)
			var count		= $(ra).length;
			var i			= 1;
			var activity	= setInterval(
				function()
				{
					if(i < (count + 1))
					{
						$(ra + ":nth-child(" + i + ")").animate(
							{
								opacity:1,
								top:"0px"
							},
							{
								duration:(250)
							}
						)
						i++;
					}
					else{
						clearInterval(activity)
					}
				},
				300
			)	

			// feature
			var ft	= ".feature"
			$(ft).hide().animate(
				{
					top:"0px"
				},
				{
					duration:500,
					complete:function()
					{
						$(ft + " .bd").hide()
						$(ft).fadeIn("slow");
						$(ft + " .bd").animate(
							{
								top:"0px"
							},
							{
								duration:500,
								complete:function()
								{
									$(this).slideDown("slow");
								}
							}
						)
					}
				}
			)
		},
	
	/*
		general animation
	*/
	GeneralAnimation: function(el, config)
	{	
		var elem	= config.elem;
		$(elem).css(
			{
				opacity:0
			}
		);
		
		var i		= 0;
		var count	= 4;
		var activity	= setInterval(
			function()
			{
				if(i < (count))
				{
					var f = $(elem).get(i)
					$(f).css(
						{
							opacity:0
						}
					)
					$(f).animate(
						{
							opacity:1
						},
						{
							duration:350
						}
					)
					i++;
				}
				else{
					clearInterval(activity)
				}
			},
			300		
		)
		/*
		$(elem).each(
			function()
			{
				$(this).animate(
					{
						top:"0px"
					},
					{
						duration:(i * 1000),
						complete:function()
						{
							i++;
							$(this).animate(
								{
									opacity:1
								},
								{
									duration:250
								}
							)
						}
					}
				)
			}
		)
		*/
	}
}

//==========================================================================================
//	Password reminder
//==========================================================================================
function PasswordReminder()
{
	this.init	= function()
	{
		$.ajax(
			{
				url: "password.do",
				cache: false,
				data:{},
				dataType:"text",
				type:"GET", 
				success:function(text){
					$('body').append(text);
					//$.scrollTo('#scroll', 1500); // works but ends up conflicting with iframe ?!?!?
					_fixDimensions()
					_addClose();
					_addSubmit();				
				}			
			}
		);		
	}
	
	// fix dimension
	_fixDimensions	= function()
	{
		// static
		_lightbox		= $("#lightbox");		
		_blocker		= $(".blocker");
		_popup			= $(".popup");		

		_lightbox.show();
				
		if(document.innerHeight){temp=document.innerHeight;}else if(document.documentElement.clientHeight){temp=document.documentElement.clientHeight;}else if(document.body){temp=document.body.clientHeight;}		
	
		w	= $('body').width();
		h	= $('body').height() > temp ? $('body').height() : temp;
		
		x	= (w/2) - (_popup.width()/2);
		y	= (temp/2) - (_popup.height()/2) - 25;
		
		// background
		_blocker.css(
			{
				width:w,
				height:h,
				opacity:.60
			}
		).fadeIn("slow")
		
		// foreground
		_popup.css(
			{
				left:x,
				top:y				
			}
		).fadeIn('slow');
	}
	
	// add submit
	_addSubmit		= function()
	{
		var _submit			= $("#SubmitButton");
		var _email			= $("#EmailPassword");
	    var _options = { 	    	
    	    //target:        '#output2',   // target element(s) to be updated with server response 
        	//beforeSubmit:  _showRequest,  // pre-submit callback 
	        success:       _showResponse  // post-submit callback 
	        
	    }; 		
		_submit.bind(
			'click',
			function()
			{
				if($(_email).val().length < 1)
				{
					$(_email).css(
						{
							border:"solid #990000"
						}
					)
				}else if($(_email).val().length  > 1){
					var flag = false;
					with ($(_email).val())
					 {
						mailChecker =  '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@.-_?+';
						
						for (i=0; i < $(_email).val().length; i++)
							if(mailChecker.indexOf($(_email).val().charAt(i)) < 0)
							{
								flag = false;
							}
							
						apos=$(_email).val().indexOf("@");
						lpos=$(_email).val().lastIndexOf("@");
						dotpos=$(_email).val().lastIndexOf(".");
						lastpos=$(_email).val().length-1;
						
						if (apos<1 || (dotpos-apos)<2 || (lastpos-dotpos)>3 || (lastpos-dotpos)<2 || apos != lpos )
						{
							flag =  false;
						}
						else
						{
							flag =  true;
						}
					 }
					
					if(!flag){ 
						$(_email).css(
							{
								border:"solid #990000"
							}
						)
					}else{
						$("#ProfileForm").ajaxSubmit(_options);
					}
				}
			}
		)	
	}
	//Show response jsp
	_showResponse = function(responseText, statusText,el,_timeout)
	{
			_kill();
			$('body').append(responseText);
			//$.scrollTo('#scroll', 1500); // works but ends up conflicting with iframe ?!?!?
			_fixDimensions()
			_addClose();
	}
	
	
	// add close
	_addClose		= function()
	{
		var _close			= $(".close, #CancelButton");
		_close.bind(
			'click',
			function()
			{
				_kill()
			}
		)	
	}
	
	_kill			= function()
	{
		_popup.fadeOut(
			"fast",
			function()
			{
				_blocker.fadeOut(
					"fast",
					function()
					{
					//	_lightbox.remove();
					}
				)						
			}
		)
	}	
	
	// run init
	this.init();
}

//read cookie value for ClickOut() function
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

//==========================================================================================
//	Click Out
//==========================================================================================
function ClickOut(config,_userid)
{
	// constructor
	var _snackbar		= {
		top:config.snackbar.top,
		bottom:config.snackbar.bottom
	}
	
	/*
		animation notation
		-------------------------------------
		fade badge		-> .toolbarBadge-sm
		fade logout		-> #sbLogout
		fade buttons	-> #sbStuff
		fade search		-> #sbSearch
		fade logo		-> #logo
	*/
	
	this._objects		= {
		badge:" .toolbarBadge-sm, .toolbarBadgeext-sm",
		logout:" #sbLogout",
		buttons:" #sbStuff",
		search:" #sbSearch",
		logo:" #logo"
	}
		
	var	_links			= $(config.links);
	var	_dropbox		= $(config.dropbox);
	//var 	_serviceURL		= "http://bangbasil.sapient.com/pem/ToolBarGetNavigationSites.do";
	var 	_serviceURL		= "sample-json.html";
	
	
	// hide bottom bar and place at bottom
	$(_snackbar.bottom).hide();
	
	if( config.page && config.page.toLowerCase() == "homebase" ){
		$(_snackbar.top + ", " + _snackbar.bottom).css(
			{
				top: "-120px"
			}
		)			
	}else{	
		$(_snackbar.top + ", " + _snackbar.bottom).css(
			{
				position:"relative"
			}
		)
	}
	
	//  Hide bottom snackbar when remove button is clicked
	$("#closeSnackBarBtm").bind(
		'click',
			function(){
				$("#BottomSnackbar").hide();
				//set iframe width/height to 100%
				$("#iframe").css(
					{
						width: "100%",
						height: "100%"
					}
				);
			}
	)
	
	// variables
	var _a;
	var _lightbox;
	var _blocker;
	var _popup;	
	
	// bind links
	_links.bind(
		'click',
		function(e)
		{	
			_a	= $(this).attr("href");
			_isFoodComRecipe = $(this).attr("isFoodComRecipe");
			_hrefId = $(this).attr("id");//Added from DEV file while integration
			var recipeID = $(this).attr("rel");
			var title = $(this).attr("title");
			var recipeURL = $(this).attr("url");
			var source = $(this).attr("source");
						
			var 	_jsonServiceURL		= "sample-json.html";
			var redirectURL = "search-results-confirm.html";
			var friendlyName = "friendlyName";
			var validThirdParty = true;
			
			
			var userHistoryURL = "userHistoryController.do";
			
			// user history
			$.ajax({
				url:userHistoryURL,
				cache:false,
				data:{"recipeID":_hrefId,"recipeURL":_serviceURL,"source":source,"url":_a,"title":title},
				dataType:"text",
				type:"POST"
			})
			
			
			//if the user has a toolbar installed, we don't need to do the ajax calls
			//or
			//if the link is from food.com, meaning same domain, don't do third party nav or any interstitials
			//we are assuming a relative url so there should be no http://
			if(( $('#isToolbarLoggedIn').val()=="true" ) || _isFoodComRecipe){
				window.location =_a;
				return false;
			}
			
			//first find out if the site can be shown in an iframe
			$.ajax({
				url: _serviceURL,
				cache:false,
				data:"null",
				dataType:"json",
				type:"POST",
				success:function(result){
					var uri = _a.split("//")[1].toLowerCase();
					for ( var index in result.response.valid ){
						if( index != "contains" ){
							var curSiteName = result.response.valid[index][0].toLowerCase();
							if(uri.indexOf(curSiteName) >=0){
								if( result.response.valid[index][1]=="N" ){
									redirectURL = "jsp/interstitial_leave_site.jsp";
									friendlyName = result.response.valid[index][2];
									validThirdParty = false;
								}
								break;
							}
						}
					}


					/*
						interstitial
					*/

					$.ajax(
						{
							url: redirectURL,
							cache: false,
							data:{ "friendlyName": friendlyName, "uri" : _a},
							dataType:"text",
							type:"GET", 
							success:function(text){
								$('body').append(text);
								//get cookie for not showing third party interstitial
								var x = readCookie('ThirdParty'+_userid);
								
								if(!validThirdParty){
									x = readCookie('InvalidThirdParty'+_userid);
								}
								
								if( validThirdParty && recipeID != null ){
									$("#sbAddBoxLink").attr("rel", recipeID);
									$("#sbAddBoxLink").attr("title", title);
									$("#sbAddBoxLink").attr("url", recipeURL);
									$("#sbAddBoxLink").attr("source", source);
								}
								
								//just redirect if there is no need for the interstitial
								if (x && x == 'skip') 
								{		
								   	if(!validThirdParty){	window.location =_a;} 
									ClickOut._success();
								}else{
									//only show interstitial if the cookie is not set
									ClickOut._fixDimensions(x)

									ClickOut._addClose();
									ClickOut._buttons();
								}					

							}
						}
					);	
				}
			});
			
			return false;
		}
	)
	
	// fix dimension
	this._fixDimensions	= function(cookieValue)
	{
		//only show lightbox if the skip cookie has not been set
		if(!(cookieValue && cookieValue == 'skip')){
			// static
			_lightbox		= $("#lightbox");		
			_blocker		= $(".blocker");
			_popup			= $(".popup");		
	
			_lightbox.show();
					
			if(document.innerHeight){temp=document.innerHeight;}else if(document.documentElement.clientHeight){temp=document.documentElement.clientHeight;}else if(document.body){temp=document.body.clientHeight;}		
		
			w	= $('body').width();
			h	= $('body').height() > temp ? $('body').height() : temp;
			
			x	= (w/2) - (_popup.width()/2);
			//y	= (temp/2) - (_popup.height()/2) - 25;
			
			// scroll to
			var y = document.body.scrollTop;
			if (y == 0)
			{
				if (window.pageYOffset)
				{
					y = window.pageYOffset;
				}			        
				else
				{
					y = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;	
				}
			}
			y += 50;
			
			// background
			_blocker.css(
				{
					width:w,
					height:h,
					opacity:.60
				}
			).fadeIn("slow")
			
			// foreground
			_popup.css(
				{
					left:x,
					top:y				
				}
			).fadeIn('slow');
		}
	}
	
	// add close
	this._addClose		= function()
	{
		var _close			= $(".close");
		_close.bind(
			'click',
			function()
			{
				ClickOut._kill()
			}
		)	
	}
	
	this._kill			= function()
	{
		_popup.fadeOut(
			"fast",
			function()
			{
				_blocker.fadeOut(
					"fast",
					function()
					{
						_lightbox.remove();
					}
				)						
			}
		)
	}
	
	this._buttons		= function()
	{
		$(".cancel").bind(
			'click',
			function()
			{
				ClickOut._kill()
			}
		)
		
		$(".okay").bind(
			'click',
			function()
			{
				ClickOut._success();
			}
		)
		
		// second popup
		$(".leave").bind(
			'click',
			function()
			{
				ClickOut._kill()
				
				/*
					change your snack bar here
				*/	
				
			}
		)
		
		$(".deny").bind(
			'click',
			function()
			{
				ClickOut._kill()
			}
		)								
	}
	
	this._success		= function()
	{

		if(_lightbox){
			ClickOut._kill();
		}
		
		ClickOut.interval;
		//Commented dev line for Integration// _anchor = $(_snackbar).position().top;
		
		_anchor = $(_snackbar.top).position().top;
		
		$("#fadeContent").fadeOut(
			1000,
			function()
			{
				$(this).remove();
				
				ClickOut.interval	= setInterval(
					function()
					{					
						$(_snackbar.top).css(
							{
								top:_anchor + "px"
							}
						)
					},
					10
				)				
			}
		)
		$("#header").fadeOut(
			1010,
			function()
			{		
				//_switch()
				_animate();
			}
		)		

		$(window).unbind('resize');	
	}
	
	_switch		= function()
	{

		html	= "";
		html	+= "<div id=\"external\" class=\"snackSection\">";
		html	+= "<input type=\"hidden\" name=\"recipeDetails3rdParty\" value='"+ _hrefId +"'/>"
//		html	+= "<a href=\"\" onclick=\"javascript:addToRecipeBox('"+ _hrefId +"')\">Add to Box</a>";
		html	+= "<a href=\"\" class=\"icon\" id=\"sb-Search\" title=\"Back to search results\" onclick=\" javascript:history.go(0) \">Back to search results</a>";
		html	+= "<h1><a href=\"homebase.do\">Food.com</a></h1>";
		html	+= "</div>";
		$(config.snackbar + " .wrapper").prepend(html)
		
		$("#sb-AddRecipe").show();

		_animate()
	}
	
	_animate	= function()
	{	
		// vars
		if(document.innerHeight){
			temp=document.innerHeight;
		}else if(document.documentElement.clientHeight){
			temp=document.documentElement.clientHeight;
		}else if(document.body){
			temp=document.body.clientHeight;
		}
		var _h	= $(window).height();
		var _y	= _h - 84;
		if( config.page && config.page.toLowerCase() == "homebase" ){
			_y -= 350;
		}
				
		//---------------------------------------------
		// chain
		//---------------------------------------------		
		
		var _speed	= 150
		// badge
		var snackbar	= _snackbar.top;
		// logout
		$(snackbar + ClickOut._objects.logout).fadeOut(
			_speed,
			function()
			{
				//  buttons
				$(snackbar + ClickOut._objects.buttons).fadeOut(
					_speed,
					function()
					{
						//  search
						$(snackbar + ClickOut._objects.search).fadeOut(
							_speed,
							function()
							{
								// clear interval
								clearInterval(ClickOut.interval)

								// hide dropbox
								$(_dropbox).fadeOut(
									"fast",
									function()
									{
										ClickOut._scale()
										$(window).bind(
											'resize',
											ClickOut._scale
										)
									}
								)

								// move bar
								$(snackbar).css(
									{
										"z-index":"999",
										"position":"relative"
									}
								)
								$(snackbar).animate(
									{
										top:_y
									},
									{
										duration:750,
										complete:_reanimate
									}
								)										
							}
						)
					}
				)						
			}
		)
	}
	
	_reanimate	= function()
	{	
		if(!this._set)
		{
			this._set = true
			
			
			var _top = $(_snackbar.top).css("top")
			_top = parseInt(_top);
			
			if( config.page && config.page.toLowerCase() == "homebase" ){
				_top += 350;
			}
			
			// set to same y position
			$(_snackbar.bottom).css(
				{
					top:_top,
					position:"relative"
				}
			)
			
			// hide objects
			for(prop in ClickOut._objects)
			{
				if(prop != "logo")
				{
					$(_snackbar.bottom + ClickOut._objects[prop]).hide()				
				}
			}

			// show hide
			$(_snackbar.top).hide();			
			$(_snackbar.bottom).show();			

			//---------------------------------------------
			// chain
			//---------------------------------------------			
			
			var _speed	= 150
			// badge
			var snackbar	= _snackbar.bottom;
			
			// move bar
			$(snackbar).css(
				{
					"z-index":"999"
				}
			)
						
			$(snackbar + ClickOut._objects.search).fadeIn(
				_speed,
				function()
				{
					// logout
					$(snackbar + ClickOut._objects.buttons).fadeIn(
						_speed,
						function()
						{
							//  buttons
							$(snackbar + ClickOut._objects.logout).fadeIn(
								_speed,
								function()
								{
									//  search
									ClickOut._frame()
								}
							)						
						}
					)				
				}
			)			
		}		
	}
	
	this._frame	= function()
	{
		var _origin		= false;		
		var _h			= $(window).height()-84;
		var _w			= $(window).width()-5;
		_iframe			= $(document.createElement("iframe"));
		_iframe.attr(
			{
				border:"none",
				width:_w,
				height:_h,
				src:_a,
				id:"iframe"
			}
		)
		_iframe.css(
			{
				position:"absolute",
				left:"0px",
				top:"0px",
				"z-index":500,
				"background-color":"#fff"
			}
		)
		
		$("#"+config.page).append(_iframe)
		
		_iframe.bind(
			"load",
			function()
			{
				if(_origin == true)
				{
					$.ajax(
						{
							url: "search-results-leaving.html",
							cache: false,
							data:{},
							dataType:"text",
							type:"GET", 
							success:function(text){
								$('body').append(text);
								_fixDimensions()
								_addClose();
								_buttons();					
							}
						}
					);
				}				
				if(_origin == false){_origin = true}
			}
		)				
	}
	
	this._scale	= function(e)
	{
		if(document.innerHeight){
			temp=document.innerHeight;
		}else if(document.documentElement.clientHeight){
			temp=document.documentElement.clientHeight;
		}else if(document.body){
			temp=document.body.clientHeight;
		}
		var _h	= $(window).height();
		var _y	= _h - 86;
		
		// fram size	
		$("#search-results").css(
			{
				height:_h,
				overflow:"hidden"
			}
		)
		
		$("#iframe").css(
			{
				height:_h
			}
		)		
		
		// snackbar position
		$(_snackbar).css(
			{
				top:_y
			}
		)		
	}
}

//==========================================================================================
//	Table class
//==========================================================================================
function Table(config){
	//--------------------------------------------------------------
	// variables
	//--------------------------------------------------------------
		var _ie		= window.ActiveXObject ? true : false;
		this._config	= {}
		this._columns	= {}
		this._width		= Array();
		this._height	= Array();
		this._rows		= Array();
		
		this._step		= 0;
		this._steps		= 0;
		
		Table			= this;

	//--------------------------------------------------------------
	// methods
	//--------------------------------------------------------------
	
	// init
	_init	= function(config)
	{
		this._config	= config;
		if(this._config['table_id'])
		{
			_clone()
		}
	}
	
	// clone 
	_clone	= function()
	{
		// clone entire table
		var holder			= this._config.holder_id;
		var div				= this._config.div_id;
		var table			= this._config.table_id;

		this._div			= $(document.createElement("div"));
		this._table			= $(table).clone();

		this._div.addClass(div);		
		
		// change class
		this._table.removeClass("rb-results-table");
		this._table.addClass("rb-results-clone");
		this._table.attr(
			{
				id:"rb-table-clone"
			}
		)	

		// append to div
		this._div.append(this._table);
		$(holder).append(this._div);
		
		$(".rb-results-cn").css(
			{
				"z-index":"800"
			}
		)
		
		$(".rb-results-cn").css
		(
			{
				left:"308px",
				width:"373px"
			}
		)
		$("#rb-table").css(
			{
				left:"-313px"	
			}
		)		
		
		// 
		
		this._columns	= Array();
		for(prop in this._config)
		{
			if(
				prop == "anchor" ||
				prop == "left" ||
				prop == "right" 
			)
			{
				this._columns.push(this._config[prop])
			}
		}
		
		$(".rb-results-clone thead th").each(
			function(i)
			{
				if($(this).attr("remove"))
				{
					$(this).remove();
				}
			}
		);
				
		var _td = $(".rb-results-clone td");
		_td.remove();
		
		var px	= [null, 261, 10, 10]

		// fix first column width
		$(".rb-results-clone tr th:nth-child(1)").css(
			{
				width:"266px"
			}
		)

		// set width of middle column
		var td	= "<td class=\"rb-clone-empty\"></td>"
		$(".rb-results-clone tr th:nth-child(2)").after(td);

		$(".rb-results-clone td").css(
			{
				width:"353px"
			}
		)
		
		// fix width of ingredients
		$(".rb-results-clone .ingredients, .rb-results .ingredients").css(
			{
				width:"115px"
			}
		)
		
		_functionality("#rb-table-clone");
		_addHover();
		Table._pageHeight();
	}
	
	this._pageHeight		= function()
	{
		// quick IE test
		if(parseInt($.browser.version) == 6 && $.browser.msie === true )
		{  
			// we need to add the additional page y 
			/*
			if(($(".grid-sidebar").height() - 200) < $("#rb-table-clone").height())
			{
				alert("sidebar " + $(".grid-sidebar").height() + ": clone " + $("#rb-table-clone").height() + ": table " + $("#rb-table").height())
				$(".grid-sidebar").height($("#rb-table-clone").height() + 200 )
			}
			else
			{
				$(".grid-sidebar").height($("#rb-table").height())			
			}
			*/
			$(".grid-sidebar").height($("#rb-table-clone").height() + 200);
		}
		else
		{
			$("#recipebox").height($("#rb-table-clone").height()+50)		
		}
		
		//set height of bottom pagination container
		$("#recipe-box").find("#recipebox #rb-holder").css("height",$("#recipe-box").find("#recipebox #rb-holder .rb-results-cn-clone").height());		
	}
	
	_addHover		= function()
	{		
		// roll over
		var origin	= "#rb-table tbody tr";
		var cloned	= "#rb-table-clone tbody tr";
		
		$(origin + ", " + cloned).hover(
			function()
			{
				var id = $(this).attr("id");
				$(
					origin + "#" + id + ", " + 
					cloned + "#" + id + ", " +
					cloned + "#" + id + " th"
					).css(
					{
						"background-color":"#f7f7f7"
					}
				)
			},
			function()
			{
				var id = $(this).attr("id");
				$(
					origin + "#" + id + ", " + 
					cloned + "#" + id + ", " +
					cloned + "#" + id + " th"
					).css(
					{
						"background-color":"#FFFFFF"
					}
				)				
			}
		)
		
		$(origin + ", " + cloned).mousedown(
			function()
			{
				$(this).mousemove(
					function()
					{
						$("#recipe-drag-box").css(
							{
								"z-index":999
							}
						)
					}
				)
			}
		)
	}
	
	this._fixRowHeight = function()
	{

		$(".rb-results-clone tbody tr").each(
			function(i)
			{
				var clone	= {
					tr:$(".rb-results tbody tr:nth-child(" + (i + 1) + ")"),
					h:$(".rb-results tbody tr:nth-child(" + (i + 1) + ")").height()
				}
				var orig	= {
					tr:$(this),
					h:$(this).height()
				}

				if(clone.h > orig.h)
				{
					$(orig.tr).css(
						{
							height:clone.h
						}
					)
					Table._updateClone($(orig.tr).attr("id"), true)
				}
				else if( clone.h < orig.h  )
				{
					$(clone.tr).css(
						{
							height:orig.h
						}
					)					
				}
			}
		)						
	}
	
	// update clone table
	this._updateClone	= function(id, d)
	{
		var h	= $(".rb-results-clone tbody tr#" + id).height();

		$(".rb-results tbody tr#" + id).css(
			{
				height:h				
			}
		)
		
		$(".rb-results tbody").hide();
		$(".rb-results tbody").show();		

		// find discrepency
		if($.browser.msie === true)
		{
			var delta  = $(".rb-results tbody tr#" + id).height() - $(".rb-results-clone tbody tr#" + id).height();
			if(delta > 0)
			{
				var add = 2
				if(d)
				{
					add = 0
				}
				$(".rb-results tbody tr#" + id).css(
					{
						height:((h - delta) + add)
					}
				)			
			}			
		}
	
		this._pageHeight()
	}
	
	_trimArray	= function(arr)
	{
		//get sorted array as input and returns the same array without duplicates.
		var result=new Array();
		var lastValue="";
		for (var i=0; i<arr.length; i++)
		{
			var curValue=arr[i];
			if (curValue != lastValue)
			{
				result[result.length] = curValue;
			}
			lastValue=curValue;
		}
		return result;
	}
		
	// add functionality
	_functionality	= function(id)
	{	
		var td			= this._config.table_id + " tbody tr:first-child";
		var children	= $(td).children("td");
		
		Table._current	= 0;
		Table._width.push(0)
		
		$(children).each(
			function()
			{
				Table._width.push($(this).width() + 21);
			}
		)
		
		// running total
		var total	= 0
		for(n in Table._width)
		{
			if(n != 0)
			{
				Table._width[n] += Table._width[n -1]
				if(Table._width[n] > 613)
				{
					if(Table._steps == 0)
					{
						Table._steps	= n + 1;
					}
					Table._width[n] = 613
				}
			}
		}
		tempArray	= _trimArray(Table._width);	
		Table._width = Array();
		Table._width.push(0)
		Table._width = Table._width.concat(tempArray)
		Table._steps		= Table._width.length
				
		// prev
		var prev = $(id + " th.prevCol");
		prev.css(
			{
				cursor:"pointer"
			}
		)

		prev.click(
			function()
			{
				Table.pagination(-1)
			}
		)
		prev.mouseover(
			function()
			{
				$(this).css(
					{
						color:"#e25d05"
					}
				)
			}
		)
		prev.mouseout(
			function()
			{
				$(this).css(
					{
						color:"#000000"
					}
				)			
			}
		)		
		// next
		var next = $(id + " th.nextCol");
		next.css(
			{
				cursor:"pointer"
			}
		)

		next.click(
			function()
			{				
				Table.pagination(1)
			}
		)
		next.mouseover(
			function()
			{
				$(this).css(
					{
						color:"#e25d05"
					}
				)
			}
		)
		next.mouseout(
			function()
			{
				$(this).css(
					{
						color:"#000000"
					}
				)			
			}
		)	
	};
	
	this.pagination = function(dir)
	{
	
		$("#rb-table th.name").css("padding", "0")
		$("#rb-table th.prevCol").css("padding", "0")
		
		var nameColWidth = $("#rb-table th.name").width()
		var prevColWidth = $("#rb-table th.prevCol").width()
		
		//the extra 2 offset at the end is just to ensure that we don't see any of the previous column 
		var offset = $("#rb-table-clone").get(0).offsetLeft - nameColWidth - prevColWidth - 2
		
		if(dir > 0)
		{
			if(this._current + dir < this._steps)
			{
				this._current++
			}
		}
		if(dir < 0)
		{
			if(this._current + dir >= 0)
			{
				this._current--
			}
		}		
		
		var x			= this._width[this._current]
		$("#rb-table").animate(
			{
				left: offset - x
			},
			{
				duration:350
			}
		)
	}
	
	
	//
	_init(config)
}
//==========================================================================================

// extend plugin scope
$.fn.extend({
tablesorter: $.tablesorter.construct
});

var ts = $.tablesorter;

// add default parsers
ts.addParser({
    // set a unique id 
    id: 'totalTime', 
    is: function(s) { 
        // return false so this parser is not auto detected 
        return false; 
    }, 
    format: function(s) { 
        // format your data for normalization 
		
        // return ; 
    }, 
    // set type, either numeric or text 
    type: 'numeric' 
});


//==========================================================================================
//	Autocomplete
//==========================================================================================
jQuery.autocomplete = function(input, options) {
	// Create a link to self
	var me = this;

	// Create jQuery object for input element
	var $input = $(input).attr("autocomplete", "off");

	// Apply inputClass if necessary
	if (options.inputClass) $input.addClass(options.inputClass);

	// Create results
	var results = document.createElement("div");
	// Create jQuery object for results
	var $results = $(results);
	$results.hide().addClass(options.resultsClass).css("position", "absolute");
	if( options.width > 0 ) $results.css("width", options.width);

	// Add to body element
	$("body").append(results);

	input.autocompleter = me;

	var timeout = null;
	var prev = "";
	var active = -1;
	var cache = {};
	var keyb = false;
	var hasFocus = false;
	var lastKeyPressCode = null;

	// flush cache
	function flushCache(){
		cache = {};
		cache.data = {};
		cache.length = 0;
	};

	// flush cache
	flushCache();

	// if there is a data array supplied
	if( options.data != null ){
		var sFirstChar = "", stMatchSets = {}, row = [];

		// no url was specified, we need to adjust the cache length to make sure it fits the local data store
		if( typeof options.url != "string" ) options.cacheLength = 1;

		// loop through the array and create a lookup structure
		for( var i=0; i < options.data.length; i++ ){
			// if row is a string, make an array otherwise just reference the array
			row = ((typeof options.data[i] == "string") ? [options.data[i]] : options.data[i]);

			// if the length is zero, don't add to list
			if( row[0].length > 0 ){
				// get the first character
				sFirstChar = row[0].substring(0, 1).toLowerCase();
				// if no lookup array for this character exists, look it up now
				if( !stMatchSets[sFirstChar] ) stMatchSets[sFirstChar] = [];
				// if the match is a string
				stMatchSets[sFirstChar].push(row);
			}
		}

		// add the data items to the cache
		for( var k in stMatchSets ){
			// increase the cache size
			options.cacheLength++;
			// add to the cache
			addToCache(k, stMatchSets[k]);
		}
	}

	$input
	.keydown(function(e) {
		// track last key pressed
		lastKeyPressCode = e.keyCode;
		switch(e.keyCode) {
			case 38: // up
				e.preventDefault();
				moveSelect(-1);
				break;
			case 40: // down
				e.preventDefault();
				moveSelect(1);
				break;
			case 9:  // tab
			case 13: // return
				if( selectCurrent() ){
					// make sure to blur off the current field
					$input.get(0).blur();
					e.preventDefault();
				}
				break;
			default:
				active = -1;
				if (timeout) clearTimeout(timeout);
				timeout = setTimeout(function(){onChange();}, options.delay);
				break;
		}
	})
	.focus(function(){
		// track whether the field has focus, we shouldn't process any results if the field no longer has focus
		hasFocus = true;
	})
	.blur(function() {
		// track whether the field has focus
		hasFocus = false;
		hideResults();
	});

	hideResultsNow();

	function onChange() {
		// ignore if the following keys are pressed: [del] [shift] [capslock]
		if( lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32) ) return $results.hide();
		var v = $input.val();
		if (v == prev) return;
		prev = v;
		if (v.length >= options.minChars) {
			$input.addClass(options.loadingClass);
			requestData(v);
		} else {
			$input.removeClass(options.loadingClass);
			$results.hide();
		}
	};

 	function moveSelect(step) {

		var lis = $("li", results);
		if (!lis) return;

		active += step;

		if (active < 0) {
			active = 0;
		} else if (active >= lis.size()) {
			active = lis.size() - 1;
		}

		lis.removeClass("ac_over");

		$(lis[active]).addClass("ac_over");

		// Weird behaviour in IE
		// if (lis[active] && lis[active].scrollIntoView) {
		// 	lis[active].scrollIntoView(false);
		// }

	};

	function selectCurrent() {
		var li = $("li.ac_over", results)[0];
		if (!li) {
			var $li = $("li", results);
			if (options.selectOnly) {
				if ($li.length == 1) li = $li[0];
			} else if (options.selectFirst) {
				li = $li[0];
			}
		}
		if (li) {
			selectItem(li);
			return true;
		} else {
			return false;
		}
	};

	function selectItem(li) {
		if (!li) {
			li = document.createElement("li");
			li.extra = [];
			li.selectValue = "";
		}
		var v = $.trim(li.selectValue ? li.selectValue : li.innerHTML);
		input.lastSelected = v;
		prev = v;
		$results.html("");
		$input.val(v);
		hideResultsNow();
		if (options.onItemSelect) setTimeout(function() { options.onItemSelect(li) }, 1);
	};

	// selects a portion of the input string
	function createSelection(start, end){
		// get a reference to the input element
		var field = $input.get(0);
		if( field.createTextRange ){
			var selRange = field.createTextRange();
			selRange.collapse(true);
			selRange.moveStart("character", start);
			selRange.moveEnd("character", end);
			selRange.select();
		} else if( field.setSelectionRange ){
			field.setSelectionRange(start, end);
		} else {
			if( field.selectionStart ){
				field.selectionStart = start;
				field.selectionEnd = end;
			}
		}
		field.focus();
	};

	// fills in the input box w/the first match (assumed to be the best match)
	function autoFill(sValue){
		// if the last user key pressed was backspace, don't autofill
		if( lastKeyPressCode != 8 ){
			// fill in the value (keep the case the user has typed)
			$input.val($input.val() + sValue.substring(prev.length));
			// select the portion of the value not typed by the user (so the next character will erase)
			createSelection(prev.length, sValue.length);
		}
	};

	function showResults() {
		// get the position of the input field right now (in case the DOM is shifted)
		var pos = findPos(input);
		// either use the specified width, or autocalculate based on form element
		var iWidth = (options.width > 0) ? options.width : $input.width();
		// reposition
		$results.css({
			width: parseInt(iWidth) + "px",
			top: (pos.y + input.offsetHeight) + "px",
			left: pos.x + "px"
		}).show();
	};

	function hideResults() {
		if (timeout) clearTimeout(timeout);
		timeout = setTimeout(hideResultsNow, 200);
	};

	function hideResultsNow() {
		if (timeout) clearTimeout(timeout);
		$input.removeClass(options.loadingClass);
		if ($results.is(":visible")) {
			$results.hide();
		}
		if (options.mustMatch) {
			var v = $input.val();
			if (v != input.lastSelected) {
				selectItem(null);
			}
		}
	};

	function receiveData(q, data) {
		if (data) {
			$input.removeClass(options.loadingClass);
			results.innerHTML = "";

			// if the field no longer has focus or if there are no matches, do not display the drop down
			if( !hasFocus || data.length == 0 ) return hideResultsNow();

			if ($.browser.msie) {
				// we put a styled iframe behind the calendar so HTML SELECT elements don't show through
				$results.append(document.createElement('iframe'));
			}
			results.appendChild(dataToDom(data));
			// autofill in the complete box w/the first match as long as the user hasn't entered in more data
			if( options.autoFill && ($input.val().toLowerCase() == q.toLowerCase()) ) autoFill(data[0][0]);
			showResults();
		} else {
			hideResultsNow();
		}
	};

	function parseData(data) {
		if (!data) return null;
		var parsed = [];
		var rows = data.split(options.lineSeparator);
		for (var i=0; i < rows.length; i++) {
			var row = $.trim(rows[i]);
			if (row) {
				parsed[parsed.length] = row.split(options.cellSeparator);
			}
		}
		return parsed;
	};

	function dataToDom(data) {
		var ul = document.createElement("ul");
		var num = data.length;

		// limited results to a max number
		if( (options.maxItemsToShow > 0) && (options.maxItemsToShow < num) ) num = options.maxItemsToShow;

		for (var i=0; i < num; i++) {
			var row = data[i];
			if (!row) continue;
			var li = document.createElement("li");
			console.log(row[0])			
			if (options.formatItem) {
				li.innerHTML = options.formatItem(row, i, num);
				li.selectValue = row[0];
			} else {
				li.innerHTML = row[0];
				li.selectValue = row[0];
			}
			var extra = null;
			if (row.length > 1) {
				extra = [];
				for (var j=1; j < row.length; j++) {
					extra[extra.length] = row[j];
				}
			}
			li.extra = extra;
			ul.appendChild(li);
			$(li).hover(
				function() { $("li", ul).removeClass("ac_over"); $(this).addClass("ac_over"); active = $("li", ul).indexOf($(this).get(0)); },
				function() { $(this).removeClass("ac_over"); }
			).click(function(e) { e.preventDefault(); e.stopPropagation(); selectItem(this) });
		}
		return ul;
	};

	function requestData(q) {
		if (!options.matchCase) q = q.toLowerCase();
		var data = options.cacheLength ? loadFromCache(q) : null;
		// recieve the cached data
		if (data) {
			receiveData(q, data);
		// if an AJAX url has been supplied, try loading the data now
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){
			/*
			$.get(makeUrl(q), function(data) {
				data = parseData(data);
				addToCache(q, data);
				receiveData(q, data);
			});
			*/
			// post
			var post		= options.post;
			post.searchText	= q;

			// ajax call
			$.ajax(
				{
					url:options.url,
					cache:false,
					data:post,					
					dataType:"json",
					type:"POST",
					success:function(result){						
						// success						
						if(result.response.success == "success")
						{
							var data		= "";
							var ingredients	= eval(result.response.ingredients);
							for(i in ingredients)
							{
								//data += ingredients[i] + "|" + i + "\n";
								data += ingredients[i] + "\n";
							}
							data = parseData(data);
							addToCache(q, data);
							receiveData(q, data);					
						}
						//fail
						else
						{								

						}							
					},
					error:function()
					{

					}				
				}
			);
		// if there's been no data found, remove the loading class
		} else {
			$input.removeClass(options.loadingClass);
		}
	};

	function makeUrl(q) {
		var url = options.url + "?q=" + encodeURI(q);
		for (var i in options.extraParams) {
			url += "&" + i + "=" + encodeURI(options.extraParams[i]);
		}
		return url;
	};

	function loadFromCache(q) {
		if (!q) return null;
		if (cache.data[q]) return cache.data[q];
		if (options.matchSubset) {
			for (var i = q.length - 1; i >= options.minChars; i--) {
				var qs = q.substr(0, i);
				var c = cache.data[qs];
				if (c) {
					var csub = [];
					for (var j = 0; j < c.length; j++) {
						var x = c[j];
						var x0 = x[0];
						if (matchSubset(x0, q)) {
							csub[csub.length] = x;
						}
					}
					return csub;
				}
			}
		}
		return null;
	};

	function matchSubset(s, sub) {
		if (!options.matchCase) s = s.toLowerCase();
		var i = s.indexOf(sub);
		if (i == -1) return false;
		return i == 0 || options.matchContains;
	};

	this.flushCache = function() {
		flushCache();
	};

	this.setExtraParams = function(p) {
		options.extraParams = p;
	};

	this.findValue = function(){
		var q = $input.val();

		if (!options.matchCase) q = q.toLowerCase();
		var data = options.cacheLength ? loadFromCache(q) : null;
		if (data) {
			findValueCallback(q, data);
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){
			$.get(makeUrl(q), function(data) {
				data = parseData(data)
				addToCache(q, data);
				findValueCallback(q, data);
			});
		} else {
			// no matches
			findValueCallback(q, null);
		}
	}

	function findValueCallback(q, data){
		if (data) $input.removeClass(options.loadingClass);

		var num = (data) ? data.length : 0;
		var li = null;

		for (var i=0; i < num; i++) {
			var row = data[i];

			if( row[0].toLowerCase() == q.toLowerCase() ){
				li = document.createElement("li");
				if (options.formatItem) {
					li.innerHTML = options.formatItem(row, i, num);
					li.selectValue = row[0];
				} else {
					li.innerHTML = row[0];
					li.selectValue = row[0];
				}
				var extra = null;
				if( row.length > 1 ){
					extra = [];
					for (var j=1; j < row.length; j++) {
						extra[extra.length] = row[j];
					}
				}
				li.extra = extra;
			}
		}

		if( options.onFindValue ) setTimeout(function() { options.onFindValue(li) }, 1);
	}

	function addToCache(q, data) {
		if (!data || !q || !options.cacheLength) return;
		if (!cache.length || cache.length > options.cacheLength) {
			flushCache();
			cache.length++;
		} else if (!cache[q]) {
			cache.length++;
		}
		cache.data[q] = data;
	};

	function findPos(obj) {
		var curleft = obj.offsetLeft || 0;
		var curtop = obj.offsetTop || 0;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
		return {x:curleft,y:curtop};
	}
}

jQuery.fn.autocomplete = function(url, options, data) {
	// Make sure options exists
	options = options || {};
	// Set url as option
	options.url = url;
	// set some bulk local data
	options.data = ((typeof data == "object") && (data.constructor == Array)) ? data : null;

	// Set default values for required options
	options.inputClass = options.inputClass || "ac_input";
	options.resultsClass = options.resultsClass || "ac_results";
	options.lineSeparator = options.lineSeparator || "\n";
	options.cellSeparator = options.cellSeparator || "|";
	options.minChars = options.minChars || 1;
	options.delay = options.delay || 400;
	options.matchCase = options.matchCase || 0;
	options.matchSubset = options.matchSubset || 1;
	options.matchContains = options.matchContains || 0;
	options.cacheLength = options.cacheLength || 1;
	options.mustMatch = options.mustMatch || 0;
	options.extraParams = options.extraParams || {};
	options.loadingClass = options.loadingClass || "ac_loading";
	options.selectFirst = options.selectFirst || false;
	options.selectOnly = options.selectOnly || false;
	options.maxItemsToShow = options.maxItemsToShow || -1;
	options.autoFill = options.autoFill || false;
	options.width = 221//parseInt(options.width, 10) || 0;

	this.each(function() {
		var input = this;
		new jQuery.autocomplete(input, options);
	});

	// Don't break the chain
	return this;
}

jQuery.fn.autocompleteArray = function(data, options) {
	return this.autocomplete(null, options, data);
}

jQuery.fn.indexOf = function(e){
	for( var i=0; i<this.length; i++ ){
		if( this[i] == e ) return i;
	}
	return -1;
};

function findValue(li) {
	if( li == null ) return alert("No match!");

	// if coming from an AJAX call, let's use the recipiId as the value
	if( !!li.extra ) var sValue = li.extra[0];

	// otherwise, let's just display the value in the text box
	else var sValue = li.selectValue;

	// alert("The value you selected was: " + sValue);
}

function selectItem(li) {
	findValue(li);
}

function formatItem(row) {
	return row[0] + " (id: " + row[1] + ")";
}

function lookupAjax(){
	var oSuggest = $("#Recipies")[0].autocompleter;

	oSuggest.findValue();

	return false;
}

function lookupLocal(){
	var oSuggest = $("#RecipiesList")[0].autocompleter;

	oSuggest.findValue();

	return false;
}
//==================================================================
//	FORMS
//==================================================================
function Forms(id)
{
	//--------------------------------------------------------------
	// variables
	//--------------------------------------------------------------
	
	var _id;
	var _data;
	var _success;	
	var _states		= US_STATES;
	var _industry	= INDUSTRY;
	var _income		= INCOME_RANGE;
	var _fails		= 0;
	var _login;
	
	//--------------------------------------------------------------
	// public methods
	//--------------------------------------------------------------
	this.init = function(data)
	{
		// set data
		_setData(data);
		
		// set data
		_setId(_data.id);		
		
		// check if state
		if(_data.states)
		{
			_populateStates(_data.states)
		}
		
		// check if industry
		if(_data.industry)
		{
			_populateIndustry(_data.industry)
		}
		
		// check if income
		if(_data.income)
		{
			_populateIncome(_data.income)
		}				
		
		// check if editable / hide input
		if(_data.editable)
		{
			// hide inputs / select / radio / ...
			$(_id + " :input").hide()
			$(_id + " fieldset span.required").hide();
			
			// buttons
			var _edit		= $(_id + " input[@name=Edit]");
			var _submit		= $(_id + " input[@name=Submit]");
			var _cancel		= $(_id + " input[@name=Cancel]");			

			// hide submit, cancel
			// show edit		
			_edit.show();
			_submit.hide();
			_cancel.hide();

			_createBlocks();
			_setValues();
		}
		
		if(_data.success)
		{
			_success = _data.success
		}
		
		if(_data.login)
		{
			_login	= _data.login;
		}
	}
	
	_createBlocks	= function()
	{
		// block other
		if(_data.block)
		{
			for(block in _data.block)
			{
				var blocked	= _data.block[block];
				$(blocked).each(
					function()
					{
						console.log($(this));
						$(this).css(
							{
								position:"relative"
							}
						)
						var blocker = {
							w:$(this).width(),
							h:$(this).height(),
							x:$(this).offset().left,
							y:$(this).offset().top
						}				
						
						var div	= $(document.createElement("div"));
						div.attr(
							{
								"class":"blockers"
							}
						)
						div.css(
							{
								position:"absolute",
								width:blocker.w + "px",
								height:blocker.h + "px",
								left:"0px",
								top:"0px",
								background:"#FFFFFF",
								border:"none",
								opacity:0
							}
						)
						
						$(this).append(div)

					}
				)
			}
			$(".blockers").hide();
		}
	}
	
	_setValues		= function()
	{
		$(_id + " fieldset span").each(
			function()
			{
				_val	= $(this).html();
				
				// text field input
				var _input = $(this).parent().children("input")
				var _select = $(this).parent().children("select")

				if(_input.length > 0)
				{
					_input.attr(
						{
							value:_val
						}
					)
				}
				
				if(_select.length > 0)
				{
					var _options	= _select.children("option").length	
					for(var n = 0; n < _options; n++)
					{
						if(_select.children("option")[n].value.toLowerCase() == _val.toLowerCase())
						{
							_select.children("option")[n].selected = true;
						}
					}
				}				
				
				
			}			
		)
	}
	
	this.editForm	= function()
	{			
		this._success	= _success;				
		// buttons
		var _edit		= $(_id + " input[@name=Edit]");
		var _submit		= $(_id + " input[@name=Submit]");
		var _cancel		= $(_id + " input[@name=Cancel]");
				
		var _version	= _submit.css("display") == "none" ? true : false ;
		
		// show editable
		if(_version)
		{
			// show inputs / select / radio / ...
			$(_id + " :input").show();
			$(_id + " fieldset span.value").hide();
			$(_id + " fieldset span.required").show();
						
			// show submit, cancel
			// hide edit			
			_edit.hide();
			_submit.show();
			_cancel.show();	
			
			if(_data.block)
			{
				$(".blockers").show()
				$(".blockers").animate(
					{
						opacity:0.5
					},
					{
						duration:250
					}
				)
			}
		}
		// hide editable
		else
		{
			// hide inputs / select / radio / ...
			$(_id + " :input").hide();
			$(_id + " fieldset span.value").show();
			$(_id + " fieldset span.required").hide();
			
			// hide submit, cancel
			// show edit
			_edit.show();
			_submit.hide();
			_cancel.hide();
			
			if(_data.block)
			{
				$(".blockers").animate(
					{
						opacity:0
					},
					{
						duration:250,
						complete:function()
						{
							$(".blockers").hide()
						}
					}
				)
			}			
		}		
	}

	
	this.processForm = function(_submitForm1)
	{	
		// set up error vars
		var errorMessage = Array(); 
		
		var emailError = true;
		var prepHour;
		var cookHours;
		
		var _error	= false;
		var _errors	= Array();
		
		var _submit	= {};
		
		// loop through form
		$(":input", _id).each(
			function()
			{							
				field		= $(this).attr("name");
				if(field=='prepHours'){
					prepHour = $(this).val();
				}
				if(field=='cookHours'){
					cookHours = $(this).val();
				}								
				
				if($(_id + " #" + field).length > 0)
				{
					if(_data.required[field] == "checkbox"){

						if(!$(this).is(":checked"))
						{
							_error	= true;
							_errors.push(field)
						}
						else{
							_submit[field]	= $(this).val();
						}

					} else if(_data.required[field]){
						if(!$(this).val())
						{
							_error	= true;
							_errors.push(field)
							
						}
						else{
							if(field == 'email' || field == 'loginId' || field == 'LastName'){
								emailError = checkEmailId($(this).val());
								if(emailError){
									_submit[field]	= $(this).val();
								}else{
									errorMessage.push("Invalid Email Id")
									_error	= true;
									_errors.push(field)
								}
								
							}else if(field == 'zip' || field == 'Zip'){
								if($(this).val().length < 5){
										errorMessage.push("Zip should of five characters")
										_error	= true;
										_errors.push(field)
								}else if($(this).val().length == 5){
								emailError = validateData($(this).val());
								if(emailError){
									_submit[field]	= $(this).val();
								}else{
									errorMessage.push("Enter Numbers only for Zip")
									_error	= true;
									_errors.push(field)
									}
								}
								
							}else{
								_submit[field]	= $(this).val();
							}
						}
					}else{
						if(field=='prepMins' && prepHour == "0"){
								if($(this).val() == "0")
								_error	= true;
								_errors.push(field)
						}else if($(this).attr("type") == "checkbox")
						{
							_submit[field]	= $(this).attr("checked") ? true : false;								
	
						}else{
							_submit[field]	= $(this).val();
						}
					}
				}
			}
		)
		var _obj	= {
			success:_success,
			login:_login
		}
		if(_submitForm1 == 'true'){
			if(!_error){	
				_submitForm(_submit, _data.url, _obj) 
			}else {
				if(!emailError){
					_errorEmailInvalidForm(errorMessage);
				}
				else if(_error){
				 	_errorForm(_errors);
				}
			}
		}else{
					if(_error)
						{
						_errorForm(_errors);
						return false;
						
						}else{
							return true;
						}
		}
	}
	
	checkEmail	= function(email)
	{
		var at="@"
		var dot="."
		var lat=email.indexOf(at)
		var lstr=email.length
		var ldot=email.indexOf(dot)
		if (email.indexOf(at)==-1){return false;}
		if (email.indexOf(at)==-1 || email.indexOf(at)==0 || email.indexOf(at)==lstr){return false;}
		if (email.indexOf(dot)==-1 || email.indexOf(dot)==0 || email.indexOf(dot)==lstr){return false;}
		if (email.indexOf(at,(lat+1))!=-1){return false;}
		if (email.substring(lat-1,lat)==dot || email.substring(lat+1,lat+2)==dot){return false;}
		if (email.indexOf(dot,(lat+2))==-1){return false;}
		if (email.indexOf(" ")!=-1){return false;}
		return true;		
	}
	function checkEmailId(entered)
	{
	 with (entered)
	 {
		mailChecker =  '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@.-_?+';
		
		for (i=0; i < entered.length; i++)
			if(mailChecker.indexOf(entered.charAt(i)) < 0)
			{
				return false;
			}
			
		apos=entered.indexOf("@");
		lpos=entered.lastIndexOf("@");
		dotpos=entered.lastIndexOf(".");
		lastpos=entered.length-1;
		
		if (apos<1 || (dotpos-apos)<2 || (lastpos-dotpos)>3 || (lastpos-dotpos)<2 || apos != lpos )
		{
			return false;
		}
		else
		{
			return true;
		}
	 }//end with
	 
	}//end function
	
	
		function validateData(data)
		{
			var dataPattern="0123456789";
			var i=0;
			var j=0;
			var pos=1;
			
			while(i<data.length && pos==1)
			 {
				for(j=0;j<dataPattern.length;j++)
				{
					if(data.charAt(i) == dataPattern.charAt(j))
					{
					   i++;
					   pos=1;
					   break;
					}
					else
					{
						pos=0;
					}
				}
			}
			if(i<data.length)
			{
				return false;
			}
			return true;
			
		}	
	_addErrotFields	= function(_errors){
		var _form		= $('#ErrorForm');
		var _popup		= $(".popup");
		var	_p			= $(".popup .message");
		
		for(n in _errors)
		{
			var field	= _errors[n];
			var _div	= $(document.createElement("div"));
			
			_div.append("<sup class=\"restar\">*</sup>")
			_div.append(field);
			_p.append(_div);
		}		
	}
	
	_errorEmailInvalidForm = function(_errors)
	{
		InterstitialController.error(
			{
				title:"Oops!",
				message:"[We need apprpriate copy here]"
			}
		)
		/*
		$.ajax(
			{
				url: "errors.html",
				cache: false,
				data:{},
				dataType:"text",
				type:"GET", 
				success:function(text){
					$('body').append(text);
					_addErrotFields(_errors);
					_fixDimensions();
					_addClose();					
				}			
			}
		);
		*/		
	}
	
	//--------------------------------------------------------------
	// private methods
	//--------------------------------------------------------------			
	_setData = function(data)
	{
		_data		= data;
	}
	
	_setId = function(id)
	{
		_id		= id;
	}	
	_submitForm	= function(_submit, _url, _obj)
	{		

		$.ajax(
			{
				url: _url,
				cache: false,
				data:_submit,					
				dataType:"json",
				type:"POST", 
				success:function(json){
					// check if editable / hide input
					// in addition the loaded page should send back a return or echo -> success=true;
					if(json.response.success == "true"){
						//if we have a success message, show it, otherwise redirect
						if( _obj.success )	{
							_successRedirect( _obj.success, json.response.url )
						}else{				
							window.location = json.response.url
						}
					}
					if(json.response.passwordChange == "success"){
						document.forms.PasswordForm.password.value = "";
		     			document.forms.PasswordForm.currentPassword.value = "";
						document.forms.PasswordForm.rePassword.value = "";
						_passwordChange();
					}
					if(json.response.passwordChange == "failure"){
						_passwordChange();
					}

					if(json.response.emailUpdate && json.response.emailUpdate=="pass"){
						$("#EmailForm fieldset span.value").html($("#EmailForm fieldset input#email").val());
						DoEmail.editForm();
					}
					if(json.response.success == "fail"){
						_passwordChange();
					}
					if(json.response.invitedUser == "success"){
					    if(document.forms.RegistrationForm.loginId){ document.forms.RegistrationForm.loginId.value = ""; }
					    if(document.forms.RegistrationForm.firstName){ document.forms.RegistrationForm.firstName.value = "";}
						if(document.forms.RegistrationForm.lastName){ document.forms.RegistrationForm.lastName.value = "";}
						if(document.forms.RegistrationForm.email){ document.forms.RegistrationForm.email.value = "";}
						if(document.forms.RegistrationForm.streetAddress1){ document.forms.RegistrationForm.streetAddress1.value = "";}
						if(document.forms.RegistrationForm.streetAddress2){ document.forms.RegistrationForm.streetAddress2.value = "";}
						if(document.forms.RegistrationForm.state){ document.forms.RegistrationForm.state.value = "";}
						if(document.forms.RegistrationForm.zip){ document.forms.RegistrationForm.zip.value = "";}
						if(document.forms.RegistrationForm.gender){ document.forms.RegistrationForm.gender.value = "";}
						if(document.forms.RegistrationForm.incomeRange){ document.forms.RegistrationForm.incomeRange.value = "";}
						if(document.forms.RegistrationForm.industry){ document.forms.RegistrationForm.industry.value = "";}
						if(document.forms.RegistrationForm.typeOfJob){ document.forms.RegistrationForm.typeOfJob.value = "";}
						if(document.forms.RegistrationForm.city){ document.forms.RegistrationForm.city.value = "";}
						
						_invitedUserSuccess();
					}else if(json.response.invitedUser == "failed"){
						_invitedUserSuccess();
					}

					if(json.response.accountUpdate == "failed"){
						_invitedUserSuccess();
					}
					if(json.response.systemerror == "true")
					{	
						//for all unexpected system error's lets delegate the call to
						//a generic system error page. the url attribute would be error page url.
						window.location = json.response.url
					}
					// server needs to return failed echo -> login="failed"
					if(json.response.login == "failed")		
					{
						// Comments from BASELINE_fails++;
						// comments from BASELINEif(_fails > 2)
							_loginFailed();
					}

					//Added for handling user registration
					if(json.response.register && json.response.register== "userExist")
					{
						_userExist();
					}				
					
					if(json.response.register && json.response.register== "uninvitedUser")
					{
						_uninvitedUser();
					}

					if(json.response.register && json.response.register == "profanityError")
					{			
						_profanityError(json);
					}				
					
				},
				error:function(json) {				
					window.location = "exceptionController.do";
					//_loginFailed();
					//Commented Baseline JS line for Integration//InterstitialController.error(InterstitialController.errormessage.load)
				}
			}
		);

//*		
		// remove this one once ajax is working
		if(_obj.success)
		{
			_addSuccess(_obj.success)
		}		
		
//		*/
	}
	
	
	_successRedirect	= function( _success, _url )
	{
		$.ajax(
			{
				url: "jsp/interstitial_success_redirect.jsp",
				cache: false,
				data:{ title:_success.title, message:_success.message, url:_url },
				dataType:"text",
				type:"GET", 
				success:function(text){
					InterstitialController.clearContent();
					InterstitialController.display(text);
					
				}			
			}
		);	
	}	
	
	
	_loginFailed	= function()
	{
	/*
		$.ajax(
			{
				url: "jsp/interstitial_failed_login.jsp"",
				cache: false,
				data:{},
				dataType:"text",
				type:"GET", 
				success:function(text){
					$('body').append(text);
					_fixDimensions();
					_addClose();					
				}				
			}
		);		
		*/
		Login.Failed("jsp/interstitial_failed_login.jsp");
	}
	
	_invitedUserSuccess	= function()
	{
		$.ajax(
			{
				url: "jsp/interstitial_beta_tester.jsp",
				cache: false,
				data:{},
				dataType:"text",
				type:"GET", 
				success:function(text){

					InterstitialController.clearContent();
					InterstitialController.display(text);
					
					setTimeout( 
						function(){
							$(InterstitialController.interstitial.lightbox).fadeOut("fast");
						},
						5000
					)
					
				}			
			}
		);	
	}
	
	// Added by Abhinandan R.....
	
	_passwordChange	= function()
	{
		$.ajax(
			{
				url: "jsp/changePasswordInterstitial.jsp",
				cache: false,
				data:{},
				dataType:"text",
				type:"GET", 
				success:function(text){
					$('body').append(text);
					_fixDimensions();
					_addClose();	
					
					setTimeout( 
						function(){
							$(InterstitialController.interstitial.lightbox).fadeOut("fast");
						},
						5000
					)								
				}				
			}
		);		
	}
	_loginSuccess	= function()
	{
		
		$.ajax(
			{
				url: "jsp/loginSuccess.html",
				cache: false,
				data:{},
				dataType:"text",
				type:"GET", 
				success:function(text){
					$('body').append(text);
					_fixDimensions();
					_addClose();					
				}				
			}
		);		
	}
	_showSystemError = function()
	{		
		$.ajax(
			{
				url: "jsp/systemerror.html",
				cache: false,
				data:{},
				dataType:"text",
				type:"GET", 
				success:function(text){
					$('body').append(text);
					_fixDimensions();
					_addClose();					
				}				
			}
		);		
	}

	_uninvitedUser = function()
	{
		$.ajax(
			{
				url: "jsp/uninvited.jsp",
				cache: false,
				data:{},
				dataType:"text",
				type:"GET", 
				success:function(text){
					$('body').append(text);
					
					_fixDimensions();
					_addClose();					
				}				
			}
		);		
		
		
	}
	
	_userExist = function()
	{
		$.ajax(
			{
				url: "jsp/userexist.jsp",
				cache: false,
				data:{},
				dataType:"text",
				type:"GET", 
				success:function(text){
					$('body').append(text);
					
					_fixDimensions();
					_addClose();					
				}				
			}
		);		
	}

	_profanityError = function(_json)
	{
		$.ajax(
			{
				url: "jsp/showProfanityErrors.jsp",
				cache: false,
				data:{},
				dataType:"text",
				type:"GET", 
				success:function(text){
					$('body').append(text);
					$('.popup .message').append(_json.response.errMessage);					
					_fixDimensions();
					_addClose();					
				}				
			}
		);		
	}
	
	_addSuccess	= function(_success)
	{
		
		$.ajax(
			{
				url: "jsp/success.html",
				cache: false,
				data:{},
				dataType:"text",
				type:"GET", 
				success:function(text){
					$('body').append(text);
					$(".popup h2").append(_success.title);
					$(".popup p").append(_success.message);
										
					_fixDimensions();
					_addClose();					
				}
			}
		);
	}
	
	_errorForm = function(_errors)
	{
		InterstitialController.error(
			{
				title:"Oops!",
				message:"[We need apprpriate copy here]"
			}
		)
		/*
		$.ajax(
			{
				url: "errors.html",
				cache: false,
				data:{},
				dataType:"text",
				type:"GET", 
				success:function(text){
					$('body').append(text);
					_addFields(_errors);
					_fixDimensions();
					_addClose();					
				}
			}
		);
		*/		
	}	
	
	_addFields	= function(_errors){
		var _form		= $('#ErrorForm');
		var _popup		= $(".popup");
		var	_p			= $(".popup .message");

		for(n in _errors)
		{
			var field	= _errors[n];
			var html	= $("#" + field).parent().children('label').html();
			
			var i		= html.indexOf("*")
			if(i != -1)
			{
				html		= html.slice(0, i) + html.slice((i + 1), html.length)
			}
	
			var _div	= $(document.createElement("div"));
			_div.append("<sup class=\"restar\">*</sup>")
			_div.append(html);
			
			_p.append(_div);
		}		
	}
	
	_fixDimensions	= function()
	{
		$('#lightbox').show();
		
		var _blocker	= $(".blocker");
		var _popup		= $(".popup");
				
		if(document.innerHeight){temp=document.innerHeight;}else if(document.documentElement.clientHeight){temp=document.documentElement.clientHeight;}else if(document.body){temp=document.body.clientHeight;}		
	
		w	= $('body').width();
		h	= $('body').height() > temp ? $('body').height() : temp;
		
		x	= (w/2) - (_popup.width()/2);
		y	= (h/2) - (_popup.height()/2) - 25;
		
		// background
		_blocker.css(
			{
				width:w,
				height:h,
				opacity:.60
			}
		).fadeIn("slow")
		
		// foreground
		_popup.css(
			{
				left:x,
				top:y				
			}
		).fadeIn('slow');		
	}
	
	_populateStates = function(id)
	{
		var select	= $(id).get(0)
		var n	= 0;
		
		for(state in _states)
		{
			n++;
			select.options[n] = new Option(state, state);	
		}
	}
	
	_populateIndustry = function(id)
	{
		var select	= $(id).get(0)
		var n	= 0;
		
		for(industry in _industry)
		{
			n++;
			select.options[n] = new Option(_industry[industry], industry);	
		}
	}	
	
	_populateIncome = function(id)
	{
		var select	= $(id).get(0)
		var n	= 0;
		
		for(income in _income)
		{
			n++;
			select.options[n] = new Option(_income[income], income);
		}
	}	
	
	_addClose	= function()
	{
		var _close			= $(".close");
		_close.bind(
			'click',
			function()
			{
				_kill()
			}
		)		
	}
	
	_kill			= function()
	{
		var _lightbox	= $("#lightbox");
		var _blocker	= $(".blocker");
		var _popup		= $(".popup");
		
		_popup.fadeOut(
			"fast",
			function()
			{
				_blocker.fadeOut(
					"fast",
					function()
					{
						_lightbox.remove();
					}
				)						
			}
		)
	}	
}


//==================================================================
//	US STATES ARRAY
//==================================================================
var US_STATES = {
	AA: "Military Americas",
	AE: "Military Europe/ME/Canada",
	AK: "Alaska",
	AL: "Alabama",
	AP: "Military Pacific",
	AR: "Arkansas",
	AS: "American Samoa",
	AZ: "Arizona",
	CA: "California",
	CO: "Colorado",
	CT: "Connecticut",
	DC: "D.C.",
	DE: "Delaware",
	FL: "Florida",
	FM: "Micronesia",
	GA: "Georgia",
	GU: "Guam",
	HI: "Hawaii",
	IA: "Iowa",
	ID: "Idaho",
	IL: "Illinois",
	IN: "Indiana",
	KS: "Kansas",
	KY: "Kentucky",
	LA: "Louisiana",
	MA: "Massachusetts",
	MD: "Maryland",
	ME: "Maine",
	MH: "Marshall Islands",
	MI: "Michigan",
	MN: "Minnesota",
	MO: "Missouri",
	MP: "Marianas",
	MS: "Mississippi",
	MT: "Montana",
	NC: "North Carolina",
	ND: "North Dakota",
	NE: "Nebraska",
	NH: "New Hampshire",
	NJ: "New Jersey",
	NM: "New Mexico",
	NV: "Nevada",
	NY: "New York",
	OH: "Ohio",
	OK: "Oklahoma",
	OR: "Oregon",
	PA: "Pennsylvania",
	PR: "Puerto Rico",
	PW: "Palau",
	RI: "Rhode Island",
	SC: "South Carolina",
	SD: "South Dakota",
	TN: "Tennessee",
	TX: "Texas",
	UT: "Utah",
	VA: "Virginia",
	VI: "Virgin Islands",
	VT: "Vermont",
	WA: "Washington",
	WI: "Wisconsin",
	WV: "West Virginia",
	WY: "Wyoming"
};

var INDUSTRY	= {
	"Administrative&Clerical": "Administrative & Clerical",
	"ArchitectureDesign": "Architecture & Design",
	"ArtsEntertainment": "Arts & Entertainment",
	"BusinessIndustry": "Business & Industry",
	"Education": "Education",
	"Healthcare": "Healthcare",
	"Homemaker": "Homemaker",
	"HospitalityFood": "Hospitality & Food",
	"FinancialServices": "Financial Services",
	"GovernmentServices": "Government Services",
	"LegalServices": "Legal Services",
	"Military": "Military",
	"Manufacturing": "Manufacturing",
	"MediaPublishing": "Media & Publishing",
	"Services": "Services",
	"SalesRetail": "Sales & Retail",
	"TechnologyInternet": "Technology & Internet",
	"Other": "Other"
}

var INCOME_RANGE	= {
	"30" : "$0 -  $30,000",
	"60" : "$30,000 - $60,000",
	"100" : "$60,000 - $100,000",
	"200" : "$100,000 - $200,000",
	"500" : "$200,000 - $500,000",
	"MORE" : "$500,000+"
}

//==========================================================================================
//	Snackbar Animation
//==========================================================================================
function SnackBarAnimation()
{
	//--------------------------------------------------------------
	// variables
	//--------------------------------------------------------------
	
	var _id;
	var _dir;
	var _y;
	var _link;	
	var _form	= false;
	var _anchor	= {
		up:122,
		down:228
	}
	var	_home;
	var _onclick;
	
	//--------------------------------------------------------------
	// public methods
	//--------------------------------------------------------------
	this.init = function(data)
	{
		_id		= data.id
		_dir	= data.dir
		_y		= _anchor[_dir]
		_home	= data.home
		
		this._capture();
	}
	
	this._capture	= function()
	{
		// $("a, button")
		var _bind = !_home ? "#logo h1, #external h1" : "a[class!='external'], button"
		if(!_home){
			$(_bind).css(
				{
					cursor:"pointer"
				}
			)			
		}

		$(_bind).bind(
			'click',
			function(event)
			{	
				_href		= !_home ? $("#logo a").attr("href") : $(this).attr("href");
				_onclick	= $(this).attr("onclick");
				
				// ternary
				_link	= !_href ? 
					!_onclick ? 
					 	/* form */
						$(this).parents().map(
							function()
							{
								if(this.nodeName.toLowerCase() == "form" && !_form)
								{
									_form = $(this);
								}
							}
						) :
						/* button */ 
						"_onclick" : 
					_href;
					
				_movebar();
				return false;
			}
		)
	}
	
	_movebar	= function()
	{
		if(_home)
		{
			$(_id + " #fakelogo").fadeIn(
				"slow",
				function()
				{
					$(_id).animate(
						{
							top:_y
						},
						{
							duration:1000,
							complete:SnackBarAnimation._complete
						}
					)
				}			
			)			
		}
		else
		{
			$(_id).animate(
				{
					top:_y
				},
				{
					duration:1000,
					complete:SnackBarAnimation._complete
				}
			)	
		}
	}
	
	this._complete	= function()
	{
		if(_form)
		{
			_form.submit()
		}
		else
		{
			if(_onclick)
			{
				$('body').append("<script>" + _onclick + "</script>");
			}
			else
			{
				window.location = _link;
			}
		}
	}
}
//==========================================================================================
//	INIT
//==========================================================================================	
jQuery.fn.pem = jQuery.pem.init;




//==========================================================================================
//	RB-DETAIL IMAGE ROLLOVERS
//==========================================================================================
    var RecipeBoxImage = {
		// objects
		objects:{
			base: ".recipe-image",
			image:".recipe-image .image",
			title:".recipe-image .message .title",
			copy:".recipe-image .message .copy"
		},
		
		// open in popup
		open:function()
		{
			var w		= $(this.objects.image + " img").width() < 300 ? 300 : $(this.objects.image + " img").width() + 10;
			var h		= $(this.objects.image + " img").height()+50
						
			var params = "?source="+escape($(this.objects.image + " img").attr("src"));
			params += "&title="+escape($(this.objects.title).text());
			params += "&message="+escape($(this.objects.copy).text());
			
			window.open(
				"rb-detail-image-popup.html"+params,
				"RecipeImage",
				"status=0, toolbar=0, resizable=0, scrollbars=0, width=" + w + ", height=" + h 
			)
		},
		
		// on state
		on:function()
		{
			// image height
			$(this.objects.image).animate(
				{
					height:320
				},
				{
					duration:500
				}
			);
			
			// copy
			$(this.objects.copy).fadeIn('fast');
		},

		// off state		
		off:function()
		{
			// image height
			$(this.objects.image).animate(
				{
					height:220
				},
				{
					duration:500
				}
			);
			
			// copy
			$(this.objects.copy).fadeOut('fast');			
		}
	}
	
	$(document).ready(
		function()
		{
			/*$(".recipe-image .image").bind(
				'click',
				function()
				{
					RecipeBoxImage.open()
				}
			)
						
			
			$(".recipe-image .image").bind(
				'mouseover',
				function()
				{
					RecipeBoxImage.on()
				}
			)
			
			$(".recipe-image .image").bind(
				'mouseout',
				function()
				{
					RecipeBoxImage.off()
				}
			)
			*/			
		}
	)


//==========================================================================================
// TOOL TIP BUBBLES
//========================================================================================== 
$(function () {
  $('.bubbleInfo').each(function () {
    // options
    var distance = 10;
    var time = 150;
    var hideDelay = 500;

    var hideDelayTimer = null;

    // tracker
    var beingShown = false;
    var shown = false;
    
    var trigger = $('.trigger', this);
    var popup = $('.infopop', this).css('opacity', 0);

    // set the mouseover and mouseout on both element
    $([trigger.get(0), popup.get(0)]).mouseover(function () {
      // stops the hide event if we move from the trigger to the popup element
      if (hideDelayTimer) clearTimeout(hideDelayTimer);

      // don't trigger the animation again if we're being shown, or already visible
      if (beingShown || shown) {
        return;
      } else {
        beingShown = true;

        // reset position of popup box
        popup.css({
          top: -37,
          left: 298,
          display: 'block' // brings the popup back in to view
        })

        // (we're using chaining on the popup) now animate it's opacity and position
        .animate({
          top: '-=' + distance + 'px',
          opacity: 1
        }, time, 'swing', function() {
          // once the animation is complete, set the tracker variables
          beingShown = false;
          shown = true;
        });
      }
    }).mouseout(function () {
      // reset the timer if we get fired again - avoids double animations
      if (hideDelayTimer) clearTimeout(hideDelayTimer);
      
      // store the timer so that it can be cleared in the mouseover if required
      hideDelayTimer = setTimeout(function () {
        hideDelayTimer = null;
        popup.animate({
          top: '-=' + distance + 'px',
          opacity: 0
        }, time, 'swing', function () {
          // once the animate is complete, set the tracker variables
          shown = false;
          // hide the popup entirely after the effect (opacity alone doesn't do the job)
          popup.css('display', 'none');
        });
      }, hideDelay);
    });
  });
});

 //plug-in for info bubbles: user-profile.html//
$(function () {
  $('.bubbleInfo').each(function () {
    // options
    var distance = 10;
    var time = 250;
    var hideDelay = 500;

    var hideDelayTimer = null;

    // tracker
    var beingShown = false;
    var shown = false;
    
    var trigger = $('.trigger2', this);
    var popup = $('.infopop2', this).css('opacity', 0);

    // set the mouseover and mouseout on both element
    $([trigger.get(0), popup.get(0)]).mouseover(function () {
      // stops the hide event if we move from the trigger to the popup element
      if (hideDelayTimer) clearTimeout(hideDelayTimer);

      // don't trigger the animation again if we're being shown, or already visible
      if (beingShown || shown) {
        return;
      } else {
        beingShown = true;

        // reset position of popup box
        popup.css({
          top: -38,
          left: 285,
          display: 'block' // brings the popup back in to view
        })

        // (we're using chaining on the popup) now animate it's opacity and position
        .animate({
          top: '-=' + distance + 'px',
          opacity: 1
        }, time, 'swing', function() {
          // once the animation is complete, set the tracker variables
          beingShown = false;
          shown = true;
        });
      }
    }).mouseout(function () {
      // reset the timer if we get fired again - avoids double animations
      if (hideDelayTimer) clearTimeout(hideDelayTimer);
      
      // store the timer so that it can be cleared in the mouseover if required
      hideDelayTimer = setTimeout(function () {
        hideDelayTimer = null;
        popup.animate({
          top: '-=' + distance + 'px',
          opacity: 0
        }, time, 'swing', function () {
          // once the animate is complete, set the tracker variables
          shown = false;
          // hide the popup entirely after the effect (opacity alone doesn't do the job)
          popup.css('display', 'none');
        });
      }, hideDelay);
    });
  });
});

 //plug-in for info bubbles: user-register.html//
$(function () {
  $('.bubbleInfo').each(function () {
    // options
    var distance = 100;
    var time = 250;
    var hideDelay = 500;

    var hideDelayTimer = null;

    // tracker
    var beingShown = false;
    var shown = false;
    
    var trigger = $('.trigger3', this);
    var popup = $('.infopop3', this).css('opacity', 0);
    // set the mouseover and mouseout on both element
    $([trigger.get(0), popup.get(0)]).mouseover(function () {
      // stops the hide event if we move from the trigger to the popup element
      if (hideDelayTimer) clearTimeout(hideDelayTimer);

      // don't trigger the animation again if we're being shown, or already visible
      if (beingShown || shown) {
        return;
      } else {
        beingShown = true;

        // reset position of popup box

		var y	= 0;
		var obj	= document.getElementById($(this).attr('id'));
		
		var txt	= "inspect\n------\n";
		y = $(obj).position().top;
		moveLeft	= !document.getElementById($(this).attr('id')).offsetParent.x ? document.getElementById($(this).attr('id')).x : document.getElementById($(this).attr('id')).offsetParent.x ;
		moveLeft += 25

        popup.css({
          top: y + 50 ,//+ distance,
          left: moveLeft + "px",
          display: 'block' // brings the popup back in to view
        })		

        // (we're using chaining on the popup) now animate it's opacity and position
        .animate({
          top: '-=' + distance + 'px',
          opacity: 1
        }, time, 'swing', function() {
          // once the animation is complete, set the tracker variables
          beingShown = false;
          shown = true;
        });
      }
    }).mouseout(function () {
      // reset the timer if we get fired again - avoids double animations
      if (hideDelayTimer) clearTimeout(hideDelayTimer);
      
      // store the timer so that it can be cleared in the mouseover if required
      hideDelayTimer = setTimeout(function () {
        hideDelayTimer = null;
        popup.animate({
          top: '-=' + distance + 'px',
          opacity: 0
        }, time, 'swing', function () {
          // once the animate is complete, set the tracker variables
          shown = false;
          // hide the popup entirely after the effect (opacity alone doesn't do the job)
          popup.css('display', 'none');
        });
      }, hideDelay);
    });
  });
});

 //plug-in for info bubbles: rb-preview.html//
$(function () {
  $('.bubbleInfo').each(function () {
    // options
    var distance = 10;
    var time = 250;
    var hideDelay = 500;

    var hideDelayTimer = null;

    // tracker
    var beingShown = false;
    var shown = false;
    
    var trigger = $('.trigger4', this);
    var popup = $('.infopop4', this).css('opacity', 0);

    // set the mouseover and mouseout on both element
    $([trigger.get(0), popup.get(0)]).mouseover(function () {
      // stops the hide event if we move from the trigger to the popup element
      if (hideDelayTimer) clearTimeout(hideDelayTimer);

      // don't trigger the animation again if we're being shown, or already visible
      if (beingShown || shown) {
        return;
      } else {
        beingShown = true;

        // reset position of popup box
        popup.css({
          top: -56,
          left: 265,
          display: 'block' // brings the popup back in to view
        })

        // (we're using chaining on the popup) now animate it's opacity and position
        .animate({
          top: '-=' + distance + 'px',
          opacity: 1
        }, time, 'swing', function() {
          // once the animation is complete, set the tracker variables
          beingShown = false;
          shown = true;
        });
      }
    }).mouseout(function () {
      // reset the timer if we get fired again - avoids double animations
      if (hideDelayTimer) clearTimeout(hideDelayTimer);
      
      // store the timer so that it can be cleared in the mouseover if required
      hideDelayTimer = setTimeout(function () {
        hideDelayTimer = null;
        popup.animate({
          top: '-=' + distance + 'px',
          opacity: 0
        }, time, 'swing', function () {
          // once the animate is complete, set the tracker variables
          shown = false;
          // hide the popup entirely after the effect (opacity alone doesn't do the job)
          popup.css('display', 'none');
        });
      }, hideDelay);
    });
  });
});




//==========================================================================================
// SNACKBAR DROPDOWN MENUS- ICON HOVERS AND BADGE DOWNLOAD OVERLAY
//========================================================================================== 

var sfHover = {
	create:function(type)
	{
		var sfEls = type;		
		if($(sfEls).length > 0)
		{
			$(sfEls).each(
				function()
				{
					$(this).bind(
						'mouseover',
						function()
						{
							$(this).addClass("sfhover")
						}
					)
					
					$(this).bind(
						'mouseout',
						function()
						{
							$(this).removeClass("sfhover")
						}
					)					
				}
			)
		}		
	}	
}
$(document).ready(
	function()
	{
		sfHover.create("#nav li")
		sfHover.create("#dwnld li")
		sfHover.create("#navbtm li")
		sfHover.create("#dwnldbtm li")	
		sfHover.create("#dwnldhm li")	
	}
)

//==========================================================================================
// INTERSTITIAL CONTROLLER
//==========================================================================================
var InterstitialController	= {
	// internal
	controller:{},
	interstitial:{
		// interstitial shell
		shell:"jsp/interstitial_shell.jsp",
		
		// interstitial shell components
		lightbox:"#lightbox",
		blocker:"#lightbox > .blocker",
		popup:"#lightbox > .popup",
		close:"#lightbox .close"
	},
	
	// variables
	errormessage:{
		load:{
			title:"Oops!",
			message:"We did something wrong<br />We are currently resolving this issue!"
		}
	},
	
	// parameters
	/*
		trigger: id, class or csv of either or both
		url: url of page to load
	*/
	parameters:{},
	
	// config
	config:function(data)
	{
		// loop and assign
		this.parameters[data.instance] = {};
		instance	= this.parameters[data.instance];
		for(prop in data)
		{
			instance[prop] = data[prop];
		}
	
		// bind
		this.bind(instance)
	},
	
	// bind
	bind:function(object)
	{	
		// create element if non existant
		if(!object.trigger)
		{
			object.trigger	= "#" + object.instance;
			var trigger		= $(document.createElement("div"));
			$(trigger).attr(
				{
					id:object.instance
				}
			)
			$('body').append(trigger)
		}
		
		// dummy attribute
		$(object.trigger).attr(
			{
				"trigger":object.instance
			}
		)
	
		InterstitialController.bindTrigger( object );

	},
	
	bindTrigger:function( object ){
		//prevent default onclick, instead grab params from the specific element
		$(object.trigger).click(function(event){
			event.preventDefault();
			object["paramString"] = $(this).attr("params");
			object["params"]={ };
			object["params"]["id"] = $(this).attr("rel");
			object["params"]["name"] = $(this).attr("title");
			InterstitialController.getParams( object["params"], $(this).attr("params") );
			InterstitialController.open(this);
		});
	},
	
	//takes a string with name value pairs separated by & and puts them as n:v in paramArray
	getParams:function( paramArray, paramString ){
		if(paramString != null){
			var params = paramString.split('&');
			for( x=0; x<params.length; x++){	
				var oneParam = params[x].split('=');
				paramArray[ oneParam[0] ] =  oneParam[1];
			}
		}
	},
	
	// open
	open:function(instance)
	{
		// close if previous
		if($("#lightbox").length > 0)
		{
			this.kill();
		}
		
		var instance	= instance.getAttribute("trigger");
		var url	= InterstitialController.parameters[instance].url;		
		var params = "";
		
		if(InterstitialController.parameters[instance].paramString != null){	params = InterstitialController.parameters[instance].paramString;}
		if(InterstitialController.parameters[instance].params.id != null){	params += "&id="+InterstitialController.parameters[instance].params.id;}
		if(InterstitialController.parameters[instance].params.name != null){	params += "&name="+InterstitialController.parameters[instance].params.name;}
				
		// ajax call
		$.ajax(
			{
				url:InterstitialController.interstitial.shell,
				cache: false,
				data:{},
				dataType:"text",
				type:"GET",
				success:function(html)
				{
					
					// append to body
					$('body').append(html);
					
					var paramSep = url.search("\\?") < 0 ? "?" : "&" ;
				
					// load interior
					$.ajax(
						{
							url:url+paramSep+params,
							cache: false,
							data:{},
							dataType:"text",
							type:"GET",
							success:function(html)
							{
								InterstitialController.display(html, instance)								
							},
							error:function()
							{
								InterstitialController.error(errormessage.load)
							}
						}
					)										
				},
				error:function()
				{				
					InterstitialController.error(InterstitialController.errormessage.load)
				}
			}
		);
	},
	
	
	clearContent:function(){
		// close if previous
		if($("#lightbox").length > 0)
		{
			this.kill();
		}
		
		//build interstitial
		var lightbox	= $(document.createElement("div"));
		$(lightbox).attr(
			{
				id:"lightbox"
			}
		)	
		
		var blocker	= $(document.createElement("div"));
		$(blocker).addClass("blocker");
		
		var popup	= $(document.createElement("div"));
		$(popup).addClass("popup");
		
		var close	= $(document.createElement("div"));
		$(close).addClass("close");	
		
		$(popup).append(close);
		$(lightbox).append(blocker);
		$(lightbox).append(popup);
		
		$('body').append(lightbox);
	},
	
	error:function(copy)
	{
		InterstitialController.clearContent;
		
		this.parameters['LoadError']		= {
			type:"error"
		}
		
		var html	= ""
		html		+= "<h2>" + copy.title + "</h2>";
		html		+= "<p class=\"message\">" + copy.message + "</p>";
		html		+= "<form action=\"\" id=\"\" class=\"genericForm\" style=\"padding:0px;\">";
		html		+= "<fieldset>";
		html		+= "<input type=\"Button\" name=\"Cancel\" value=\"Close\" class=\"sm-btn\" onclick=\"InterstitialController.close()\">";
		html		+= "</fieldset>";
		html		+= "</form>";		
		
		this.display(html, 'LoadError')
	},
	
	step:function(url, instance, type)
	{
		// ajax call
		$.ajax(
			{
				url:InterstitialController.interstitial.shell,
				cache: false,
				data:{},
				dataType:"text",
				type:"GET",
				success:function(html)
				{
					// append to body
					$('body').append(html);
					
					// load interior
					$.ajax(
						{
							url:url,
							cache: false,
							data:{},
							dataType:"text",
							type:"GET",
							success:function(html)
							{
								InterstitialController.parameters[instance].type = type
								InterstitialController.display(html, instance)								
							},
							error:function()
							{
								InterstitialController.error(InterstitialController.errormessage.load)
							}
						}
					)										
				},
				error:function()
				{				
					InterstitialController.error(InterstitialController.errormessage.load)
				}
			}
		);		
	},
	
	display:function(html, instance)
	{	
		if( !this.parameters[instance] || !this.parameters[instance].no_scroll || this.parameters[instance].no_scroll!="true" ){
			// scroll to top
			window.scrollTo(0, 0)
		}
		
		
		// animate
		var lightbox	= $(this.interstitial.lightbox);		
		var blocker		= $(this.interstitial.blocker);
		var popup		= $(this.interstitial.popup);
		var close		= $(this.interstitial.close);
		// hide the select boxes on the page
		InterstitialController.toggleSelects();
		
		// append data
		$(popup).html(html);
		
		// type
		if(instance != null && this.parameters[instance].type)
		{
			$(popup).addClass(this.parameters[instance].type)
		}
		else
		{
			$(this.interstitial.popup + " p").css(
				{
					width:"400px"
				}
			)
		}
		
		// step
		if(instance != null && this.parameters[instance].step)
		{
			// instance
			var InterstitialController_instance	= document.createElement("input");
			$(InterstitialController_instance).attr(
				{
					type:"hidden",
					value:instance,
					id:"InterstitialController_instance",
					name:"InterstitialController_instance"
				}
			)			
			// success
			var InterstitialController_success	= document.createElement("input");
			$(InterstitialController_success).attr(
				{
					type:"hidden",
					value:this.parameters[instance].step.success,
					id:"InterstitialController_success",
					name:"InterstitialController_success"
				}
			)
			
			// error
			var InterstitialController_error	= document.createElement("input");
			$(InterstitialController_error).attr(
				{
					type:"hidden",
					value:this.parameters[instance].step.error,
					id:"InterstitialController_error",
					name:"InterstitialController_error"
				}
			)

			$(popup).append(InterstitialController_instance);						
			$(popup).append(InterstitialController_success);
			$(popup).append(InterstitialController_error);
		}
				
		// show lightbox	
		$(lightbox).show();
		
		this.dimensions(blocker, popup, instance);
		
		$(blocker).fadeIn('slow');
		$(popup).fadeIn('slow');
		
		$(close).bind(
			'click',
			function()
			{
				InterstitialController.close();
			}
		)
		
		$(blocker).bind(
			'click',
			function()
			{
				InterstitialController.close();
			}
		)	

		// trap enter key
		$(this.interstitial.popup + " > form input[@type=button]").each(
			function()
			{
				if($(this).attr('onclick'))
				{
					var name = $(this).attr('name').toString();
					if( name.toLowerCase() == "submit" ){
						InterstitialController.enter = $(this);
					}
				}
			}
		)

		if(InterstitialController.enter)
		{
			if(InterstitialController.enter.length > 0)
			{
				$(document).bind(
					'keypress',
					function(key)
					{
						if(key.which == 13)
						{
							$(InterstitialController.enter).trigger('click')
							return false;
						}
					}
				)			
			}			
		}
	},
	
	dimensions:function(blocker, popup, instance)
	{
		if(document.innerHeight){temp=document.innerHeight;}else if(document.documentElement.clientHeight){temp=document.documentElement.clientHeight;}else if(document.body){temp=document.body.clientHeight;}

		w	= $('body').width();
		h	= $('body').height() > temp ? $('body').height() : temp;
		
		x	= (w/2) - (popup.width()/2);
		y	= $('body').height() > temp ? (temp/2) - (popup.height()/2) - 25 : (h/2) - (popup.height()/2) - 25;
		
		
		if( instance && this.parameters[instance].y_pos){
			y = this.parameters[instance].y_pos;
		}
		
		// background
		$(blocker).css(
			{
				width:w,
				height:h,
				opacity:.60
			}
		)
		
		// foreground
		$(popup).css(
			{
				left:x,
				top:y				
			}
		)
	},
	
	// close
	close:function()
	{
		// animate
		var lightbox	= $(this.interstitial.lightbox);		
		var blocker		= $(this.interstitial.blocker);
		var popup		= $(this.interstitial.popup);

		popup.fadeOut(
			"fast",
			function()
			{
				blocker.fadeOut(
					"fast",
					function()
					{
						lightbox.remove();
//						$(document).unbind('keypress'); /* removed because it interferes with existing keybinding */
						InterstitialController.toggleSelects(true);
					}
				)						
			}
		)		
	},
	
	kill:function()
	{
		var lightbox	= $(this.interstitial.lightbox);
		lightbox.remove();
//		$(document).unbind('keypress');	/* removed because it interferes with existing keybinding */
	},
	
	// process
	process:function(form1)
	{
		var error	= false;		
		var errors	= Array();
		var form 	= $(form1);
		var action	= $(form).attr("action")
		var post	= {}
		
		// collect POST
		$(":input", form).each(
			function()
			{
				if(this.type != "button")
				{
					$(this).css(
						{
							"border":"solid 1px",	
							"border-color":"#8e8e8e #cecece #e3e3e3 #cecece"
						}
					)					
				}
				
				if(this.type != "button")
				{
					var id		= $(this).attr("id");
					var val		= $(this).val();

					if(id.toLowerCase().indexOf("email") != -1)
					{
						if(ValidEmail(val) == false)
						{
							var val = false;
						}
					}

					if(!val)
					{
						error	= true;
						errors.push(id)
					}
					else if(val.length < 1)
					{
						error 	= true;
						errors.push(id);
					}
					else
					{
						post[id]	= val;
					}					
				}
			}
		)
		
		if(error)
		{
			for(e in errors)
			{
				$("#lightbox #" + errors[e]).css(
					{
						border:"solid 1px #990000"
					}
				)
			}
		}
		else
		{
			if($(form).attr("interstitial"))
			{
				switch($(form).attr("interstitial"))
				{
					case "DoLogin":
						Login.Submit(Login.services.submit, post, form1)
					break;
				}
			}
			else
			{
				var url	= $("#InterstitialController_success").val();
				var instance = $("#InterstitialController_instance").val();	
				
				//add any params we got to the data we'll send
				for( x in this.parameters[instance].params ){
					post[x] = this.parameters[instance].params[x];
					//alert(x+" "+post[x]);
				}
				
				// submit to action url
				dataType = action.indexOf(".do") != -1 ? "json" : "text";
				$.ajax(
					{
						url:action,
						cache: false,
						data:post,
						dataType:dataType,
						type:"POST",
						success:function(json)
						{
							// No json response
							if(!json.response)
							{
								//kill is faster then close method
								InterstitialController.kill();						
								// check for error id
								if($("#InterstitialController_success").length > 0)
								{
									InterstitialController.kill();						
									InterstitialController.step(url, instance, "success");
								}
								else{
									InterstitialController.error(InterstitialController.errormessage.load)
								}
							}	
							// HAS json response			
							else
							{
								//------------------------------------------
								// do your actions here
								//------------------------------------------
								
								//build a param string
								var params = "";
								if(InterstitialController.parameters[instance].paramString != null){	params = InterstitialController.parameters[instance].paramString;}
								if(InterstitialController.parameters[instance].params.id != null){	params += "&id="+InterstitialController.parameters[instance].params.id;}
								if(InterstitialController.parameters[instance].params.name != null){	params += "&name="+InterstitialController.parameters[instance].params.name;}								
								
								//grab any special-case user-selectable params
								//if(post["Collection"] != null){	params += "&Collection="+post["Collection"]; }
								if(post["collectionName"] != null){	params += "&collectionName="+post["collectionName"]; }
								if(post["boxDelete"] != null){	params += "&boxDelete="+post["boxDelete"]; }
								
								//this is for success w/ confirmation screens
								if(json.response.success=="success" && url.length > 0){
									
									//first update the page if needed
									if(InterstitialController.parameters[instance].update != null){
										RBUpdater.updatePage(post, InterstitialController.parameters[instance].update, json);
									}
									
									//if we have a message from the backend
									if(json.response.message){
										params += "&message="+json.response.message;
									}
								
									//if we have a redirect from backend
									if(json.response.redirect){	
										params += "&newUrl="+json.response.redirect;
									}
									
									var paramSep = url.search("\\?") < 0 ? "?" : "&" ;
									
									$.ajax({
										url:url+paramSep+params,
										cache: false,
										dataType:"text",
										type:"GET",
										success:function(html){
											InterstitialController.clearContent();
											InterstitialController.display(html, instance);	
										}
									})
								//this is for semantic errors 
								}else if( json.response.success=="error" ){
								
									url = $("#InterstitialController_error").val();
									var paramSep = url.search("\\?") < 0 ? "?" : "&" ;
									
									$.ajax({
										url:url+paramSep+params,
										cache: false,
										dataType:"text",
										type:"GET",
										success:function(html){
											InterstitialController.clearContent();
											InterstitialController.display(html, instance);	
										}
									})
								
								//this is for server errors
								}else if( json.response.success=="critical" ){
									var copy = {
										title:json.response.title,
										message:json.response.message
									}

									InterstitialController.clearContent();
									InterstitialController.error(copy);								
								}
								
								
								// if url
								if(json.response.url)
								{
									window.document.location	 = json.response.url
								}
								
								// if invalid email
								if(json.response.email)
								{						
									// InterstitialController
									InterstitialController.config(
										{
											instance:"InterstitialFromJavascript",
											trigger:null,
											url:"jsp/interstitial_forgot_password_error.jsp",
											step:{
												success:"jsp/interstitial_forgot_password_success.jsp",
												error:"jsp/interstitial_load_error.jsp"
											},
											type:"error"
										}
									)
									
									// fire interstitial
									$("#InterstitialFromJavascript").trigger('click')
									$("#InterstitialFromJavascript").remove()									
								}
								
								// if invalid email 3rd time
								/*if(json.response.captcha)
								{						
									// InterstitialController
									InterstitialController.config(
										{
											instance:"InterstitialFromJavascript",
											trigger:null,
											url:"jsp/interstitial_forgot_password_captcha.jsp",
											step:{
												success:"jsp/interstitial_forgot_password_success.jsp",
												error:"jsp/interstitial_load_error.jsp"
											},
											type:"error"
										}
									)
									
									// fire interstitial
									$("#InterstitialFromJavascript").trigger('click')
									$("#InterstitialFromJavascript").remove()									
								}	*/																				
							}
						},
						error:function()
						{
							// check for error id
							if($("#InterstitialController_error").length > 0)
							{
								var url = $("#InterstitialController_error").val();
								var instance	= $("#InterstitialController_instance").val();								
								InterstitialController.kill();			
								InterstitialController.step(url, instance, "error");
							}
							else{
								InterstitialController.error(InterstitialController.errormessage.load)
							}
						}
					}
				)				
			}			
		}
	},

	// print
	print:function(form, radio)
	{
		var value = $("input[@name=" + radio + "]:checked");
		CookieClass.set(["print", value])
		this.close();
		print();
	},
	toggleSelects : function(state) {
		state ? $("select").show() : $("select").hide();
	}
}

//==========================================================================================
// COOKIE CLASS
//==========================================================================================
var CookieClass = {
	// cookie name
	_name:"PrintType",
	
	// check cookie
	check:function()
	{
		cookie	= document.cookie.indexOf(this._name + "=");
		if(cookie != -1){
			this.get();
		}
		else{
			this.set(Array(this._name,this._name), 365);	
		}			
	},
	
	// set cookie
	set:function(data, days)
	{
		name	= data[0];
		expire	= this.expire(days);
		for(n = 0; n < data.length; n++)
		{
			data[n] = escape(data[n]);
		}
		document.cookie = name + "=" + data[1] + ";" + ((expire == null) ? "" : ("; expires=" + expire.toGMTString()))			
	},
	
	// get cookie
	get:function()
	{
		data	= document.cookie.split(";");
		
		// fund size
		for(d in data)
		{
			prop	= data[d]
			if(prop.indexOf("size=") != -1)
			{
				// split the paired cookie value
				var print = prop.split("=")[1]
				
				// call your sizing script here
				break;
			}
		}
	},
	
	remove:function()
	{

	},
	
	// expire
	expire:function(days)
	{
		var exp	= new Date(); 
		exp.setTime(exp.getTime() + (exp*24*60*60*1000));
		return exp;
	}		
}

//==========================================================================================
// LOGIN SPECIFIC FUNCTION
//==========================================================================================
var Login = {	
	// services
	services:{
		required:"jsp/interstitial_required_field.jsp",
		failed:"jsp/interstitial_failed_login.jsp",
		submit:"user-login.do"
	},
	
	// from interstitial
	interstitial:false,
	showRequired:false,
	
	// fields
	Fields:function(form)
	{
		Login.id	= form;
		
		// variables
		this.parameters	= {
			form:$(form)	
		}

		// fields
		this.required	= {
			Email:$(form + " #email"),
			Password:$(form + " #password")	
		}
		
		this.errorMessage ={
			Email:"Please provide a valid e-mail address",
			Password:"Please enter a password"
		}

		this.remember	= $(form + " #Remeber");
		this.count		= 0;
	},
	
	// process	
	Process:function(form)
	{
		this.Fields(form)
		
		// set errors
		var error	= false;
		var errors	= Array();
		var post	= {};
		
		// run through form
		for(prop in this.required)
		{
			$(this.required[prop]).css(
				{
					"border":"solid 1px",	
					"border-color":"#8e8e8e #cecece #e3e3e3 #cecece"
				}
			)
						
			this.count++
			var value	= this.required[prop].val();

			// email 
			if(prop.toLowerCase().indexOf("email") != -1)
			{
				if(ValidEmail(value) == false)
				{
					var value = false;
				}
			}
			// assign errors
			if (!value){
				errors.push(prop);
				this.showRequired = true;
				
			}
			else{
				post[prop] = value;
			}
			
			if(value)
			{
				$(this.required[prop]).css(
					{
						border:"none"
					}
				)
			}			
		}

		// if errors
		if(errors.length > 0)
		{
			// run interstial for incomplete
			if (this.showRequired) {
				this.Required(this.services.required, errors);
			}
			else{
				this.interstitial = true;
				this.Failed(this.services.failed);
			}
			//this.Required(this.services.required, errors)
		}
		else
		{
			// run submit
			this.Submit(this.services.submit, post)
		}
	},
	
	Failed:function(url)
	{		
		// vars for InterstitialController
		var instance		= "InterstitialFromJavascript";
		var lightbox		= "#lightbox";
		var form			= lightbox + " form"
		var close			= lightbox + " .close";
		var a				= lightbox + " .message a";
		var button			= lightbox + " #Submit"
			
		
		// InterstitialController
		InterstitialController.config(
			{
				instance:instance,
				trigger:null,
				url:url,
				type:"error"
			}
		)
		
		// fire interstitial
		$("#" + instance).trigger('click')
		$("#" + instance).remove();
		
		// update interstitial
		var listen	= setInterval(
			// listen for lightbox
			function()
			{
				if($(a).length > 0)
				{
					// kill interval
					clearInterval(listen);

					// bind new link attribute
					$(a).bind(
						'click',
						function()
						{
							return false;
						}
					)
					$(a).attr(
						{
							id:"LinkForForgotPasswordFromJavascript"
						}
					)
					// InterstitialController
					InterstitialController.config(
						{
							instance:"LinkForForgotPasswordFromJavascript",
							trigger:"#LinkForForgotPasswordFromJavascript",
							url:"jsp/interstitial_forgot_password.jsp",
							step:{
								success:"jsp/interstitial_forgot_password_success.jsp",
								error:"jsp/interstitial_load_error.jsp"
							},
							type:"error"
						}
					)			

				}
				$(form).attr(
					{
						"interstitial":"DoLogin"
					}
				)				
			},
			100
		)		
		
		// scroll to top
		window.scrollTo(0, 0)			
	},
	
	
	// Required
	Required:function(url, errors)
	{
		// vars for InterstitialController
		var instance		= "InterstitialFromJavascript";
		var lightbox		= "#lightbox";		
		var message			= lightbox + " .fields";
		var form			= lightbox + " form"
		
		var errorText = "Please provide the following required information:";
		
		// InterstitialController
		InterstitialController.config(
			{
				instance:instance,
				trigger:null,
				url:url+"?errorText="+escape(errorText),
				type:"error"
			}
		)
		
		//have to call click twice for enter event
		if( $("#fromEnter").length > 0 ){
			$("#" + instance).trigger('click')  
			$("#fromEnter").remove();
		}
		
		// fire interstitial
		$("#" + instance).trigger('click')
		$("#" + instance).remove();
		
		// update interstitial
		var listen	= setInterval(
			// listen for lightbox
			function()
			{
				if($(message).length > 0)
				{
					// kill interval
					clearInterval(listen);

					$(message).html("")				
					for(error in errors)
					{
						// interstitial

						var p	= $(document.createElement("p"));
						$(p).html( Login.errorMessage[errors[error]] )
						$(p).css(
							{
								padding:0,
								margin:0,
								color:"#000000",
								"font-weight":"bold"
							}
						)
						$(message).append(p)
					}
				}
				$(form).attr(
					{
						"interstitial":"DoLogin"
					}
				)				
			},
			100
		)
		
		// scroll to top
		window.scrollTo(0, 0)			

	},

	// Submit
	Submit:function(url, post, formId)
	{
		/*
			in order to NOT conflict with india's work
			on successful form evaluation
			we instatiate a new Forms() object
			set the init
			and trigger the processForm method
			
			this has been copied from http://bangbasil.sapient.com/pem/user-login.do
		*/
		var id;
		if (formId){
			id = formId;
		}
		else{
			id= "#LoginForm";			
		}
		//set time zone hidden var for Sanjeev
		//create new input if it doesn't exist
		if (!($(id + " #tzOffset").attr("id"))){
			var tzInput = $(document.createElement("input"));
			$(tzInput).attr("type","hidden");
			$(tzInput).attr("id","tzOffset");
			$(tzInput).attr("name","tzOffset");
			$(tzInput).attr("value", new Date().getTimezoneOffset());
		}
		else{
			$(id + " #tzOffset").attr("value", new Date().getTimezoneOffset());
		}
		//add input to end of form
		$(id).append(tzInput);
		
		DoLogin	= new Forms();
		DoLogin.init(
			{
				id:id,
				url:Login.services.submit,
				required:{
					email:"string",
					password:"string"
				}
			}
		)
		DoLogin.processForm('true');
	}
}

//==========================================================================================
// REGISTER SPECIFIC FUNCTION
//==========================================================================================
var Register = {	
	// services
	services:{
		required:"jsp/interstitial_required_field.jsp"
	},
	
	// fields
	Fields:function(form)
	{
		Login.id	= form;
		
		// variables
		this.parameters	= {
			form:$(form)	
		}

		// fields
		this.required	= {
			Email:$(form + " #email"),
			FirstName:$(form + " #firstName"),
			LastName:$(form + " #lastName"),
			StreetAddress1:$(form + " #streetAddress1"),
			City:$(form + " #city"),
			State:$(form + " #state"),
			Zip:$(form + " #zip"),
			Password:$(form + " #password"),
			RePassword:$(form + " #rePassword"),		
			Alias:$(form + " #userName"),	
			Terms:$(form + " #Terms")
		}
		
		// fields
		Register.errorMessages	= {
			Email:"Please provide a valid e-mail address",
			FirstName:"Please enter first name",
			LastName:"Please enter last name",
			StreetAddress1:"Please enter street adress",
			City:"Please enter city",
			State:"Please select a state",
			Zip:"Please provide zip in this format: #####",
			Password:"Please enter password",
			RePassword:"Please enter repassword",		
			PasswordNoMatch:"Your password fields did not match. Please enter your password again.",
			SmallPassword:"Your password must be between 6-20 characters.",
			Alias:"Please enter alias",
			Terms:"You must agree to the Terms of Use, Privacy Policy and Infringments Policy."
		}
		
		// fields
		Register.errorLevels	= {
			Email:1,
			FirstName:1,
			LastName:1,
			StreetAddress1:1,
			City:1,
			State:1,
			Zip:1,
			Alias:1,
			Password:1,
			RePassword:1,		
			PasswordNoMatch:2,
			SmallPassword:2,
			Terms:3
		}

		this.count		= 0;
	},
	
	// process	
	Process:function(form)
	{
		this.Fields(form)
		
		// set errors
		var error	= false;
		var errors	= Array();
		var post	= {};
		var errorLevel = 4;
		var invalidEmailOrZip = false;
		
		// run through form
		for(prop in this.required)
		{
			if($(this.required[prop]).length > 0)
			{
				$(this.required[prop]).css(
					{
						"border":"solid 1px",	
						"border-color":"#8e8e8e #cecece #e3e3e3 #cecece"
					}
				)

				this.count++
				var value	= this.required[prop].val();
				if(this.required[prop].attr("type") == "checkbox")
				{
					if(!this.required[prop].attr("checked"))
					{
						var value = false;
						var terms = true;
					}
				}

				if(prop.toLowerCase().indexOf("email") != -1)
				{
					if(ValidEmail(value) == false)
					{
						var value = false;
						invalidEmailOrZip = true;
					}
				}

				//zip code
				if(prop.toLowerCase().indexOf("zip") != -1)
				{
					if(ValidZip(value) == false)
					{
						var value = false;
						invalidEmailOrZip = true;
					}
				}

				// assign errors
				if(value)
				{
					post[prop] = value
					$(this.required[prop]).css(
						{
							border:"none"
						}
					)
				}else{
					errors.push(prop)
					if(terms && errorLevel>3){ errorLevel = 3 }
					else{	 errorLevel = 1 }
				}				
			}
		}
		if(this.required.Password.val() != null && this.required.Password.val().length > 0)
		{
			if(this.required.Password.val() != this.required.RePassword.val())
			{
				if(errors.length > 1)
				{
					errors.push("PasswordNoMatch")
					for(error in errors)
					{
						if(errors[error].toLowerCase() == "password" || errors[error].toLowerCase() == "repassword")
						{
							delete errors[error];
						}
					}
				}
				else
				{
					var errors = Array("PasswordNoMatch")					
				}			
				if( errorLevel > 2 ){ errorLevel = 2; }	
			}

			if(this.required.Password.val() == this.required.RePassword.val())
			{
				var pw	= this.required.Password.val();
				if(pw.indexOf(" ") != -1 || pw.length < 6 || pw.length > 32)
				{
					if(errors.length > 1)
					{
						errors.push("SmallPassword")
						for(error in errors)
						{
							if(errors[error].toLowerCase() == "password" || errors[error].toLowerCase() == "repassword")
							{
								delete errors[error];
							}
						}
					}
					else
					{
						var errors = Array("SmallPassword")						
					}
					if( errorLevel > 2 ){ errorLevel = 2; }	
				}
			}			
		}
		
		// if errors
		if(errors.length > 0)
		{
			// run interstial for incomplete
			this.Required(this.services.required, errors, errorLevel,invalidEmailOrZip)
		}
		else
		{
			// run submit
			this.Submit(this.services.submit, post)
		}		
	},
	
	// Required
	Required:function(url, errors, errorLevel,invalidEmailOrZip)
	{
		
		// vars for InterstitialController
		var instance		= "InterstitialFromJavascript";
		var lightbox		= "#lightbox";		
		var message			= lightbox + " .fields";

		//this is the explanation text of the interstitial
		switch(errorLevel){
			case 1: 
				var errorText = "Please provide the following required information:";
				var errorHeader = "Oops!"
				break;
			case 2: 
				var errorText = "";
				var errorHeader = "Oops!"
				break;				
			case 3:
				var errorText = "";
				var errorHeader = "Wait!"
				break;
			default:
				var errorText = "Please provide the following required information:";
				var errorHeader = "Oops!"
		}

		// InterstitialController
		InterstitialController.config(
			{
				instance:instance,
				trigger:null,
				url:url+"?errorHeader="+escape(errorHeader)+"&errorText="+escape(errorText)+"&invalidEmailOrZip="+invalidEmailOrZip,
				type:"error"
			}
		)
		
		// fire interstitial
		$("#" + instance).trigger('click')
		$("#" + instance).remove();

		// update interstitial
		var listen	= setInterval(
			// listen for lightbox
			function()
			{
				if($(message).length > 0)
				{
					// kill interval
					clearInterval(listen);

					$(message).html("")				
					for(error in errors)
					{
						
						if( Register.errorLevels[errors[error]]==errorLevel ){
							// interstitial
							var p	= $(document.createElement("p"));
							$(p).html( Register.errorMessages[errors[error]] )
							$(p).css(
								{
									padding:0,
									margin:0,
									color:"#000000",
									"font-weight":"bold"
								}
							)
							$(message).append(p)
						}
					}
				}
			},
			100
		)
		
		// scroll to top
		window.scrollTo(0, 0)		
	},

	// Submit
	Submit:function(url, post)
	{
		/*
			in order to NOT conflict with india's work
			on successful form evaluation
			we instatiate a new Forms() object
			set the init
			and trigger the processForm method
			
			this has been copied from http://bangbasil.sapient.com/pem/user-login.do
		*/	
		DoRegister.processForm('true');			
	}		
	
}

//==========================================================================================
// RECIPE UPLOAD
//==========================================================================================
var RecipeUpload = {
	// services
	services:{
		required:"jsp/interstitial_required_field.jsp",
		quantityInvalid:"jsp/interstitial_invalid_quantity.jsp"
	},
	
	// hide warning
	warnings:".contextError",

	// restrict input
	RestrictKeys:function(myfield, e, restrictionType){	
		var restrictionType = /[0-9\.\/\-/\s]/g;

		if (!e)
		{
			var e = window.event
		}
		if (e.keyCode)
		{
			code = e.keyCode;	
		} 
		else if (e.which)
		{ 
			code = e.which
		};
		
		var character = String.fromCharCode(code);
		if (code==27)
		{
			this.blur();
			return false; 
		}
		if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
			if (character.match(restrictionType))
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	},
	
	// fields
	Fields:function(form)
	{
		Login.id	= form;
		
		// variables
		this.parameters	= {
			form:$(form)	
		}

		// fields
		this.required	= {
			recipeTitle:$(form + " #recipeTitle"),
			prepHours:$(form + " #prepHours"),
			prepMins:$(form + " #prepMins"),			
			cookHours:$(form + " #cookHours"),
			cookMins:$(form + " #cookMins"),			
			noServings:$(form + " #noServings"),
			difficulty:$(form + " #difficulty"),
			"quantity-1":$(form + " #quantity-1"),
			"measurement-1":$(form + " #measurement-1"),
			"ingredient-1":$(form + " #ingredient-1"),
			"step-1":$(form + " #step-1"),
			"mainIngred":$(form + " .mainIngred" ),
			uploadTitle:$(form + " #uploadTitle")	
		}
		
		// error titles
		RecipeUpload.titles = {
			recipeTitle:"Recipe Title",
			prepHours:"Preperation Time",
			prepMins:"Preperation Time",
			cookHours:"Cook Time",
			cookMins:"Cook Time",
			noServings:"Number of Servings",
			difficulty:"Difficulty",
			"quantity-1":"Quantity: Row 1",
			"measurement-1":"Measurements: Row 1",
			"ingredient-1":"Ingredient: Row 1",
			"step-1":"Preperation",
			"mainIngred":"Main Ingredient",
			uploadTitle:"Upload Title"		
		},		

		this.count		= 0;
	},
	
	// process	
	Process:function(form)
	{
		// timer
		var startTime = new Date().getTime()

		
		$(".contextError").hide();		
		
		this.Fields(form)
		
		// set errors
		var error	= false;
		var errors	= Array();
		var quantityError = false;
		var quantityErrors = Array();
		var post	= {};
		
		//add error for missing main ingredient...we'll take it away if we get a main ingredient prop
		var mainIngredIndex = errors.push("mainIngred") - 1;
		
		// run through form
		for(prop in this.required)
		{
			$(this.required[prop]).css(
				{
					"border":"solid 1px",	
					"border-color":"#8e8e8e #cecece #e3e3e3 #cecece"
				}
			)
						
			this.count++
			var value	= this.required[prop].val();
			
			if( !value || value.slice(0, 1) == " ")
			{
				var value	= false;
			}
		
			// assign errors
			if(prop != "prepHours" && prop != "prepMins" && prop != "cookHours" && prop != "cookMins" && prop != "mainIngred" && prop != "quantity-1")
			{
				if(!value){
					//check if field is from row one, if so, need to add quantity-1 to errors stack so that error icon shows
					if (prop == "measurement-1" || prop == "ingredient-1"){
						errors.push("quantity-1");
					}
					errors.push(prop);
				}
				else{
					post[prop] = value;
				}
			}
			
			//---------------------------------------------
			// check valid quantity-1
			//---------------------------------------------		
			if(prop == "quantity-1"){
				// check valid quantity-1
				if(!value)
				{
					//empty quantity-1, push it on errors stack
					errors.push("#quantity-1");
					//#quantity-1 is added for icon to show
					errors.push("quantity-1");
				}
				else{
					//if not empty, check valid value
					var isErrorQuantity = this.ValidateQuantity(value);
					if(isErrorQuantity){
						//push to quantityErrors stack
						quantityErrors.push("quantity-1");					
					}
				}
			}

			//---------------------------------------------
			// main ingredient
			//---------------------------------------------		
			if(prop == "mainIngred"){
				this.required[prop].each( function(){
					if(this.checked){
						if(errors[mainIngredIndex]=="mainIngred"){
							errors.splice(mainIngredIndex,1)
						}
					}
				})
			}
			
			//---------------------------------------------
			// preperation time
			//---------------------------------------------
			// hours
			if(prop == "prepHours")
			{
				// check if minutes
				if(!value)
				{
					if(this.required["prepMins"].val())
					{
						post["prepHours"] = "0";
						post["prepMins"] = this.required["prepMins"].val();
					}
					else{
						errors.push("prepHours")
					}
				}
			}
			// minutes
			if(prop == "prepMins")
			{
				// check if minutes
				if(!value)
				{
					if(this.required["prepHours"].val())
					{
						post["prepHours"] = this.required["prepMins"].val();
						post["prepMins"] = "0";						
					}
					else{
						errors.push("prepHours")
					}
				}
			}
			
			//---------------------------------------------
			// cook time
			//---------------------------------------------
			// hours
			if(prop == "cookHours")
			{
				// check if minutes
				if(!value)
				{
					if(this.required["cookMins"].val())
					{
						post["cookHours"] = "0";
						post["cookMins"] = this.required["cookMins"].val();
					}
					else{
						errors.push("cookHours")
					}
				}
			}
			// minutes
			if(prop == "cookMins")
			{
				// check if minutes
				if(!value)
				{
					if(this.required["cookHours"].val())
					{
						post["cookHours"] = this.required["cookMins"].val();
						post["cookMins"] = "0";						
					}
					else{
						errors.push("cookHours")
					}
				}
			}		
			
		}
		//console.log(quantityErrors);
		// check agains other iterations of quantity
		//----------------------------------------------------		
		var ingredients = [
			"#quantity-",
			"#measurement-",
			"#ingredient-"
		]		
		var rowsToCheck	= Array();
		var rowLength	= $("input[id^='quantity']").length
		for(row = 2; row <= rowLength; row++)
		{
			var add	= false;
			for(col in ingredients)
			{
				var value	= $(form + " " + ingredients[col] + row).val();
				if(value.slice(0, 1) == " ")
				{
					var value	= false;
				}
				if(value)
				{
					add = true
				}
			}
			if(add)
			{
				rowsToCheck.push(row)
			}
		}
		// make sure all required from row are filed
		for(row in rowsToCheck)
		{
			var add = true;
			for(col in ingredients)
			{
				var value	= $(form + " " + ingredients[col] + rowsToCheck[row]).val();
				if(value.slice(0, 1) == " " || value.length < 1)
				{
					var value = false;
				}
				if(!value)
				{
					errors.push(ingredients[col] + rowsToCheck[row])					
					add = false
				}
				//check for valid quantity if not empty
				if ((ingredients[col] == "#quantity-") && ($.trim(value).length > 0)){
					var isErrorQuantity = this.ValidateQuantity($.trim(value));
					if(isErrorQuantity){
						//push to quantityErrors stack
						quantityErrors.push("quantity-" + rowsToCheck[row]);					
					}						
				}
			}
			if(!add)
			{
				errors.push("quantity-" + rowsToCheck[row])
			}
		}		

		
		//----------------------------------------------------
		if(value)
		{
			$(this.required[prop]).css(
				{
					border:"none"
				}
			)
		}		


		// if errors
		if(errors.length > 0)
		{
			// run interstial for incomplete
			errors	= this.TrimArray(errors);
			this.Required(this.services.required, errors);
		}
		else
		{
			if (quantityErrors.length > 0){
				quantityErrors	= this.TrimArray(quantityErrors);
				this.ShowQuantityErrors(this.services.quantityInvalid, quantityErrors);	
			}
			else{
				// run submit
				this.Submit(this.services.submit, post)
				//alert("need to change submit");
			}
		}
	},
	
	TrimArray:function(arr)
	{
		//get sorted array as input and returns the same array without duplicates.
		var result=new Array();
		var lastValue="";
		for (var i=0; i<arr.length; i++)
		{
			var curValue=arr[i];
			isAddable = true;
			for (var j=result.length-1; j > -1; j--){
				if (curValue == result[j])
				{
					isAddable = false;
				}
			}
			if (isAddable){
				result[result.length] = curValue;
			}
		}
		return result;
	},
	
	//validate quantity field
	ValidateQuantity:function(userInput)
	{
		var minString;
		var maxString;

		var error = false;

		var quantity = $.trim(userInput);

		if (quantity.indexOf("-") != -1)
		{
			minString = $.trim(quantity.substring(0, quantity.indexOf("-")));
			maxString = $.trim(quantity.substring(quantity.indexOf("-") + 1));
		}
		else
		{
			minString = quantity;
		}

		if (minString)
		{
			error = this.ValidateQuantityHelper(minString);
		}
		if (maxString)
		{
			error = this.ValidateQuantityHelper(maxString);
		}
		
		return error;	
	},
	
	//quantity validator helper
	ValidateQuantityHelper:function(val)
	{
		var error = false;

		var wholeNum;
		var fraction;
		var numerator;
		var denominator;

		fraction = val;
		if (val.indexOf(" ") != -1)
		{
			wholeNum = val.substring(0, val.indexOf(" "));
			fraction = $.trim(val.substring(val.indexOf(" ") + 1));

			// See if wholeNum is a valid number
			if(!(wholeNum && this.IsInteger(wholeNum))){
				error = true;
			}
		}
		//check for fractions
		if (fraction.indexOf("/") != -1)
		{
			numerator = fraction.substring(0, fraction.indexOf("/"));
			denominator = fraction.substring(fraction.indexOf("/") + 1);

			// See if numerator and denominator are valid numbers
			if(!(numerator && denominator && this.IsInteger(numerator) && this.IsInteger(denominator))){
				error = true;
			}					
		}
		else
		{
			//check for a number real or integer
			if (!val || isNaN(val)){
				error = true;
			}
		}
		return error;
		
	},
	//check a value to see if it is an integer
	IsInteger:function(val){
			var isIntRegExp  = /(^-?\d\d*$)/;
			return isIntRegExp.test(val);
	},
	// Required
	Required:function(url, errors)
	{
		// vars for InterstitialController
		var instance		= "InterstitialFromJavascript";
		var lightbox		= "#lightbox";		
		var message			= lightbox + " .fields";
		
		// InterstitialController
		InterstitialController.config(
			{
				instance:instance,
				trigger:null,
				url:url,
				type:"error"
			}
		)
		
		
		// fire interstitial
		$("#" + instance).trigger('click')
		$("#" + instance).remove();
		
		// update interstitial
		var listen	= setInterval(
			// listen for lightbox
			function()
			{
				if($(message).length > 0)
				{
					// kill interval
					clearInterval(listen);

					$(message).html("")				
					for(error in errors)
					{
						$("#" + errors[error]).parent().parent().find(".contextError").show();
						// interstitial

						var p	= $(document.createElement("p"));


						if(errors[error].indexOf("#quantity-") != -1 || errors[error].indexOf("#measurement-") != -1  || errors[error].indexOf("#ingredient-") != -1 )
						{
							var dash 	= errors[error].indexOf("-");
							var digit	= errors[error].slice(dash + 1, errors[error].length) 
							var elem 	= errors[error].slice(1, dash) + "-1"
							var text 	= RecipeUpload.titles[elem]
							text		= text.slice(0, text.indexOf("Row 1") + 4) + digit
							$(p).html(text)
						}
						else
						{
							if (errors[error] != "quantity-1"){
								$(p).html(RecipeUpload.titles[errors[error]])							
							}
						}
						
						$(p).css(
							{
								padding:0,
								margin:0,
								color:"#000000",
								"font-weight":"bold"
							}
						)
						$(message).append(p)
					}
				}
			},
			100
		)
		
		// scroll to top
		window.scrollTo(0, 0)	
	},

	// Show all invalid Quantities, this fires only if there are no required field validation errors
	ShowQuantityErrors:function(url, errors)
	{
		// vars for InterstitialController
		var instance		= "InterstitialFromJavascript";
		var lightbox		= "#lightbox";		
		
		// InterstitialController
		InterstitialController.config(
			{
				instance:instance,
				trigger:null,
				url:url,
				type:"error"
			}
		)
		
		// fire interstitial
		$("#" + instance).trigger('click')
		$("#" + instance).remove();
		
		// update interstitial
		var listen	= setInterval(
			// listen for lightbox
			function()
			{
				// kill interval
				clearInterval(listen);

				for(error in errors)
				{
					$("#" + errors[error]).parent().parent().find(".contextError").show();
				}
			},
			100
		)
		
		// scroll to top
		window.scrollTo(0, 0)	
	},

	// Submit
	Submit:function(url, post)
	{
		/*
			in order to NOT conflict with india's work
			on successful form evaluation
			we instatiate a new Forms() object
			set the init
			and trigger the processForm method	
		*/	
		//submit the form instead of calling the Forms class.
		$("#uploadRecipe").submit();
		//DoUpload.processForm('true');	
	}		
	
}

//==========================================================================================
// PROFILE SPECIFIC FUNCTION
//==========================================================================================
var Profile = {	
	// services
	services:{
		required:"jsp/interstitial_required_field.jsp"
	},
	
	// fields
	Fields:function(form)
	{
		Login.id	= form;
		
		// variables
		this.parameters	= {
			form:$(form)	
		}

		// fields
		this.required	= {
			FirstName:$(form + " #firstName"),
			LastName:$(form + " #lastName"),
			Alias:$(form + " #alias"),			
			StreetAddress1:$(form + " #streetAddress1"),
			City:$(form + " #city"),
			State:$(form + " #state"),
			Zip:$(form + " #zip")		
		}

		this.count		= 0;
	},
	
	// process	
	Process:function(form)
	{
		this.Fields(form)
		
		// set errors
		var error	= false;
		var errors	= Array();
		var post	= {};
		
		// run through form
		for(prop in this.required)
		{
			$(this.required[prop]).css(
				{
					"border":"solid 1px",	
					"border-color":"#8e8e8e #cecece #e3e3e3 #cecece"
				}
			)
						
			this.count++
			var value	= this.required[prop].val();

			if(value.slice(0, 1) == " ")
			{
				var value	= false;
			}

			// email 
			if(prop.toLowerCase().indexOf("email") != -1)
			{
				if(ValidEmail(value) == false)
				{
					var value = false;
				}
			}
			//zip code
			if(prop.toLowerCase().indexOf("zip") != -1)
			{
				if(ValidZip(value) == false)
				{
					var value = false;
				}
			}
			
			// assign errors
			!value ? errors.push(prop) : post[prop] = value;
			
			if(value)
			{
				$(this.required[prop]).css(
					{
						border:"none"
					}
				)
			}		
		}
		
		// if errors
		if(errors.length > 0)
		{
			// run interstial for incomplete
			this.Required(this.services.required, errors)
		}
		else
		{
			// run submit
			this.Submit(this.services.submit, post)
		}		
	},
	
	// Required
	Required:function(url, errors)
	{
		// vars for InterstitialController
		var instance		= "InterstitialFromJavascript";
		var lightbox		= "#lightbox";		
		var message			= lightbox + " .fields";
		
		// InterstitialController
		InterstitialController.config(
			{
				instance:instance,
				trigger:null,
				url:url,
				type:"error"
			}
		)
		
		// fire interstitial
		$("#" + instance).trigger('click')
		$("#" + instance).remove();
		
		// update interstitial
		var listen	= setInterval(
			// listen for lightbox
			function()
			{
				if($(message).length > 0)
				{
					// kill interval
					clearInterval(listen);

					$(message).html("")				
					for(error in errors)
					{
						// interstitial

						var p	= $(document.createElement("p"));
						$(p).html(errors[error])
						$(p).css(
							{
								padding:0,
								margin:0,
								color:"#000000",
								"font-weight":"bold"
							}
						)
						$(message).append(p)
					}
				}
			},
			100
		)
		
		// scroll to top
		window.scrollTo(0, 0)		
	},

	// Submit
	Submit:function(url, post)
	{
		/*
			in order to NOT conflict with india's work
			on successful form evaluation
			we instatiate a new Forms() object
			set the init
			and trigger the processForm method
			
			this has been copied from http://bangbasil.sapient.com/pem/user-login.do
		*/	
		DoProfile.processForm('true');			
	}		
	
}

var Pswd = {	
	// services
	services:{
		required:"jsp/interstitial_required_field.jsp",
		mismatch:"",
		submit:"offlineService/changePassword.do"
	},
	
	// fields
	Fields:function(form, reset)
	{
		Login.id	= form;
		
		// variables
		this.parameters	= {
			form:$(form)	
		}

		// fields
		if(reset){
			this.required	= {
				Password:$(form + " #password"),
				RePassword:$(form + " #rePassword")
			}
		}else{
			this.required	= {
				CurrentPassword:$(form + " #currentPassword"),
				Password:$(form + " #password"),
				RePassword:$(form + " #rePassword")
			}	
		}


		this.count		= 0;
	},
	
	// process	
	Process:function(form, reset)
	{
		this.Fields(form, reset)
		
		// set errors
		var error	= false;
		var errors	= Array();
		var post	= {};
		
		// run through form
		for(prop in this.required)
		{
			$(this.required[prop]).css(
				{
					"border":"solid 1px",	
					"border-color":"#8e8e8e #cecece #e3e3e3 #cecece"
				}
			)
						
			this.count++
			var value	= this.required[prop].val();

			// email 
			if(prop.toLowerCase().indexOf("email") != -1)
			{
				if(ValidEmail(value) == false)
				{
					var value = false;
				}
			}
			
			// assign errors
			!value ? errors.push(prop) : post[prop] = value;
			
			if(value)
			{
				$(this.required[prop]).css(
					{
						border:"none"
					}
				)
			}
		}
		
		if(this.required.Password.val() != this.required.RePassword.val())
		{
			var errors = Array("The password fields do not match. Please enter it again.")
		}
		
		if(this.required.Password.val() == this.required.RePassword.val())
		{
			var pw	= this.required.Password.val();
			if(pw.indexOf(" ") != -1 || pw.length < 6 || pw.length > 32)
			{
				var errors = Array("Password should be between 6-32 characters, no spaces")
			}
		}
		
		// if errors
		if(errors.length > 0)
		{
			// run interstial for incomplete
			this.Required(this.services.required, errors)
		}
		else
		{
			// run submit
			this.Submit(this.services.submit, post)
		}		
	},
	
	// Required
	Required:function(url, errors)
	{
		// vars for InterstitialController
		var instance		= "InterstitialFromJavascript";
		var lightbox		= "#lightbox";		
		var message			= lightbox + " .fields";
		
		// InterstitialController
		InterstitialController.config(
			{
				instance:instance,
				trigger:null,
				url:url,
				type:"error"
			}
		)
		
		// fire interstitial
		$("#" + instance).trigger('click')
		$("#" + instance).remove();
		
		// update interstitial
		var listen	= setInterval(
			// listen for lightbox
			function()
			{
				if($(message).length > 0)
				{
					// kill interval
					clearInterval(listen);

					$(message).html("")				
					for(error in errors)
					{
						// interstitial

						var p	= $(document.createElement("p"));
						$(p).html(errors[error])
						$(p).css(
							{
								padding:0,
								margin:0,
								color:"#000000",
								"font-weight":"bold"
							}
						)
						$(message).append(p)
					}
				}
			},
			100
		)
		
		// scroll to top
		window.scrollTo(0, 0)		
	},

	// Submit
	Submit:function(url, post)
	{
		/*
			in order to NOT conflict with india's work
			on successful form evaluation
			we instatiate a new Forms() object
			set the init
			and trigger the processForm method
			
			this has been copied from http://bangbasil.sapient.com/pem/user-login.do
		*/
		DoPassword	= new Forms();
		DoPassword.init(
			{
				id:"#PasswordForm",
				url:Pswd.services.submit,
				required:{
				currentPassword:"string",
				password:"string",
				rePassword:"string"
				}		
			}
		)
		DoPassword.processForm('true');
	}	
}

//==========================================================================================
// PROFILE EMAIL SPECIFIC FUNCTION
//==========================================================================================
var EmailForm = {	
	// services
	services:{
		required:"jsp/interstitial_required_field.jsp"
	},
	
	// fields
	Fields:function(form)
	{
		Login.id	= form;
		
		// variables
		this.parameters	= {
			form:$(form)	
		}

		// fields
		this.required	= {
			Email:$(form + " #email")		
		}

		this.count		= 0;
	},
	
	// process	
	Process:function(form)
	{
		this.Fields(form)
		
		// set errors
		var error	= false;
		var errors	= Array();
		var post	= {};
		
		// run through form
		for(prop in this.required)
		{
			$(this.required[prop]).css(
				{
					"border":"solid 1px",	
					"border-color":"#8e8e8e #cecece #e3e3e3 #cecece"
				}
			)
						
			this.count++
			var value	= this.required[prop].val();

			if(value.slice(0, 1) == " ")
			{
				var value	= false;
			}

			// email 
			if(prop.toLowerCase().indexOf("email") != -1)
			{
				if(ValidEmail(value) == false)
				{
					var value = false;
				}
			}
			
			// assign errors
			!value ? errors.push(prop) : post[prop] = value;
			
			if(value)
			{
				$(this.required[prop]).css(
					{
						border:"none"
					}
				)
			}		
		}
		
		// if errors
		if(errors.length > 0)
		{
			// run interstial for incomplete
			this.Required(this.services.required, errors)
		}
		else
		{
			// run submit
			this.Submit(this.services.submit, post)
		}		
	},
	
	// Required
	Required:function(url, errors)
	{
		// vars for InterstitialController
		var instance		= "InterstitialFromJavascript";
		var lightbox		= "#lightbox";		
		var message			= lightbox + " .fields";
		
		// InterstitialController
		InterstitialController.config(
			{
				instance:instance,
				trigger:null,
				url:url,
				type:"error"
			}
		)
		
		// fire interstitial
		$("#" + instance).trigger('click')
		$("#" + instance).remove();
		
		// update interstitial
		var listen	= setInterval(
			// listen for lightbox
			function()
			{
				if($(message).length > 0)
				{
					// kill interval
					clearInterval(listen);

					$(message).html("")				
					for(error in errors)
					{
						// interstitial

						var p	= $(document.createElement("p"));
						$(p).html(errors[error])
						$(p).css(
							{
								padding:0,
								margin:0,
								color:"#000000",
								"font-weight":"bold"
							}
						)
						$(message).append(p)
					}
				}
			},
			100
		)
		
		// scroll to top
		window.scrollTo(0, 0)		
	},

	// Submit
	Submit:function(url, post)
	{
		/*
			in order to NOT conflict with india's work
			on successful form evaluation
			we instatiate a new Forms() object
			set the init
			and trigger the processForm method
			
			this has been copied from http://bangbasil.sapient.com/pem/user-login.do
		*/		
		DoEmail.processForm('true');			
	}		
	
}

//==========================================================================================
// RECIPE TITLE AND CAPTION
//==========================================================================================
var TitleAndCaption = {	
	// services
	services:{
		required:"jsp/interstitial_required_field.jsp"
	},
	
	// fields
	Fields:function(form)
	{
		Login.id	= form;
		
		// variables
		this.parameters	= {
			form:$(form)	
		}

		// fields
		this.required	= {
			uploadTitle:$(form + " #uploadTitle")	
		}

		this.count		= 0;
	},
	
	// process	
	Process:function(form)
	{
		this.Fields(form)
		
		// set errors
		var error	= false;
		var errors	= Array();
		var post	= {};
		
		// run through form
		for(prop in this.required)
		{
			$(this.required[prop]).css(
				{
					"border":"solid 1px",	
					"border-color":"#8e8e8e #cecece #e3e3e3 #cecece"
				}
			)
						
			this.count++
			var value	= this.required[prop].val();

			if(value.slice(0, 1) == " ")
			{
				var value	= false;
			}

			// email 
			if(prop.toLowerCase().indexOf("email") != -1)
			{
				if(ValidEmail(value) == false)
				{
					var value = false;
				}
			}
			//zip code
			if(prop.toLowerCase().indexOf("zip") != -1)
			{
				if(ValidZip(value) == false)
				{
					var value = false;
				}
			}
			
			// assign errors
			!value ? errors.push(prop) : post[prop] = value;
			
			if(value)
			{
				$(this.required[prop]).css(
					{
						border:"none"
					}
				)
			}		
		}
		
		// if errors
		if(errors.length > 0)
		{
			// run interstial for incomplete
			this.Required(this.services.required, errors)
		}
		else
		{
			// run submit
			this.Submit(this.services.submit, post)
		}		
	},
	
	// Required
	Required:function(url, errors)
	{
		// vars for InterstitialController
		var instance		= "InterstitialFromJavascript";
		var lightbox		= "#lightbox";		
		var message			= lightbox + " .fields";
		
		// InterstitialController
		InterstitialController.config(
			{
				instance:instance,
				trigger:null,
				url:url,
				type:"error"
			}
		)
		
		// fire interstitial
		$("#" + instance).trigger('click')
		$("#" + instance).remove();
		
		// update interstitial
		var listen	= setInterval(
			// listen for lightbox
			function()
			{
				if($(message).length > 0)
				{
					// kill interval
					clearInterval(listen);

					$(message).html("")				
					for(error in errors)
					{
						// interstitial

						var p	= $(document.createElement("p"));
						$(p).html(errors[error])
						$(p).css(
							{
								padding:0,
								margin:0,
								color:"#000000",
								"font-weight":"bold"
							}
						)
						$(message).append(p)
					}
				}
			},
			100
		)
		
		// scroll to top
		window.scrollTo(0, 0)		
	},

	// Submit
	Submit:function(url, post)
	{
		/*
			in order to NOT conflict with india's work
			on successful form evaluation
			we instatiate a new Forms() object
			set the init
			and trigger the processForm method
			
			this has been copied from http://bangbasil.sapient.com/pem/user-login.do
		*/		
		DoProfile.processForm('true');			
	}		
	
}

//==========================================================================================
// VALIDATION
//==========================================================================================
function ValidEmail(email)
{
	
	/** commenting out Eugene's code and calling the function written by backend team for email check **/
	/*
	var regex = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i
	return(regex.test(email))
	
	**/
	/* inserting email validation from forms class */
	var entered = email;
	 with (entered)
	 {
		mailChecker =  '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@.-_?+';
		
		for (i=0; i < entered.length; i++)
			if(mailChecker.indexOf(entered.charAt(i)) < 0)
			{
				return false;
			}
			
		apos=entered.indexOf("@");
		lpos=entered.lastIndexOf("@");
		dotpos=entered.lastIndexOf(".");
		lastpos=entered.length-1;
		
		if (apos<1 || (dotpos-apos)<2 || (lastpos-dotpos)>3 || (lastpos-dotpos)<2 || apos != lpos )
		{
			return false;
		}
		else
		{
			return true;
		}
	 }//end with
	
}

function ValidZip(zip) {
   	var regex	 = /^\d{5}([\-]\d{4})?$/;
   	return (regex.test(zip));
}


//==========================================================================================
// TRACKING
//==========================================================================================
Tracking = function(args)
{

	// query string
	var omni_evar 	= "omni_evar=";
	var omni_props 	= "omni_props=";	
	var omni_events = "omni_events=";		
	
	/*
		{
			Evar:
			Prop:
			Event:
		}
	*/
	
	// loop Evar
	if(args.Evar)
	{
		var count		= args.Evar.length;
		var i			= 0;	
		for(prop in args.Evar)
		{
			i++
			omni_evar += "s." + prop + "~" + args.Evar[prop];	
			if(i < count)
			{
				omni_evar += "|"
			}
		}		
	}
	
	// loop Prop
	if(args.Prop)
	{
		var count		= args.Prop.length;
		var i			= 0;
		for(prop in args.Prop)
		{
			i++
			omni_props += "s." + prop + "~" + args.Prop[prop];	
			if(i < count)
			{
				omni_props += "|"
			}
		}		
	}
	
	// loop Event
	if(args.Event)
	{
		var count		= args.Evar.length;
		var i			= 0;	
		for(prop in args.Event)
		{
			i++
			omni_events += "s." + prop + "~" + args.Event[prop];	
			if(i < count)
			{
				omni_events += "|"
			}
		}		
	}
	
	// remove - this is only for logging
	if(window.console && window.console.log)
	{
		console.log(omni_evar)
		console.log(omni_props)
		console.log(omni_events)		
	}
	
	// insert you javascript here
	
}


//==========================================================================================
// THUMBNAIL GENERATOR
//==========================================================================================
var ThumbnailGenerator	= {
	// config
	config:{},
	
	// init
	init:function(args)
	{
		for(prop in args)
		{
			this.config[prop] = args[prop]
		}	
		this.generate();
	},
	
	// generate
	generate:function()
	{
		var count = 0;
		$(this.config.element).each(
			function()
			{
				//IE won't bind properly, but this works fine with FF
				$(this).bind(
						'load',
						function()
						{
							ThumbnailGenerator.resize(this)
						}
					)
				//this is for IE
				ThumbnailGenerator.resize(this)
			}
		)
	},
	
	resize:function(obj)
	{
		//check to make sure obj has loaded
		if (($(obj).width() > 0) && ($(obj).attr("src"))){
			// capture original w and height
			var w		= $(obj).width();
			var h		= $(obj).height();
			
			var ratio	= w/h;
			
			$(obj).css(
				{
					position:"relative",
					height:this.config.height,
					width:this.config.height * ratio
				}
			)
						
			// add new container	
			var div		= $(document.createElement('div'))
			$(div).css(
				{
					margin:"0 0 14px 0",
					border:"solid 1px #CFCFCF",
					width:this.config.width,
					height:this.config.height,
					overflow:"hidden",
					position:"relative"
				}
			)
			
			// border
			var border	= $(document.createElement('div'));
			$(border).css(
				{
					border:"solid 2px #FFFFFF",
					width:this.config.width - 4,
					height:this.config.height - 4,
					position:"relative",
					top:window.ActiveXObject ? -this.config.height : -this.config.height - 3
				}
			)
	
			// clone image
			var dW		= (this.config.width - $(obj).width())/2;
			var dH		= (this.config.height - $(obj).height())/2;

			$(obj).removeClass()
			var clone	= $(obj).clone();
			$(clone).css(
				{
					position:"relative",
					top:dH,
					left:dW
				}
			)
				
			// append them all together
			$(clone).show();
			$(div).append(clone)		
			$(div).append(border)	
			$(obj).after(div)
			
			// remove original image
			$(obj).remove();
		}
		else{
			//hide the image if it is not loaded or not valid
			$(obj).hide();
		}
	}
}


//==========================================================================================
// RECIPEBOX UPDATER
//==========================================================================================
var RBUpdater	= {
	
	CREATE_COLLECTION_UPDATE  : "createCollection",
	DELETE_COLLECTION_UPDATE  : "deleteCollection",
	RENAME_COLLECTION_UPDATE  : "renameCollection",
	ADD_TO_COLLECTION_UPDATE  : "addToCollection",
	DELETE_RECIPE_UPDATE      : "deleteRecipe",
	ADD_TO_COLL_DETAIL_UPDATE : "addToCollDetail",
	
	FAVOURITE_RECIPE	 : "favourite",
	UNFAVOURITE_RECIPE	 : "unfavourite",
	FAVOURITE_RECIPE_TEXT	 : "Favorite",
	UNFAVOURITE_RECIPE_TEXT	 : "Remove from favorites",
	FAVOURITE_CLASS		 : "addfav",
	UNFAVOURITE_CLASS	 : "removefav",
	FAVORITE_ICON_CLASS	 : "icon-fav",
	UNFAVORITE_ICON_CLASS    : "icon-fav-on",
	
	MORE_INGRED_TEXT 	 : "More Ingredients",
	LESS_INGRED_TEXT	 : "Less Ingredients",
	
	CUST_COLLECTION_MENU 	: "#cust-collections-categories",
	SYS_COLLECTION_MENU 	: "#sys-collections-categories",
	CUST_COLLECTION_TABLE 	: "#tbl-rb-collections",
	RECIPE_TABLE		: "#rb-table",
	RECIPE_TABLE_CLONE	: "#rb-table-clone",
	BOOKMARK_TABLE		: "#bookmarkContent",
	
	VIEW_CONTROLLER		: "div.view, div.view-bot",
	PAGINATION_CONTROLLER	: "div.pagination",
	SCROLL_TEXT		: "p.more",
	CONTENT_DIV		: "div.grid-e.clrfix > div.clrfix",
	
	
	updatePage : function(post_vars, update_function, json){
		switch(update_function){
			case RBUpdater.CREATE_COLLECTION_UPDATE:
				RBUpdater.addCustomCollection(post_vars["collectionName"], json.response.id, json.response.href, json.response.num);
				break;
				
			case RBUpdater.DELETE_COLLECTION_UPDATE:
				RBUpdater.removeCustomCollection(post_vars["id"]);
				break;
				
			case RBUpdater.RENAME_COLLECTION_UPDATE:
				RBUpdater.renameCustomCollection( post_vars["id"], post_vars["collectionName"], json.response.num );
				break;
				
			case RBUpdater.ADD_TO_COLLECTION_UPDATE:
				RBUpdater.addToCollection( json.response.successID, post_vars["id"], false );
				break;
				
			case RBUpdater.DELETE_RECIPE_UPDATE:
				RBUpdater.deleteFromBox( post_vars["id"], json.response.deleteID, post_vars["boxDelete"] );
				break;
				
			case RBUpdater.ADD_TO_COLL_DETAIL_UPDATE:
				RBUpdater.addToCollection( json.response.successID, post_vars["id"], true );
				break;
		}	
	},
	
	addCustomCollection : function(name, id, href, num){
		//add to left hand pane
		var text = "<li id=\""+name+"\" class=\"action allowDrop ui-droppable\" title=\""+name+"\" rel=\""+id+"\">"
				+"<a href=\""+href+"\"><span><em>"+name+" <b>("+num+")</b></em></span></a>"
			  +"</li>"
		
		$(RBUpdater.CUST_COLLECTION_MENU+" .collapsable").append(text);
		
		//add event listener for dropping
		RBUpdater.addDropEvent("li.allowDrop[rel='"+id+"']");
		
		//find out which instances of InterstitialController rename/delete are for
		var deleteTrigger = "";
		var renameTrigger = "";
		
		for( instance in InterstitialController.parameters ){
			if( InterstitialController.parameters[instance].update == RBUpdater.DELETE_COLLECTION_UPDATE ){
				deleteTrigger = instance;
			}

			if( InterstitialController.parameters[instance].update == RBUpdater.RENAME_COLLECTION_UPDATE ){
				renameTrigger = instance;			
			}			
		}
		
		//add to table
		var d = new Date();
		
		$(RBUpdater.CUST_COLLECTION_TABLE+" tbody").append(
				"<tr id=\""+id+"\" >"+
					"<th>"+name+"</th>"+
					"<td>"+d.format("longDate")+"</td>"+
					"<td class=\"numRecipes\">"+num+"</td>"+
					"<td>"+
						"<ul>"+
							"<li>"+
								"<a class=\"dialoglink link-renameCol\" params=\"oldName="+name+"\" rel=\""+id+"\" title=\""+name+"\" href=\""+name+"\" trigger=\""+renameTrigger+"\">Rename</a>"+
							"</li>"+
							"<li class=\"last\">"+
								"<a class=\"dialoglink link-deleteCol\" rel=\""+id+"\" title=\""+name+"\" href=\""+name+"\" trigger=\""+deleteTrigger+"\">Remove</a>"+
							"</li>"+
						"</ul>"+
					"</td>"+
				"</tr>"
		);
		
		//add rename on click
		$(RBUpdater.CUST_COLLECTION_TABLE+" #"+id+" th").click(function(){
			showRenameTextBox(id, name);
		});		

		//config delete element
		$(RBUpdater.CUST_COLLECTION_TABLE+" #"+id+" .link-deleteCol").click( function(event){
			event.preventDefault();
			
			var trigger = $(this).attr("trigger");
			var object = InterstitialController.parameters[trigger];
			object["paramString"] = $(this).attr("params");
			object["params"]={};
			object["params"]["id"] = $(this).attr("rel");
			object["params"]["name"] = $(this).attr("title");
			InterstitialController.getParams( object["params"], $(this).attr("params") );
			InterstitialController.open(this);
		});				

		//config rename element
		$(RBUpdater.CUST_COLLECTION_TABLE+" #"+id+" .link-renameCol").click(function(event){
			event.preventDefault();
			
			var trigger = $(this).attr("trigger");
			var object = InterstitialController.parameters[trigger];
			object["paramString"] = $(this).attr("params");
			object["params"]={};
			object["params"]["id"] = $(this).attr("rel");
			object["params"]["name"] = $(this).attr("title");
			InterstitialController.getParams( object["params"], $(this).attr("params") );
			InterstitialController.open(this);
		});
		
		
		//add hover state to the row
		$("#tbl-rb-collections tbody tr[id='"+id+"']").hover(
			function(){
				$(this).addClass("over");
			},
			function(){
				$(this).removeClass("over");
				
			}
		);
		
		//remove prompt text to create custom collection (if exists)
		$("#rbmenu div.empty.bottom").remove();

	},
	
	removeCustomCollection : function(id){
		//remove from left-hand pane
		//$(RBUpdater.CUST_COLLECTION_MENU+ " [rel="+id+"]").remove();
		
		var newElem = "";
		
		$(RBUpdater.CUST_COLLECTION_MENU+" li").each(function(i){
			if( $(this).attr("rel") != id ){
				var html = $(this).html();
				var newid = $(this).attr("id") ? ("id=\""+$(this).attr("id")+"\"") : "" ;
				var classes = $(this).attr("class") ? ("class=\""+$(this).attr("class")+"\"") : "" ;
				var title = $(this).attr("title") ? ("title=\""+$(this).attr("title")+"\"") : "" ;
				var rel = $(this).attr("rel") ? ("rel=\""+$(this).attr("rel")+"\"") : "" ;
				
				var attribs = newid+" "+classes+" "+title+" "+rel;
				
				newElem += "<li "+attribs+">"+html+"</li>";
			}
		});
		
		$(RBUpdater.CUST_COLLECTION_MENU).empty();
		$(RBUpdater.CUST_COLLECTION_MENU).html(newElem);
		
		//remove from main table
		$(RBUpdater.CUST_COLLECTION_TABLE+" #"+id).remove();
	},
	
	renameCustomCollection : function( id, name, num ){
		//rename in left-hand pane
		$(RBUpdater.CUST_COLLECTION_MENU+ " [rel="+id+"] a span em").remove();
		$(RBUpdater.CUST_COLLECTION_MENU+ " [rel="+id+"] a span").append("<em>"+name +" <b>("+num+")</b></em>");
		$(RBUpdater.CUST_COLLECTION_MENU+ " [rel="+id+"]").attr("title", name);
		$(RBUpdater.CUST_COLLECTION_MENU+ " [rel="+id+"] a").attr("href", "recipeBox.do?collectionName="+encodeURI(name) );
		
		//rename in main table
		$(RBUpdater.CUST_COLLECTION_TABLE+" #"+id+" th").remove();
		$(RBUpdater.CUST_COLLECTION_TABLE+" #"+id).prepend("<th>"+name+"</th>");
		$(RBUpdater.CUST_COLLECTION_TABLE+" #"+id+" .link-deleteCol").attr("title",name);
		$(RBUpdater.CUST_COLLECTION_TABLE+" #"+id+" .link-deleteCol").attr("href",name);
		$(RBUpdater.CUST_COLLECTION_TABLE+" #"+id+" .link-renameCol").attr("title",name);
		$(RBUpdater.CUST_COLLECTION_TABLE+" #"+id+" .link-renameCol").attr("href",name);
		$(RBUpdater.CUST_COLLECTION_TABLE+" #"+id+" .link-renameCol").attr("params","oldName="+name);
		
		//add click event to header
		$(RBUpdater.CUST_COLLECTION_TABLE+" #"+id+" th").click( function(){
			showRenameTextBox(id, name);
		})
	},
	
	changeFavourite : function( favouriteChoice, recipeID, targetLink, targetIcon, inFav ){		
		//change the count on the left-hand pane
		var curText = $("#favorites em").text();
		curText = curText.split("(")[1].split(")")[0];
		curText = parseInt(curText) + (favouriteChoice == RBUpdater.FAVOURITE_RECIPE ? 1 : -1); 
		
		$("#favorites em").text("Favorites ("+curText+")");
		
		//change the CTA
		if( targetLink==null ){	
			targetLink = favouriteChoice==RBUpdater.FAVOURITE_RECIPE ? $(".rb-results-clone li.addfav[rel="+recipeID+"] a") : $(".rb-results-clone li.removefav[rel="+recipeID+"] a") ;
		
		}
		
		if(targetLink.text() == RBUpdater.UNFAVOURITE_RECIPE_TEXT){ 
			var newText = RBUpdater.FAVOURITE_RECIPE_TEXT;
			var newClass = RBUpdater.FAVOURITE_CLASS;
		}
		else{ 
			var newText = RBUpdater.UNFAVOURITE_RECIPE_TEXT;
			var newClass = RBUpdater.UNFAVOURITE_CLASS;
		}
		
		targetLink.text(newText);
		targetLink.parent().removeClass();
		targetLink.parent().addClass(newClass);
		
		
		//change the favourite icon
		var iconClass = favouriteChoice==RBUpdater.FAVOURITE_RECIPE ? "."+RBUpdater.FAVORITE_ICON_CLASS : "."+RBUpdater.UNFAVORITE_ICON_CLASS;
		var newClass = favouriteChoice==RBUpdater.FAVOURITE_RECIPE ? RBUpdater.UNFAVORITE_ICON_CLASS : RBUpdater.FAVORITE_ICON_CLASS;
		
		if( targetIcon==null ){	targetIcon = $("a"+iconClass+"[rel="+recipeID+"]");}
		targetIcon.attr("class", newClass);
		
		//remove recipe from the main table if needed
		if( inFav && favouriteChoice==RBUpdater.UNFAVOURITE_RECIPE ){
			$(RBUpdater.RECIPE_TABLE+" tr[rel="+recipeID+"]").remove();
			$(RBUpdater.RECIPE_TABLE_CLONE+" tr[rel="+recipeID+"]").remove();			
		}
	},
	
	addToCollection : function ( id, recipeID, RBDetailUpdate ){
		
		//find id of favourite collection
		var favID = $("#favorites", document).attr("rel");
		
		id = id.split(",");	
		
		//change count for each 
		for( x=0; x<id.length; x++ ){
			//if it's a favourite collection
			if( id[x]==favID ){ 
				if( RBDetailUpdate ){ RBDetailUpdater.changeFavourite( RBDetailUpdater.FAVOURITE_RECIPE, recipeID, null ); }
				else{	RBUpdater.changeFavourite( RBUpdater.FAVOURITE_RECIPE, recipeID, null ); }
			}
			else{
				var curText = $(RBUpdater.CUST_COLLECTION_MENU+ " [rel="+id[x]+"] em").text();
				var name = curText.split("(")[0];
				curText = curText.split("(")[1].split(")")[0];
				curText = parseInt(curText) + 1;
				$(RBUpdater.CUST_COLLECTION_MENU+ " [rel="+id[x]+"] em").text(name+"("+curText+")");
			}
		}
	},
	
	deleteFromBox : function ( id, collections, deleteBox ){
		//remove from main table (if exists)
		$(RBUpdater.RECIPE_TABLE+" tr[rel="+id+"]").remove();
		$(RBUpdater.RECIPE_TABLE_CLONE+" tr[rel="+id+"]").remove();
		
		//remove from bookmarks table (if exists)
		$(RBUpdater.BOOKMARK_TABLE+" .recipe[rel="+id+"]").remove();
		
		//remove from left hand pane
		collections = collections.split(",");
		for( x=0; x<collections.length; x++ ){
			RBUpdater.deleteFromCollection( collections[x] );
		}
		
		if( deleteBox=="true" ){
			//remove from all recipes count
			var curText = $("#all-recipes-hdr em").text();
			if(curText.length > 0){
				var name = curText.split("(")[0];
				curText = curText.split("(")[1].split(")")[0];
				curText = parseInt(curText) - 1;
				$("#all-recipes-hdr em").text(name+"("+curText+")");	
			}
		}
	},
	
	deleteFromCollection : function( id ){
		if(id.length < 1){ return false;}
		
		var sysCol = false;
		var curText = $(RBUpdater.CUST_COLLECTION_MENU+ " [rel="+id+"] em").text();
		
		//if the id is not in custom collections, it must be in system collections
		if( !curText ){
			curText = $(RBUpdater.SYS_COLLECTION_MENU+ " [rel="+id+"] em").text();
			sysCol = true;
		}
	
		if(curText.length > 0){
			var name = curText.split("(")[0];
			curText = curText.split("(")[1].split(")")[0];
			curText = parseInt(curText) - 1;
		
			if( sysCol ){
				$(RBUpdater.SYS_COLLECTION_MENU+ " [rel="+id+"] em").text(name+"("+curText+")");
				var collectionDiv = RBUpdater.SYS_COLLECTION_MENU;
			} else {
				$(RBUpdater.CUST_COLLECTION_MENU+ " [rel="+id+"] em").text(name+"("+curText+")");
				var collectionDiv = RBUpdater.CUST_COLLECTION_MENU;
			}
			
			//find out if the id we're deleting from is the currently selected collection
			var curCollection = $(collectionDiv+" span li.on[rel="+id+"]").length > 0 ? true : false;
			
			//if there are no recipes left in the currently selected collection, we must change the text
			if( curText == "0" && curCollection && $(RBUpdater.CONTENT_DIV+" #emptyText").length < 1 ){
				$(RBUpdater.RECIPE_TABLE).hide();
				$(RBUpdater.RECIPE_TABLE_CLONE).hide();
				$(RBUpdater.VIEW_CONTROLLER).hide();
				$(RBUpdater.PAGINATION_CONTROLLER).hide();
				$(RBUpdater.SCROLL_TEXT).hide();
				$(RBUpdater.CONTENT_DIV).append("<h1 id=\"emptyText\">This collection is empty. Go ahead and add some recipes to it or delete it</h1>");
			}
		}
	},
	
	
	handleMoreIngredients : function( e ){
		//set local vars
		var ingredElem = $(e.target).parents("div").children(".ingredients");

		//perform appropriate action
		if( $(e.target).parent("div").children("span").html() == RBUpdater.MORE_INGRED_TEXT ){

			$(e.target).parent("div").children("img").attr({"src":"images/icn-less-ingredients.gif"});
			ingredElem.css("height", "auto");
			$(e.target).parent("div").children("span").html(RBUpdater.LESS_INGRED_TEXT);
		} else {

			$(e.target).parent("div").children("img").attr({"src":"images/icn-more-ingredients.gif"});
			ingredElem.css("height", "" );
			$(e.target).parent("div").children("span").html(RBUpdater.MORE_INGRED_TEXT);
		}
		
		Table._updateClone($(e.target).parents("tr").attr("id"))
	},
	
	
	
	addDropEvent : function( target ){
		// droppable
		$(target).droppable({
			accept: function(draggable) {
				return $(draggable).children();
			},
			tolerance:"pointer",
			over: function(ev, ui)
			{
				$("#recipe-drag-box").append("<img class=\"drag-plus\" src=\"images/drag-plus.png\" />");
			},
			out: function(ev, ui)
			{
				$("#recipe-drag-box .drag-plus").remove();								
			},
			drop: function(ev, ui)
			{				
				// send data
				var _id		= $("#recipe-drag-box").attr("value");					
				var _bucket	= $(this).attr("id");
				var _cId	= $(this).attr("rel");

				var args	= {
					recipe_id: _id,
					bucket: _bucket,
					collectionID : _cId,
					action : jQuery.pem.RECIPE_DRAG_COLLECTION
				}

				$.ajax({
					url: "addRecipe.do",
					cache: false,
					data: args,
					dataType: "json",
					type:"POST", 
					success:function(json){
						switch(json.response.success){
							case "success":
								var post = {"id":_id};
								RBUpdater.updatePage(post, RBUpdater.ADD_TO_COLLECTION_UPDATE, json);
								break;
							case "error":									

								break;
							case "critical":
								var copy = {
									title:json.response.title,
									message:json.response.message
								}

								InterstitialController.clearContent();
								InterstitialController.error(copy);
								break;
						}
					},
					error:function(json) {								
						window.location = "exceptionController.do";
					}							
				});												
			}//end of drop function
		})	
	}//end of addDropEvent
	
	
}//end of RBUpdater





//==========================================================================================
// RECIPEBOX DETAIL UPDATER
//==========================================================================================
var RBDetailUpdater	= {

	FAV_ICON_ID		: "favIcon",	
	FAVOURITE_RECIPE 	: "favourite",
	UNFAVOURITE_RECIPE 	: "unfavourite",
	FAVOURITE_ICON 		: "images/icn_heart.gif",
	UNFAVOURITE_ICON 	: "images/icons/icn-no-heart.gif",
	FAVOURITE_CLASS		: "icn-fav-lg",
	UNFAVOURITE_CLASS	: "icn-unfav-lg",
	
	CHOICE_PRIVATE		: "makePrivate",
	CHOICE_PUBLIC		: "makePublic",
	TOGGLE_PRIV_SERVICE	: "offlineService/togglePrivate.do",
	MAKE_PUBLIC_CLASS	: "icn-public-lg",
	MAKE_PRIVATE_CLASS	: "icn-private-lg",
	
	SOURCE_ICON		: "icon",
	SOURCE_LINK		: "link",

	changeFavClick : function(e, source){
		//set local vars
		var theElem = $(e.target);
		var id = theElem.attr("rel");
		var title = theElem.attr("title");

		if( source=="icon" ){
			var choice = theElem.attr("src")==RBDetailUpdater.FAVOURITE_ICON ? RBDetailUpdater.UNFAVOURITE_RECIPE : RBDetailUpdater.FAVOURITE_RECIPE ;
		}else{
			var choice = theElem.attr("class")==RBDetailUpdater.FAVOURITE_CLASS ? RBDetailUpdater.FAVOURITE_RECIPE : RBDetailUpdater.UNFAVOURITE_RECIPE;
		}

		if(choice == RBDetailUpdater.FAVOURITE_RECIPE){
			var action = "add";
			var favouriteServiceURL = "offlineService/addToFavouriteSuccess.do";
		} else {
			var action = "remove";
			var favouriteServiceURL = "offlineService/addToFavouriteSuccess.do";
		}

		// make ajax call
		$.ajax({
			url: favouriteServiceURL,
			cache: false,
			data:{ "id": id, "title":title, "action":action },
			dataType:"json",
			type:"POST",
			success:function(json){

				if(json.response.success == "success"){
					//update the recipe box
					if( source=="icon" ){
						RBDetailUpdater.changeFavourite(choice, id, null, theElem);
					}else{
						RBDetailUpdater.changeFavourite(choice, id, theElem, null);
					}
				}
			}
		})

		return false;
	},
	
	changeFavourite : function( favouriteChoice, recipeID, targetLink, targetIcon ){		
		//change the count on the left-hand pane
		var curText = $("#favorites em").text();
		if(curText.length > 0){
			curText = curText.split("(")[1].split(")")[0];
			curText = parseInt(curText) + (favouriteChoice == RBDetailUpdater.FAVOURITE_RECIPE ? 1 : -1); 
		
			$("#favorites em").text("Favorites ("+curText+")");
		}
		
		//change the favourite icon
		var newIcon = favouriteChoice==RBDetailUpdater.FAVOURITE_RECIPE ? RBDetailUpdater.FAVOURITE_ICON : RBDetailUpdater.UNFAVOURITE_ICON;

		if( targetIcon==null ){	targetIcon = $("#"+RBDetailUpdater.FAV_ICON_ID);}
		targetIcon.attr("src", newIcon);
		
		
		//change the CTA
		var oldClass = favouriteChoice==RBDetailUpdater.FAVOURITE_RECIPE ? RBDetailUpdater.FAVOURITE_CLASS : RBDetailUpdater.UNFAVOURITE_CLASS;
		var newClass = favouriteChoice==RBDetailUpdater.FAVOURITE_RECIPE ? RBDetailUpdater.UNFAVOURITE_CLASS : RBDetailUpdater.FAVOURITE_CLASS;
	
		if( targetLink==null ){	targetLink = $("a."+oldClass);}
	
		if(targetLink.text() == RBUpdater.UNFAVOURITE_RECIPE_TEXT){ var newText = RBUpdater.FAVOURITE_RECIPE_TEXT;}
		else{ var newText = RBUpdater.UNFAVOURITE_RECIPE_TEXT;}
		
		targetLink.text(newText);
		targetLink.removeClass(oldClass);
		targetLink.addClass(newClass);
	},
	
	
	togglePrivate : function( e, choice ){
	
		var theElem = $(e.target);
		var recipeID = theElem.attr("rel");
		var title = theElem.attr("title");
	
		// make ajax call
		$.ajax({
			url: RBDetailUpdater.TOGGLE_PRIV_SERVICE,
			cache: false,
			data:{ "id": recipeID, "action":choice, "collection":title },
			dataType:"json",
			type:"POST",
			success:function(json){

				if(json.response.success == "success"){
					window.location = json.response.url;
				}else{
					var copy = {
						title:json.response.title,
						message:json.response.message
					}
					InterstitialController.clearContent();
					InterstitialController.error(copy);				
				}
			}
		})		
	},	
	
	
	
	addToBox : function ( id, title ){
		//build new list of CTAs
		CTAString = "<ul>";
		CTAString +="	<li><a href=\"#\" class=\"icn-print\" id=\"PrintDetails\">Print</a></li>";
		CTAString +="	<li><a href=\"#\" class=\"deleteRecipe icn-delete-lg\" rel=\""+id+"\" id=\"DeleteRecipe\" title=\""+title+"\" params=\"collectionName=customCollectionName\">Delete</a></li>";
		CTAString +="	<li><a href=\"#\" class=\"icn-fav-lg\" rel=\"001\">Add to Favorites</a></li>";
		CTAString +="</ul>";

		CTAString +="<ul>";
		CTAString +="	<li><a href=\"#\" class=\"btn-addto\" rel=\""+id+"\" title=\""+title+"\">Add to collection</a></li>";
		CTAString +="</ul>";	
		
		//add to page
		$(".ctaHolder-public").html(CTAString);
		
		
		//add the heart icon beside the title
		var headerString = "<img src=\""+RBDetailUpdater.UNFAVOURITE_ICON+"\" alt=\"[FAVORITE]\" id=\"favIcon\" rel=\""+id+"\" />"+title;
		$("#rb-detailp div h2").html(headerString);
		
		
		//bind links and what not
		InterstitialController.config({
			instance:"PrintDetails",
			trigger:"#PrintDetails",
			url:"jsp/interstitial_print_details.jsp"
		})
		
		InterstitialController.config({
			instance:"DeleteRecipe",
			trigger:"#DeleteRecipe",
			url:"jsp/interstitial_recipe_delete_from_recipe_box.jsp",
			step:{
				success:"jsp/interstitial_recipe_delete_from_recipe_box_success.jsp",
				error:"jsp/interstitial_load_error.jsp"
			},
			update: RBUpdater.DELETE_RECIPE_UPDATE
		})


		InterstitialController.config({
			instance:"AddRecipeToCollection",
			trigger:".btn-addto",
			url:"jsp/interstitial_add_recipe_to_collection.jsp",
			step:{
				success:"jsp/interstitial_add_recipe_to_collection_success.jsp",
				error:"jsp/interstitial_load_error.jsp"
			},
			update: RBUpdater.ADD_TO_COLL_DETAIL_UPDATE
		})
		
		//this code is to fav/unfav
		$("#favIcon").click( function(e) { RBDetailUpdater.changeFavClick(e, RBDetailUpdater.SOURCE_ICON); });
		$("a."+RBDetailUpdater.UNFAVOURITE_CLASS).click( function(e) { RBDetailUpdater.changeFavClick(e, RBDetailUpdater.SOURCE_LINK); });
		$("a."+RBDetailUpdater.FAVOURITE_CLASS).click( function(e) { RBDetailUpdater.changeFavClick(e, RBDetailUpdater.SOURCE_LINK); });

		//put the proper text in the favourite CTAs
		$("a."+RBDetailUpdater.UNFAVOURITE_CLASS).text(RBUpdater.UNFAVOURITE_RECIPE_TEXT);
		$("a."+RBDetailUpdater.FAVOURITE_CLASS).text(RBUpdater.FAVOURITE_RECIPE_TEXT);
	}

}//end of RBDetailUpdater












//==========================================================================================
// SEARCH
//==========================================================================================
$(document).ready(
	function()
	{
		var SearchBarText	= {
			Inside:"Search inside the box",
			Outside:"Search outside the box"
		}
		
		$("#searchText").val(SearchBarText[$("input[@name=searchType]:checked").val()]);
		
		$("input[@name=searchType]").bind(
			'click',
			function()
			{
				if($("#searchText").val() == SearchBarText.Outside || $("#searchText").val() == SearchBarText.Inside || $("#searchText").val() == "")
				{
					$("#searchText").val(SearchBarText[$("input[@name=searchType]:checked").val()]);					
				}
			}
		)
		
		$("#searchText").bind(
			'focus',
			function()
			{
				if($("#searchText").val() == SearchBarText.Outside || $("#searchText").val() == SearchBarText.Inside)
				{
					$("#searchText").val("");				
				}				
			}
		)
		
		$("#searchText").focus( function(){
			this.focused=true;
		});
		
		$("#searchText").blur( function(){
			this.focused=false;
		});
		
		$(document).bind(
			'keypress',
			function(key)
			{
				if(key.which == 13)
				{
					if( $("#searchText").length > 0 && $("#searchText")[0].focused ){
						$("#searchButton").click();
					}
					
					return false;
				}
			}
		)
		
	}
)

/* Starting HomeBase Image Rotation*/
var rand1 = 0;
var useRand = 0;

images = new Array;
images[1] = new Image();
images[1].src = "images/grp-homebase1.jpg";
images[2] = new Image();
images[2].src = "images/grp-homebase2.jpg";
images[3] = new Image();
images[3].src = "images/grp-homebase3.jpg";
images[4] = new Image();
images[4].src = "images/grp-homebase4.jpg";
images[5] = new Image();
images[5].src = "images/grp-homebase5.jpg";
images[6] = new Image();
images[6].src = "images/grp-homebase6.jpg";
images[7] = new Image();
images[7].src = "images/grp-homebase7.jpg";
images[8] = new Image();
images[8].src = "images/grp-homebase8.jpg";
images[9] = new Image();
images[9].src = "images/grp-homebase9.jpg";
images[10] = new Image();
images[10].src = "images/grp-homebase10.jpg";
images[11] = new Image();
images[11].src = "images/grp-homebase11.jpg";
images[12] = new Image();
images[12].src = "images/grp-homebase12.jpg";
images[13] = new Image();
images[13].src = "images/grp-homebase13.jpg";
images[14] = new Image();
images[14].src = "images/grp-homebase14.jpg";
images[15] = new Image();
images[15].src = "images/grp-homebase15.jpg";
images[16] = new Image();
images[16].src = "images/grp-homebase16.jpg";
images[17] = new Image();
images[17].src = "images/grp-homebase17.jpg";
images[18] = new Image();
images[18].src = "images/grp-homebase18.jpg";

/*
images[16] = new Image();
images[16].src = "images/grp-homebase16.jpg";
images[17] = new Image();
images[17].src = "images/grp-homebase17.jpg";
images[18] = new Image();
images[18].src = "images/grp-homebase18.jpg";
*/

function swapPic() 
{
	var imgnum = images.length - 1;
	do
	{
		var randnum = Math.random();
		rand1 = Math.round((imgnum - 1) * randnum) + 1;
	} 
	while (rand1 == useRand)
	{
		document.randimg.setAttribute("id", document.randimg.name)
		var id	= document.randimg.id
		
		$("#" + id).hide();
		$("#" + id).bind(
			'load',
			function()
			{	
				var delta	= $("div.clrfix").height() - $(this).height();
				if(jQuery.browser.msie) delta = delta - 16; 
				$(this).css(
					{
						position:"relative",
						top:delta + "px"
					}
				)
//				alert("delta : "+delta + "\n Image : " + $(this).height() + "\n Parent Height : " + $(this).parent().height() )
				$(this).fadeIn();
			}
		)
		
		useRand = rand1;
		document.randimg.src = images[useRand].src;		
	}
}


var rand2 = 0;
var useRand1 = 0;

images1 = new Array;
images1[0] = new Image();
images1[0].src = "images/DYK_HP_1a.gif";
images1[1] = new Image();
images1[1].src = "images/DYK_HP_1b.gif";
images1[2] = new Image();
images1[2].src = "images/DYK_HP_1c.gif";
images1[3] = new Image();
images1[3].src = "images/DYK_HP_1d.gif";
images1[4] = new Image();
images1[4].src = "images/DYK_HP_2a.gif";
images1[5] = new Image();
images1[5].src = "images/DYK_HP_2b.gif";
images1[6] = new Image();
images1[6].src = "images/DYK_HP_2c.gif";
images1[7] = new Image();
images1[7].src = "images/DYK_HP_2d.gif";
images1[8] = new Image();
images1[8].src = "images/DYK_HP_2e.gif";
images1[9] = new Image();
images1[9].src = "images/DYK_HP_2f.gif";

/* COMMENTED OUT FOR 11/18

images1[10] = new Image();
images1[10].src = "images/DYK_HP_3a.gif";
images1[11] = new Image();
images1[11].src = "images/DYK_HP_3b.gif";
images1[12] = new Image();
images1[12].src = "images/DYK_HP_3c.gif";
images1[13] = new Image();
images1[13].src = "images/DYK_HP_3d.gif";
images1[14] = new Image();
images1[14].src = "images/DYK_HP_3e.gif";
images1[15] = new Image();
images1[15].src = "images/DYK_HP_3f.gif";
images1[16] = new Image();
images1[16].src = "images/DYK_HP_3g.gif";

*/

images1[17] = new Image();
images1[17].src = "images/DYK_HP_4a.gif";
images1[18] = new Image();
images1[18].src = "images/DYK_HP_4b.gif";
images1[19] = new Image();
images1[19].src = "images/DYK_HP_4c.gif";
images1[20] = new Image();
images1[20].src = "images/DYK_HP_4d.gif";
images1[21] = new Image();
images1[21].src = "images/DYK_HP_4e.gif";
images1[22] = new Image();
images1[22].src = "images/DYK_HP_4f.gif";
images1[23] = new Image();
images1[23].src = "images/DYK_HP_5a.gif";
images1[24] = new Image();
images1[24].src = "images/DYK_HP_5b.gif";
images1[25] = new Image();
images1[25].src = "images/DYK_HP_5c.gif";
images1[26] = new Image();
images1[26].src = "images/DYK_HP_5d.gif";
images1[27] = new Image();
images1[27].src = "images/DYK_HP_5e.gif";
images1[28] = new Image();
images1[28].src = "images/DYK_HP_5f.gif";
images1[29] = new Image();
images1[29].src = "images/DYK_HP_5g.gif";
images1[30] = new Image();
images1[30].src = "images/DYK_HP_6a.gif";
images1[31] = new Image();
images1[31].src = "images/DYK_HP_6b.gif";
images1[32] = new Image();
images1[32].src = "images/DYK_HP_7a.gif";
images1[33] = new Image();
images1[33].src = "images/DYK_HP_7b.gif";
images1[34] = new Image();
images1[34].src = "images/DYK_HP_7c.gif";


function swapPic1() {
	var imgnum1 = images1.length - 1;
	do 
	{
		var randnum1 = Math.random();
		rand2 = Math.round((imgnum1 - 1) * randnum1) + 1;
	} 
	while (rand2 == useRand1)
	{
		useRand1 = rand2;
		document.randimg1.src = images1[useRand1].src;

		document.randimg1.setAttribute("id", document.randimg1.name)
		document.randimg1.setAttribute("alt", "Did you know?")
		document.randimg1.setAttribute("title", "Did you know?")
				
		var id	= document.randimg1.id

		$("#" + id).css(
			{
				cursor:"pointer"				
			}
		)
		$("#" + id).bind(
			'click',
			function()
			{
				// change the location from # to corresponding page please
				window.location = "#";
			}
		)
	}
}

/* End HomeBase Image Rotation*/


//==================================================================================
//	EVENT BROADCASTER - PEM TO TOOLBAR
//==================================================================================
/**
 * Provides a way of transfering arbitrary JSON objects from a HTML-page to a
 * extension
 *
 * For Extension (XUL) - Javascript, see <code>datatransfer.js</code>
 *
 * @author Phil
 * @date 2007/08/23
 * @see http://forums.mozillazine.org/viewtopic.php?t=171216
 * @see http://www.json.org/js.html for JSON support
 */
var Communicator = {
	ELWMS_EVENT_NAME: "ELWMSDataTransferEvent",
	ELWMS_EVENT_BACK_NAME: "ELWMSDataBackchannelEvent",
	ELWMS_CALLER_ID : "elwmsdataelement",
	ELWMS_ELEMENT_NAME : "ELWMSDataElement",
 
	/**
	 * initializes the Element and Listeners
	 *
	 */
	init : function() {
		// create data / event firing Elements
		var element = Communicator.createElement();
		// register custom event on callback
		element.addEventListener(Communicator.ELWMS_EVENT_BACK_NAME, Communicator.calledBack, true);
	},
 
	/**
	 * creates the data element
	 *
	 * @return {HTMLElement} the created Element of the type <code>Communicator.ELWMS_ELEMENT_NAME</code>
	 */
	createElement : function() {
		// may I create an Event?
		if ("createEvent" in document) {
		  	// if element is not yet existing
	  		if (!document.getElementById(Communicator.ELWMS_CALLER_ID)) {
		  		var element = document.createElement(Communicator.ELWMS_ELEMENT_NAME);
		  		element.setAttribute("id", Communicator.ELWMS_CALLER_ID);
		  		// attribute containing "data parameter" for extension call
				element.setAttribute("data", "");
				// attribute containing "return value" of extension
				element.setAttribute("returnvalue", "");
		  		document.documentElement.appendChild(element);
		  		return element;
	  		} else {
	  			// element exists - return that
	  			return document.getElementById(Communicator.ELWMS_CALLER_ID);
	  		}
	  	} else {
	  		// some error...
	  		alert("Communicator.createElement ERROR!");
	  		return null;
	  	}
	},
 
	/**
	 * calls the extension with JSON - data (object)
	 *
	 * @param {Object} data the data to transfer to extension - must be convertible to JSON
	 */
	call : function(data) {
		// create or get our element
		var element = Communicator.createElement();
		element.setAttribute("data", escape(data));
		// create and fire custom Event to notify extension
		var ev = document.createEvent("Event");
		ev.initEvent(Communicator.ELWMS_EVENT_NAME, true, false);
		element.dispatchEvent(ev);
	},
 
	/**
	 * is called when the extensions fires ELWMS_EVENT_BACK_NAME - Event; data
	 * may be collected from <code>returnvalue</code>-Attribute.
	 *
	 * @param {Event} aEvent the event
	 */
	calledBack : function(aEvent) {
		// TODO: decide what to do here!
		alert("Communicator.calledBack : " + unescape(aEvent.target.getAttribute("returnvalue")));
	}
};
 
function SendToToolbarFromHTML(post) {
	// build string
	var data	= "{";
	for(prop in post)
	{
		data += prop.toLowerCase() + ":'" + post[prop] + "',"
	}
	// remove trailing comma
	data 		= data.slice(0, data.length - 1);
	data 		+= "}";
	
	// Attemp to send data to toolbar
	Communicator.call(data);
}
 
/**
 * on page load, the Communicator is initialized
 */
if(!window.ActiveXObject)
{
	document.addEventListener(
		"DOMContentLoaded", 
		function(aEvent)
		{
			Communicator.init();

			// add event Listener
			if(document.getElementById("ToolBarLogin"))
			{
				document.getElementById("ToolBarLogin").addEventListener("click", func, true);		
			}
		}, 
		false
	);	
}



var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

// Carousel
//----------------------------------------------
var Carousel	= {
	//variables
	parameters:{},
	navigation:{
		prev:"&laquo; previous",			
		next:"next &raquo;",
		delta:285
	},

	// methods

	// init			
	init:function(data)
	{		
		this.parameters[data.instance] = {};
		instance = this.parameters[data.instance];
		for(prop in data)
		{
			instance[prop] = data[prop];
		}

		this.build(instance)		
	},

	// build
	build:function(obj)
	{		
		// instance
		var instance = $(obj.instance)

		// width
		var width	= this.navigation.delta * obj.images.length				
		
		// scroller
		var scroll	= document.createElement("div")
		$(scroll).addClass("scroll")				
		$(scroll).css(
			{
				position:"absolute",						
				width:this.navigation.delta + "px",
				height:"198px",
				overflow:"hidden"
			}
		)				
		
		var holder	= document.createElement("div")
		$(holder).addClass("holder")				
		$(holder).css(
			{
				position:"relative",
				left:"0px",
				width:width + "px",
				height:"198px"
			}
		)
		

		// append
		$(scroll).append(this.generate(holder, obj.images))
		$(instance).append(scroll)
		
		// pagination
		this.pagination(obj)
	},

	// generate
	generate:function(obj, images)
	{
		for(image = 0; image < images.length; image++)
		{
			var img	= document.createElement("img")
			$(img).attr(
				{
					src:images[image]
				}
			)
			$(img).css(
				{
					float:"left"
				}
			)

			$(obj).append(img)
		}

		return $(obj)
	},

	// pagination
	pagination:function(obj)
	{
		// instance
		var instance = $(obj.instance)
		
		// prev
		var prev	= document.createElement("div")
		$(prev).html(this.navigation.prev)
		$(prev).css(
			{
				"z-index":"999",
				position:"absolute",
				left:"0px",
				top:"180px",
				cursor:"pointer",
				visibility:"hidden"
			}
		)
		$(prev).addClass("prev")				
		$(prev).attr(
			{
				trigger:obj.instance
			}
		)
					
		// next
		var next	= document.createElement("div")
		$(next).html(this.navigation.next)
		$(next).css(
			{
				"z-index":"999",
				position:"absolute",
				right:"20px",
				top:"180px",
				cursor:"pointer"					
			}
		)
		$(next).addClass("next")
		$(next).attr(
			{
				trigger:obj.instance
			}
		)
		
		// functionality
		$(prev).bind(
			'click',
			function()
			{
				Carousel.slide($(this).attr("trigger"), 1)
			}
		)
		$(next).bind(
			'click',
			function()
			{
				Carousel.slide($(this).attr("trigger"), -1)
			}
		)				
		
		$(instance).append(prev)
		$(instance).append(next)
		
						
	},
	
	slide:function(instance, dir)
	{
		var	delta	= this.navigation.delta
		var min		= 0;
		var max		= -($(instance + " .holder").width());
						
		var x		= parseInt($(instance + " .holder").css("left")) + (delta * dir)				
		if(x <= 0 && x > max)
		{
			$(instance + " .holder").animate(
				{
					left:x
				},
				{
					duration:250
				}
			)			
		}

		x == 0 ? $(instance + " .prev").css({visibility:"hidden"}) : $(instance + " .prev").css({visibility:"visible"})
		x == max + delta ? $(instance + " .next").css({visibility:"hidden"}) : $(instance + " .next").css({visibility:"visible"})				

	}
}

