/* * 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=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-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]*?)\/>/g,function(all,front,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?all:front+">";});var tags=jQuery.trim(elem).toLowerCase(),div=context.createElement("div");var wrap=!tags.indexOf("",""]||!tags.indexOf("",""]||tags.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"","
"]||!tags.indexOf("",""]||(!tags.indexOf("",""]||!tags.indexOf("",""]||jQuery.browser.msie&&[1,"div
","
"]||[0,"",""];div.innerHTML=wrap[1]+elem+wrap[2];while(wrap[0]--)div=div.lastChild;if(jQuery.browser.msie){var tbody=!tags.indexOf(""&&tags.indexOf("=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*",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 im[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=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=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=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=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("
").append(res.responseText.replace(//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;ithis.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').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.leftthis.maxLeft-this.helperProportions.width){this.position.left=this.maxLeft-this.helperProportions.width}if(this.position.topthis.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
').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('
').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)=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-KK&&IG)||(C>E&&DB))){return false}if(H-(L.helperProportions.height/2)>K&&IG){return 2}if(C>E&&DB){return 2}break;case"intersect":return(E=K&&I<=G)||(H>=K&&H<=G)||(IG))&&((D>=E&&D<=B)||(C>=E&&C<=B)||(DB));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').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'].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('
');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.maxWidthH.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.rightF||J.bottomC&&J.rightH&&J.bottom *",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(EE&&DB){return 1}}else{if(G>J&&HF){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("
").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)=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=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=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)").insertBefore(H.headers);E("").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('
').append('
').append('
').append('
').append('
').append('
').append('
').append('
');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('
');var C=A(".ui-dialog-titlebar",H);var I=(L.title)?L.title:(E.attr("title"))?E.attr("title"):"";C.append(''+I+"");C.append('X');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('
');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=OF}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("
").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").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('').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("
").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(Dthis.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…",cache:false,idPrefix:"ui-tabs-",ajaxOptions:{},fx:null,tabTemplate:'
  • #{label}
  • ',panelTemplate:"
    ",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=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(""+C.spinner+"")}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')}$.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-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(''+appendText)}else{input.after(''+appendText)}}var showOn=inst._get("showOn");if(showOn=="focus"||showOn=="both"){input.focus(this._showDatepicker)}if(showOn=="button"||showOn=="both"){input.wrap('');var buttonText=inst._get("buttonText");var buttonImage=inst._get("buttonImage");var trigger=$(inst._get("buttonImageOnly")?$("").addClass("datepicker_trigger").attr({src:buttonImage,alt:buttonText,title:buttonText}):$("
    "}}html+=(showStatus?'
    '+(this._get("initStatus")||" ")+"
    ":"")+(!closeAtTop&&!this._inline?controls:"")+'
    '+($.browser.msie&&parseInt($.browser.version)<7&&!this._inline?'':"");return html},_generateMonthYearHeader:function(drawMonth,drawYear,minDate,maxDate,selectedDate,secondary){minDate=(this._rangeStart&&minDate&&selectedDate";for(var month=0;month<12;month++){if((!inMinYear||month>=minDate.getMonth())&&(!inMaxYear||month<=maxDate.getMonth())){html+='"}}html+=""}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+='"}html+="";return html},_addStatus:function(text){return" onmouseover=\"jQuery('#datepicker_status_"+this._id+"').html('"+text+"');\" onmouseout=\"jQuery('#datepicker_status_"+this._id+"').html(' ');\""},_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&&datemaxDate?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=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;i1){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');$("tr:first td",table.tBodies[0]).each(function(){colgroup.append($('').css('width',$(this).width()));});$(table).prepend(colgroup);};}function updateHeaderSortCount(table,sortList){var c=table.config,l=sortList.length;for(var i=0;ib)?1:0));};function sortTextDesc(a,b){return((ba)?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;j0){$this.trigger("sorton",[config.sortList]);}applyWidget(this);});};this.addParser=function(parser){var l=parsers.length,a=true;for(var i=0;i1;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('
    ').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('
    ').attr({'className':'jScrollPaneTrack'}).css({'width':settings.scrollbarWidth+'px'}).append(jQuery('
    ').attr({'className':'jScrollPaneDrag'}).css({'width':settings.scrollbarWidth+'px'}).append(jQuery('
    ').attr({'className':'jScrollPaneDragTop'}).css({'width':settings.scrollbarWidth+'px'}),jQuery('
    ').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('').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('').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 * MIT license * Includes enhancements by Scott Trenda and 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.length99?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);}; /** * A simple querystring parser. * Example usage: var q = $.parseQuery(); q.fooreturns "bar" if query contains "?foo=bar"; multiple values are added to an array. * Values are unescaped by default and plus signs replaced with spaces, or an alternate processing function can be passed in the params object . * http://actingthemaggot.com/jquery * * Copyright (c) 2008 Michael Manning (http://actingthemaggot.com) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. **/ jQuery.parseQuery = function(qs,options) { var q = (typeof qs === 'string'?qs:window.location.search), o = {'f':function(v){return unescape(v).replace(/\+/g,' ');}}, options = (typeof qs === 'object' && typeof options === 'undefined')?qs:options, o = jQuery.extend({}, o, options), params = {}; jQuery.each(q.match(/^\??(.*)$/)[1].split('&'),function(i,p){ p = p.split('='); p[1] = o.f(p[1]); params[p[0]] = params[p[0]]?((params[p[0]] instanceof Array)?(params[p[0]].push(p[1]),params[p[0]]):[params[p[0]],p[1]]):p[1]; }); return params; } /** * jGrowl 1.2.1 * * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. * * Written by Stan Lemon * Last updated: 2009.10.01 * * jGrowl is a jQuery plugin implementing unobtrusive userland notifications. These notifications function * similarly to the Growl Framework available for Mac OS X (http://growl.info). */ $.jGrowl=function(m,o){if($('#jGrowl').size()==0)$('
    ').addClass($.jGrowl.defaults.position).appendTo('body');$('#jGrowl').jGrowl(m,o);};$.fn.jGrowl=function(m,o){if($.isFunction(this.each)){var args=arguments;return this.each(function(){var self=this;if($(this).data('jGrowl.instance')==undefined){$(this).data('jGrowl.instance',$.extend(new $.fn.jGrowl(),{notifications:[],element:null,interval:null}));$(this).data('jGrowl.instance').startup(this);} if($.isFunction($(this).data('jGrowl.instance')[m])){$(this).data('jGrowl.instance')[m].apply($(this).data('jGrowl.instance'),$.makeArray(args).slice(1));}else{$(this).data('jGrowl.instance').create(m,o);}});};};$.extend($.fn.jGrowl.prototype,{defaults:{pool:0,header:'',group:'',sticky:false,position:'bottom-right',glue:'after',theme:'default',corners:'10px',check:250,life:3000,speed:'normal',easing:'swing',closer:true,closeTemplate:'×',closerTemplate:'
    [ close all ]
    ',log:function(e,m,o){},beforeOpen:function(e,m,o){},open:function(e,m,o){},beforeClose:function(e,m,o){},close:function(e,m,o){},animateOpen:{opacity:'show'},animateClose:{opacity:'hide'}},notifications:[],element:null,interval:null,create:function(message,o){var o=$.extend({},this.defaults,o);this.notifications[this.notifications.length]={message:message,options:o};o.log.apply(this.element,[this.element,message,o]);},render:function(notification){var self=this;var message=notification.message;var o=notification.options;var notification=$('
    '+o.closeTemplate+'
    '+o.header+'
    '+message+'
    ').data("jGrowl",o).addClass(o.theme).children('div.close').bind("click.jGrowl",function(){$(this).parent().trigger('jGrowl.close');}).parent();(o.glue=='after')?$('div.jGrowl-notification:last',this.element).after(notification):$('div.jGrowl-notification:first',this.element).before(notification);$(notification).bind("mouseover.jGrowl",function(){$(this).data("jGrowl").pause=true;}).bind("mouseout.jGrowl",function(){$(this).data("jGrowl").pause=false;}).bind('jGrowl.beforeOpen',function(){o.beforeOpen.apply(self.element,[self.element,message,o]);}).bind('jGrowl.open',function(){o.open.apply(self.element,[self.element,message,o]);}).bind('jGrowl.beforeClose',function(){o.beforeClose.apply(self.element,[self.element,message,o]);}).bind('jGrowl.close',function(){$(this).data('jGrowl').pause=true;$(this).trigger('jGrowl.beforeClose').animate(o.animateClose,o.speed,o.easing,function(){$(this).remove();o.close.apply(self.element,[self.element,message,o]);});}).trigger('jGrowl.beforeOpen').animate(o.animateOpen,o.speed,o.easing,function(){$(this).data("jGrowl").created=new Date();}).trigger('jGrowl.open');if($.fn.corner!=undefined)$(notification).corner(o.corners);if($('div.jGrowl-notification:parent',this.element).size()>1&&$('div.jGrowl-closer',this.element).size()==0&&this.defaults.closer!=false){$(this.defaults.closerTemplate).addClass('jGrowl-closer').addClass(this.defaults.theme).appendTo(this.element).animate(this.defaults.animateOpen,this.defaults.speed,this.defaults.easing).bind("click.jGrowl",function(){$(this).siblings().children('div.close').trigger("click.jGrowl");if($.isFunction(self.defaults.closer))self.defaults.closer.apply($(this).parent()[0],[$(this).parent()[0]]);});};},update:function(){$(this.element).find('div.jGrowl-notification:parent').each(function(){if($(this).data("jGrowl")!=undefined&&$(this).data("jGrowl").created!=undefined&&($(this).data("jGrowl").created.getTime()+$(this).data("jGrowl").life)<(new Date()).getTime()&&$(this).data("jGrowl").sticky!=true&&($(this).data("jGrowl").pause==undefined||$(this).data("jGrowl").pause!=true)){$(this).trigger('jGrowl.close');}});if(this.notifications.length>0&&(this.defaults.pool==0||$(this.element).find('div.jGrowl-notification:parent').size()');this.interval=setInterval(function(){$(e).data('jGrowl.instance').update();},this.defaults.check);if($.browser.msie&&parseInt($.browser.version)<7&&!window["XMLHttpRequest"])$(this.element).addClass('ie6');},shutdown:function(){$(this.element).removeClass('jGrowl').find('div.jGrowl-notification').remove();clearInterval(this.interval);}});$.jGrowl.defaults=$.fn.jGrowl.prototype.defaults; /** * jCountr * Creates a countdown timer from a jQuery object. * * @author agentor@gmx.de * @version 1.2 [2009-05-06] */ jQuery.fn.counter=function(params){var self=this;self.display=$(this);self.hour=params.hour?params.hour:"0";self.min=params.min?params.min:"0";self.sec=params.sec?params.sec:"0";self.sec_only=params.sec_only?params.sec_only:false;self.hour_end=params.hour_end?params.hour_end:"0";self.min_end=params.min_end?params.min_end:"0";self.sec_end=params.sec_end?params.sec_end:"0";self.message=params.message?params.message:"FINISHED";self.delimiter=params.delimiter?params.delimiter:":";self.return_url=params.return_url?params.return_url:"";self.finish_function=params.finish_function?params.finish_function:"";self.interval=params.interval?params.interval*1000:"1000";self.iteration=params.iteration?params.iteration:"1";self.direction=params.direction?params.direction:"down";self.timestamp=(self.hour*60*60)+(self.min*60)+(self.sec*1);self.timestamp_end=(self.hour_end*60*60)+(self.min_end*60)+(self.sec_end*1);self.onTick=params.onTick?params.onTick:function(){return true;};self.onFinish=params.onFinish?params.onFinish:function(){return true;};self._updateCounter=function(params){self.change_hour=params.change_hour?params.change_hour:"0";self.change_min=params.change_min?params.change_min:"0";self.change_sec=params.change_sec?params.change_sec:"0";self.change_direction=params.change_direction?params.change_direction:"up";self.hour=params.hour?params.hour:self.hour;self.min=params.min?params.min:self.min;self.sec=params.sec?params.sec:self.sec;self.hour_end=params.hour_end?params.hour_end:self.hour_end;self.min_end=params.min_end?params.min_end:self.min_end;self.sec_end=params.sec_end?params.sec_end:self.sec_end;self.message=params.message?params.message:self.message;self.delimiter=params.delimiter?params.delimiter:self.delimiter;self.return_url=params.return_url?params.return_url:self.return_url;self.finish_function=params.finish_function?params.finish_function:self.finish_function;self.interval=params.interval?params.interval*1000:self.interval;self.iteration=params.iteration?params.iteration:self.iteration;self.direction=params.direction?params.direction:self.direction;self.timestamp_end=(self.hour_end*60*60)+(self.min_end*60)+(self.sec_end*1);if(self.change_hour!=0||self.change_min!=0||self.change_sec!=0){var temp_timestamp=self._createTimestamp(self.change_hour,self.change_min,self.change_sec);if(self.change_direction.match(/up/)){self.timestamp+=temp_timestamp;}else if(self.change_direction.match(/down/)){self.timestamp-=temp_timestamp;}else{return;}}else{self.timestamp=(self.hour*60*60)+(self.min*60)+(self.sec*1);};return;};self._createTimestamp=function(hour,min,sec){return(hour*60*60)+(min*60)+(sec*1)};self._getCounterFromTimestamp=function(t){if(t>0){hours=Math.floor(t/3600);minutes=Math.floor((t/3600-hours)*60);seconds=Math.round((((t/3600-hours)*60)-minutes)*60);}else{hours=0;minutes=0;seconds=0;};if(seconds==60){seconds=0;};if(seconds==0){if(hours!=0){minutes=minutes/1+1;};};if(minutes<10){if(minutes<0){minutes=0;};minutes='0'+minutes;};if(seconds<10){if(seconds<0){seconds=0;};if(self.sec_only){seconds=seconds;}else{seconds='0'+seconds;};};if(hours<10){if(hours<0){hours=0;};hours='0'+hours;};if(hours>0){return hours+self.delimiter+minutes+self.delimiter+seconds;}else if(minutes>0){return minutes+self.delimiter+seconds;}else if(seconds>0){if(self.sec_only){return seconds;};}else{return minutes+self.delimiter+seconds;};};self._tick=function(){if(self.timestamp>0&&self.timestamp!=self.timestamp_end){var counter=self._getCounterFromTimestamp(self.timestamp);self.display.html(counter);if(self.direction=="down"){self.timestamp=self.timestamp*1-self.iteration*1;}else if(self.direction=="up"){self.timestamp=self.timestamp*1+self.iteration*1;}else{return;};}else{window.clearInterval(self._interval);if(!self.onFinish(self.display)){return;};self.display.html(self.message);if(self.finish_function!=""){eval(self.finish_function);};if(self.return_url!=""){window.location.href=self.return_url;};return;};};self._tick();self._interval=window.setInterval(self._tick,self.interval);return this;}; /* ================================================= */ /* ============ document.ready function ============ */ /* ================================================= */ $(document).ready(function() { $(document).data("clickDisabled", false); $('div, span, p, a, h3, ul').each( function() { if($(this).css('background-image').indexOf('.png') != -1) { $(this).ifixpng(); } } ) $('img[@src$=.png]').ifixpng(); // Login catcher // You must be loged in to do that interstitial $("body").append($("")); InterstitialController.config( { instance:"loginRequired", trigger: "#loginRequired", url:"jsp/interstitial_login.jsp", step:{ error:"jsp/interstitial_load_error.jsp" } } ); $(".link-signin, .link-register").bind("click",function(e){ e.preventDefault(); if(LOGIN != true){ var $this = $(this); var defaultUrl = "homebase-middlesnackbar.jsp" // either page redirection or onclick callback will be executed after user login but not both // onclick takes presidence over page redirection //setup page redirection after login try{ if(this.tagName == "A" && $this.attr("href").length > 0){ // if a link was clicked then target is in the href attribute $(document).data("targetUrl",$this.attr("href")); } else if (this.tagName == "BUTTON" && $this.attr("name").length > 0) { //if a button was clicked then target is in the value attribute $(document).data("targetUrl",$this.attr("name")); } else if (this.tagName == "INPUT" && $this.attr("alt").length > 0){ //if a button was clicked and it's an input button then target is in the alt attribute $(document).data("targetUrl",$this.attr("alt")); } else { //set up a default target $(document).data("targetUrl",defaultUrl); } } catch(e) { alert(e.message); } // save the onclick attribute to execute as a callback after login if($this.attr("onclick")){ if($this.attr("onclick").length > 0){ $(document).data("targetOnClick",$this.attr("onclick")); } } if($this.hasClass("link-signin")){ $("#loginRequired").trigger("click"); } if($this.hasClass("link-register")){ if($this.attr("id") == "registerButton_popup"){ //if we clicked on the button in the login interstitial then we want to submit the form which will trigger the registration interstitial InterstitialController.process('#FirstTimeForm_popup'); } if($this.attr("trigger") == null){ //trigger registration interstitial if the link clicked on is not the explicit trigger if(InterstitialController.parameters.register){ InterstitialController.open("register"); } else { InterstitialController.config({ instance:"register", trigger:null, url:"jsp/interstitial_register.jsp", step:{ success:"jsp/interstitial_forgot_password_success.jsp", error:"jsp/interstitial_register_error.jsp" } }); // fire registration interstitial $("#register").trigger('click'); $("#register").remove(); } } } } return false; }); // trigger download toolbar based on querystring /** * copied the code from jQuery.pem.initToolbarDownloadL * if this code is modified the we should look at the code inside jQuery.pem.initToolbarDownload * */ var q = $.parseQuery(); if (q.dlToolbar == "true" && LOGIN || q.dlToolbar && LOGIN){ var host = window.location.hostname; host=host.replace("www.",""); //fill in all the version text $(".version").text("Version 1.0 (Beta)"); if( BrowserDetect.browser=="Firefox" ){ //track download interest Tracking({ Event:{"Event27":"ToolbarDownload"} },true); //window.location = "/toolbar/snackbar.xpi" xpi = {'Food.com Snackbar add-on':'http://download.'+host+'/snackbar.xpi'}; InstallTrigger.install(xpi); }else if( BrowserDetect.browser=="Explorer" ){ //track download interest Tracking({ Event:{"Event27":"ToolbarDownload"} },true); window.location = "http://download."+host+"/FoodToolBarSetup.msi" }else{ InterstitialController.config( { instance:"BrowserPush", trigger:"a.BrowserPush", url:"jsp/interstitial_browser_push.jsp", type:"error" } ) } } //TODO: added detection of ad-banner height and modify snackbar top css value accordingly - ad blockers adjustment }); /* ---------- 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(){ var host = window.location.hostname; host=host.replace("www.",""); //fill in all the version text $(".version").text("Version 1.0 (Beta)"); //change download link if( BrowserDetect.browser=="Firefox" ){ $("a.BrowserPush").click( function(e){ e.preventDefault(); //track download interest Tracking({ Event:{"Event27":"ToolbarDownload"} },true); //window.location = "/toolbar/snackbar.xpi" xpi = {'Food.com Snackbar add-on':'http://download.'+host+'/snackbar.xpi'}; InstallTrigger.install(xpi); return false; }); }else if( BrowserDetect.browser=="Explorer" ){ $("a.BrowserPush").click( function(e){ e.preventDefault(); //track download interest Tracking({ Event:{"Event27":"ToolbarDownload"} },true); window.location = "http://download."+host+"/FoodToolBarSetup.msi"; return false; }); }else{ InterstitialController.config({ instance:"BrowserPush", trigger:"a.BrowserPush", url:"jsp/interstitial_browser_push.jsp", type:"error" }); } //grab cookie if it exists var isLoggedInCookie = readCookie('ToolbarIsLoggedIn'); if (isLoggedInCookie){ //set the value of hidden input $('#isToolbarLoggedIn').val("true"); } //hide badges if not needed if( $('#isToolbarLoggedIn').val()=="true" ){ $('#dwnldhm').hide(); $('#dwnld').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("display") == "none"){ $(custom + " li").css({ display:"block"}); $(custom + " li").css({ display:"none"}); } else { $(custom + " li").css({ display:"none"}); $(custom + " li").css({ display:"block"}); } } $($(this).parent().get(0)).addClass("collapsed"); }, function() { IE ? $(system + " li").show() : $(system).slideDown() ; if(IE){ if($(custom + " li").css("display") == "none"){ $(custom + " li").css({ display:"block"}); $(custom + " li").css({ display:"none"}); } else { $(custom + " li").css({ display:"none"}); $(custom + " li").css({ display:"block"}); } } $($(this).parent().get(0)).removeClass("collapsed"); } ) $(".cust-collections li#your-custom-collections").toggle( function() { IE ? $(custom + " li").hide() : $(custom).slideUp() ; if(IE){ if($(system + " li").css("display") == "none"){ $(system + " li").css({ display:"block"}); $(system + " li").css({ display:"none"}); } else { $(system + " li").css({ display:"none"}); $(system + " li").css({ display:"block"}); } } $($(this).parent().get(0)).addClass("collapsed"); }, function() { IE ? $(custom + " li").show() : $(custom).slideDown() ; if(IE){ if($(system + " li").css("display") == "none"){ $(system + " li").css({ display:"block" }); $(system + " li").css({ display:"none" }); } else { $(system + " li").css({ display:"none"}); $(system + " li").css({ display:"block"}); } } $($(this).parent().get(0)).removeClass("collapsed"); } ) },//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; iem").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"); } else { $("#loginRequired").trigger('click'); } 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(""+ _args["oldCollectionName"] +" collection is now called "+ newName+"."); $("#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 = '' + newName +''+ _date +'0'; } $(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(" (0)"); $(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"; $.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(); //Commenting this DEV line for Integration//$(this).parents('li').addClass('openCat').find(".panel").slideOut(animSpeed); //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(e){ e.preventDefault(); if(!LOGIN){ $("#loginRequired").trigger("click"); $(document).data("addToRB",this); } else { 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" }; if(toolbarFlag) { var trigger = $(document.createElement("a")) trigger.attr({ trigger:"InstallToolbar", id:"GoAndInstallToolbarWarning" }); $("body").append(trigger) InterstitialController.config({ instance:"InstallToolbar", trigger:"#GoAndInstallToolbarWarning", url:"jsp/interstitial_install_toolbar.jsp", type:"error" }); // fire interstitial instance = "GoAndInstallToolbarWarning" $("#" + instance).trigger('click') $("#" + instance).remove(); } else { $.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"; } // load interstitial $.ajax({ url:url+"?title="+title, cache: false, data:{}, dataType:"text", type:"GET", success:function(html) { var p34 = "Search:AddRecipe:LinkClick"; var p13 = "AddRecipe:LinkClick"; Tracking({ Prop:{"prop13":p13,"prop34":p34}, Evar:{"eVar5":p13,"eVar20":p34}, Event:{"Event5":"addRecipe","Event20":"addRecipe"} },true); InterstitialController.clearContent(); InterstitialController.display(html) if(triggerID != "sbAddBoxLink" ) { setTimeout( function(){ $(InterstitialController.interstitial.lightbox).fadeOut("fast"); }, 3000 ); } } }); 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; } //if user has just signed in then we need to reload the page after they get their drop message. if($(document).data("reloadPage")){ setTimeout(function(){ $(document).data("reloadPage",false); //Submit form again rather than reload window to avoid "Send search data again" browser alert $("#SearchResultSnackbar").submit(); }, 3000 ); } }, 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")); Tracking({ Evar:{"eVar9":"facet:Ingredient"}, Event:{"Event9":"showMore"} },true); },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("..."); $(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(); } ); } ); }, // 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(""+firstLetter+""); }; }, // 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 // Altered by Abhinandan according to the mail dated Fri 10/3/2008 10:39 PM by Karthik. //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)), bottom: "15px" }); // get error hide and center var error = $(config.resize.error); error.hide(); error.css({ left:(($('body').width()/2) - (error.width()/2)), bottom: "15px" }); } // draggable //for(prop in source) for(var i = 0; i < source.length; i++) { // draggable $(source[i] + " > " + item).draggable({ revert:false, // Altered by Abhinandan according to the mail dated Fri 10/3/2008 10:39 PM by Karthik. 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; } //modified for artf836379 start var bookmarked = $(this).attr("id").match("bookmark"); //modified for artf836379 end 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(''); dragBox.css({ "width": "42px", "overflow": "hidden" }); } else { dragBox.html(title); } } else { dragBox.html(title); } //css styles for all drag boxes (images and no images) dragBox.css({ "z-index": "1000", "background": "#dedede", "height": "42px", "border": "2px solid #FFF" }); dragBox.attr({ id:"recipe-drag-box", targetId:id, title:title, recipeURL:recipeURL, recipeSource:recipeSource, "z-index":"1000", bookmark : bookmarked || "false" }); if (($.browser.msie)&&(($.browser.version)==6)) { //Fixing IE6 animiation recipe drop box animation $("#recipe-drop-box").css({"top":"auto"}); } 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{ //modified for artf836379 start if($("#recipe-drag-box").attr("bookmark") == "false"){ $("#recipe-drag-box").append(""); } //modified for artf836379 start } }, 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(); } } }); $(target).bind("drop",function(ev){ if(LOGIN == false){ //store drop item so that it's attributes can be used after login //FF uses originalTarget while other browsers use srcElement var dragBox = ev.originalTarget || ev.srcElement; $("div#recipe-drop-box").data("dropEvent",dragBox); //trigger login $("#loginRequired").trigger("click"); return false; } // send data var dragBox = ev.originalTarget || ev.srcElement || $("div#recipe-drop-box").data("dropEvent"); var $dragBox = $(dragBox); var _id = $dragBox.attr("targetId"); var _bucket = $(this).attr("id"); var _cId = $(this).attr("rel"); //modified for artf836379 start var _bookmark = $dragBox.attr("bookmark"); //modified for artf836379 end var title = $dragBox.attr("title"); var recipeURL = $dragBox.attr("recipeURL"); var recipeSource = $dragBox.attr("recipeSource"); var args = { recipe_id: _id, bucket: _bucket, title:title, recipeSource:recipeSource, recipeURL:recipeURL, collectionID : _cId, action : dragFunc }; //modified for artf836379 start if(_bookmark != "false" && $(this).parents("ul#cust-collections-categories").length == 1){ var copy = { title:"Sorry!", message:"Sorry, we're not smart enough yet to add bookmarked recipes to custom collections." } InterstitialController.clearContent(); InterstitialController.error(copy); return false; }else if(_bookmark != "false"){ return false; } //modified for artf836379 start $.ajax({ url: "addRecipe.do", cache: false, data: args, dataType: "json", type:"POST", success:function(json){ if($("div#recipe-drop-box").data("closeLogin") == true || $("div#recipe-drop-box").data("closeLogin") == "true"){ $(InterstitialController.interstitial.lightbox).fadeOut("fast"); } switch(json.response.success){ case "success": if(resize.available){ var p34 = "Search:AddRecipe:DragDrop"; var p13 = "AddRecipe:DragDrop"; Tracking({ Prop:{"prop13":p13,"prop34":p34}, Evar:{"eVar5":p13,"eVar20":p34}, Event:{"Event5":"addRecipe","Event20":"addRecipe"} },true); // 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 "duplicate": var copy = { title:json.response.title, message:json.response.message } 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){ //if user has just signed in then we need to reload the page after they get their drop message. if($("#recipe-drop-box").data("redirectURL")){ var countDown = $("").counter({sec:"3",sec_only:true,message:"0"}); $.jGrowl('Reloading Page in ',{ position:"bottom-right", beforeOpen: function(e,m){ $(e).find(".message").append(countDown); } }); setTimeout(function(){ $("#recipe-drop-box").data("redirectURL",false); //Submit form again rather than reload window to avoid "Send search data again" browser alert $("#SearchResultSnackbar").submit(); }, 3000 ) } // 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); var _queTxt = $(this).text(); var _secText = $(this).parent().siblings("h3").text(); if(_secText.indexOf(":") >= 0) { var idx = _secText.indexOf(":"); _secText = _secText.substring(0,idx); } _secText = _secText.replace(/\'/g, " "); _secText = _secText.replace(/\"/g, " "); _secText = _secText.replace(/\r/g, " "); _secText = _secText.replace(/\n/g, " "); _queTxt = _queTxt.replace(/\'/g, " "); _queTxt = _queTxt.replace(/\"/g, " "); _queTxt = _queTxt.replace(/\r/g, " "); _queTxt = _queTxt.replace(/\n/g, " "); var p3 = "open:"+_secText+":"+_queTxt; var s = "open:"+_secText; Tracking({ Prop:{"prop8":p3,"prop7":s} },true); } else { $(this).parent().removeClass(_on); $(this).parent().addClass(_off); $(this).parent().find(_ans).each(function(index,item){ $(item).hide(); }); var _queTxt = $(this).text(); var _secText = $(this).parent().siblings("h3").text(); if(_secText.indexOf(":") >= 0) { var idx = _secText.indexOf(":"); _secText = _secText.substring(0,idx); } _secText = _secText.replace(/\'/g, " "); _secText = _secText.replace(/\"/g, " "); _secText = _secText.replace(/\r/g, " "); _secText = _secText.replace(/\n/g, " "); _queTxt = _queTxt.replace(/\'/g, " "); _queTxt = _queTxt.replace(/\"/g, " "); _queTxt = _queTxt.replace(/\r/g, " "); _queTxt = _queTxt.replace(/\n/g, " "); var p3 = "close:"+_secText+":"+_queTxt; var s = "close:"+_secText; Tracking({ Prop:{"prop8":p3,"prop7":s} },true); } //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(""); $(this).select(""); }); 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, 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; } var toolbarFlag = false; var currentIframeSiteName = ""; //========================================================================================== // 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", logout:" #sbLogout", buttons:" #sbStuff", search:" #sbSearch", logo:" #logo" } var _links = $(config.links); var _dropbox = $(config.dropbox); var _serviceURL = "toolBarGetValidNavigationSites.do"; // 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%" }); Tracking({ Prop:{"prop31":"Session:toolBarClose"}, Evar:{"eVar19":"Session:toolBarClose"} },true); }); // 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.jsp"; var friendlyName = "friendlyName"; var validThirdParty = true; /* var userHistoryURL = "userHistoryController.do"; // user history $.ajax({ url:userHistoryURL, cache:false, data:{"recipeID":recipeID,"recipeURL":_serviceURL,"source":source,"url":_a,"title":title}, dataType:"text", type:"POST" }) */ //Change Request - Remove SnackBar // 1. Remove Snackbar animation // 2. Do not show snackbar on third party site // 3. Do not prompt the user with confirmation to go to third party site if(true){ window.location =_a; return false; } //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:{"recipeID":recipeID,"recipeURL":_serviceURL,"source":source,"url":_a,"title":title}, 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(); //set the site name for interstitial #23 currentIframeSiteName = curSiteName; 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; Tracking({ Prop:{"prop24":"In"}, Evar:{"eVar16":title}, Event:{"Event17":"Recipe View"} },true); }else{ Tracking({ Prop:{"prop24":"Out"}, Evar:{"eVar16":title}, Event:{"Event17":"Recipe View"} },true); } 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 += "
    "; html += "" // html += "Add to Box"; html += "Back to search results"; html += "

    Food.com

    "; html += "
    "; $(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 _snackbarHeight = $("#BottomSnackbar").height(); var _y = _h - ((_snackbarHeight > 0) ? _snackbarHeight : 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 // $(snackbar + ClickOut._objects.badge).fadeIn(_speed,function(){ClickOut._frame()}); 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:"100%", 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) { // interstitial controller var trigger = $(document.createElement("a")) trigger.attr({ trigger:"InstallToolbar", id:"GoAndInstallToolbarWarning" }); $("body").append(trigger); //interstitial controller InterstitialController.config({ instance:"InstallToolbar", trigger:"#GoAndInstallToolbarWarning", url:"jsp/interstitial_third_party_link.jsp", type:"error" }); // fire interstitial if(!toolbarFlag) { instance = "GoAndInstallToolbarWarning" $("#" + instance).trigger('click'); $("#" + instance).remove(); toolbarFlag = true; } } 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 _snackbarHeight = $("#BottomSnackbar").height(); var _y = _h - ((_snackbarHeight > 0) ? _snackbarHeight : 84); // body id $("#" + config.page).css({ height:_h, overflow:"hidden" }); $("#iframe").css({height:_y}); // snackbar position $(_snackbar.bottom).css({top:_y}); //if ie6, get rid of vertical scrollbar if (($.browser.msie)&&(($.browser.version)==6)) { $("html").css({overflow:"auto"}); } } } //========================================================================================== // 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", // This is the width of the first two columns, including borders width:"373px" }); $("#rb-table").css({left:"-308px"}); 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:"265px"}); // set width of middle column var 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(); if($.browser.version != 6 ){ $(".name-w img").each(function(){ $(this).bind('load',function(){ var ratio; ratio = this.width / this.height; if(ratio >= 1 ){ $(this).css({ width : parseInt(100 * ratio) + "px", height :parseInt(100) + "px", border : "none", padding : "0", margin : "0", position : "relative", left : "-" + parseInt(((100 * ratio)-100)/2) + "px" }); }else{ $(this).css({ width : parseInt(100) + "px", height : parseInt(((100*ratio)/this.height)*1000) + "px", border : "none", padding : "0", margin : "0", position : "relative", top : parseInt(((100 * ratio)-100)/2) + "px" }); } var div = $(document.createElement("div")); div.css({ width : "98px", height : "98px", overflow : "hidden", border: "1px solid #CECECE", "margin-bottom" : "5px" }); var pseudoBorder = $(document.createElement("div")); pseudoBorder.css({ width: "96px", height : "96px", overflow:"hidden", border : "1px solid #FFFFFF" }); $(this).wrap(div).wrap(pseudoBorder); }); }); } else { var x = 0 var images = new Array() $(".name-w img, .name-w.result-w img").each(function() { $(this).bind("load",function() { var randomnumber=Math.floor(Math.random()*1001) randomId = "img_" + randomnumber $(this).attr("id",randomId); var Img = new Image(); Img.originalImage = "#"+$(this).attr("id"); Img.onload = function(){ var ratio; ratio = this.width / this.height; if(ratio >= 1 ){ $(Img.originalImage).css({ width : parseInt(100 * ratio) + "px", height :parseInt(100) + "px", border : "none", padding : "0", margin : "0", left : "-" + parseInt(((100 * ratio)-100)/2) + "px" }); } else { $(Img.originalImage).css({ width : parseInt(100) + "px", height : parseInt(((100*ratio)/this.height)*1000) + "px", border : "none", padding : "0", margin : "0", top : parseInt(((100 * ratio)-100)/2) + "px" }); } var div = $(document.createElement("div")); div.css({ width : "98px", height : "98px", overflow : "hidden", border: "1px solid #CECECE", "margin-bottom" : "5px" }) var pseudoBorder = $(document.createElement("div")); pseudoBorder.css({ width: "96px", height : "96px", overflow:"hidden", border : "1px solid #FFFFFF" }) $(Img.originalImage).wrap(div).wrap(pseudoBorder); } Img.src = this.src; }); }); var images = new Array(); delete images; } $(".rb-results-table .name-w img").hide(); 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); //set height for bookmark page in ie6 var bookMarkWrapper = document.getElementById("bookmarkContent"); if((bookMarkWrapper) && ($.browser.msie)&&(($.browser.version)==6)) { $(".grid-sidebar").height($(".grid-sidebar .grid-e").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) + ")"), prevColImage:$(".rb-results tbody tr:nth-child(" + (i + 1) + ") th.prevCol img"), h:$(".rb-results tbody tr:nth-child(" + (i + 1) + ")").height() } var orig = { tr:$(this), prevColImage:$(this).find("th.prevCol img"), h:$(this).height() } //clear image heights for next iteration $(orig.prevColImage).css("height","0"); $(clone.prevColImage).css("height","0"); if(clone.h > orig.h) { $(orig.tr).css({ height:clone.h }); $(orig.prevColImage).css({ height:clone.h }); Table._updateClone($(orig.tr).attr("id"), true) } else if( clone.h < orig.h ) { $(clone.tr).css({ height:orig.h }); $(clone.prevColImage).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 788){ if(Table._steps == 0){ Table._steps = n + 1; } Table._width[n] = 788 // Modified for artf820572 on 18/12/08 ends } } } 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" }).click(function(){ Table.pagination(-1) }).mouseover(function(){ $(this).css({ color:"#e25d05" }); }).mouseout(function(){ $(this).css({ color:"#000000" }); }); // next var next = $(id + " th.nextCol"); next.css({ cursor:"pointer" }).click(function(){ Table.pagination(1) }).mouseover(function(){ $(this).css({ color:"#e25d05" }); }).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() + 20; var prevColWidth = $("#rb-table th.prevCol").width(); //the extra 3 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 - 3 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"); 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 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 _error = false; var _errors = Array(); //var attributeValues = Array(); var courseValues = Array(); var cuisineValues = Array(); var dishValues = Array(); var holidayValues = Array(); var prepMethodValues = Array(); var cookMethodValues = Array(); var prepDeviceValues = Array(); var cookDeviceValues = Array(); var dietValues = Array(); var mealValues = Array(); var _submit = {}; // loop through form $("input:hidden", _id).each(function(){ field = $(this).attr("name"); _submit[field] = $(this).val(); }); $("input:not(:hidden)", _id).each(function() { field = $(this).attr("name"); if(_data.required[field] == "checkbox"){ if(!$(this).is(":checked")) { _error = true; _errors.push(field); }else{ _submit[field] = $(this).attr("checked") ? true : false; //_submit[field] = $(this).val(); } } else if(_data.required[field]){ if(!$(this).val()){ _error = true; _errors.push(field) }else{ // TODO: validation for firstName, lastName, userName if(field.search(/email/i) >= 0){ isEmailValid = checkEmailId($(this).val()); if(isEmailValid){ _submit[field] = $(this).val(); }else{ errorMessage.push("Invalid Email Id") _error = true; _errors.push(field) } }else if(field.search(/zip/i) >= 0){ 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($(this).attr("type").search(/radio/i) >= 0){ if($(this).attr("checked")){ _submit[field] = $(this).val(); } }else if($(this).attr("type").search(/checkbox/i) >= 0) { _submit[field] = $(this).attr("checked") ? true : false; }else{ _submit[field] = $(this).val(); } } if($(this).attr("type").search(/checkbox/i) >= 0) { if(field.search(/course/i) >= 0){ if($(this).is(":checked")){ courseValues.push($(this).val()); _submit[field] = courseValues; } }else if(field.search(/meal/i) >= 0){ if($(this).is(":checked")){ mealValues.push($(this).val()); _submit[field] = mealValues; } }else if(field.search(/cuisine/i) >= 0){ if($(this).is(":checked")){ cuisineValues.push($(this).val()); _submit[field] = cuisineValues; } }else if(field.search(/dishtype/i) >= 0){ if($(this).is(":checked")){ dishValues.push($(this).val()); _submit[field] = dishValues; } }else if(field.search(/holidays/i) >= 0){ if($(this).is(":checked")){ holidayValues.push($(this).val()); _submit[field] = holidayValues; } }else if(field.search(/cooking_method/i) >= 0){ if($(this).is(":checked")){ cookMethodValues.push($(this).val()); _submit[field] = cookMethodValues; } }else if(field.search(/preparation_method/i) >= 0){ if($(this).is(":checked")){ prepMethodValues.push($(this).val()); _submit[field] = prepMethodValues; } }else if(field.search(/prep_devices/i) >= 0){ if($(this).is(":checked")){ prepDeviceValues.push($(this).val()); _submit[field] = prepDeviceValues; } }else if(field.search(/cooking_devices/i) >= 0){ if($(this).is(":checked")){ cookDeviceValues.push($(this).val()); _submit[field] = cookDeviceValues; } }else if(field.search(/diets/i) >= 0){ if($(this).is(":checked")){ dietValues.push($(this).val()); _submit[field] = dietValues; } } } } ); // end each function 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; } } } // end processForm 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*") _div.append(field); _p.append(_div); } } _errorEmailInvalidForm = function(_errors) { $.ajax({ url: "jsp/errors.html", cache: false, data:{}, dataType:"text", type:"GET", success:function(text){ $('body').append(text); _addErrotFields(_errors); _fixDimensions(); _addClose(); } }); } _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){ //enable submit button enableButton(); var scrollToTop; var errorMessage = ""; // server needs to return failed echo -> login="failed" if(json.response.login == "failed") { // Comments from BASELINE_fails++; // comments from BASELINEif(_fails > 2) _loginFailed(); } if(json.response.resetPassword == 'success'){ window.location = json.response.url } if(json.response.uploadRecipeSuccess == "done"){ //_uploadRecipeInts(); window.location = json.response.url }else if(json.response.uploadRecipeSuccess == "fail"){ _uploadRecipeInts(); } // check if editable / hide input // in addition the loaded page should send back a return or echo -> success=true; if(json.response.success == "true"){ scrollToTop = false; //set global LOGIN variable to true LOGIN = true; //sync toolbar first if(!window.ActiveXObject) { var toolbarPost = { email:json.response['email'], password:json.response['md5'], session:json.response['session'], user:json.response['user'] } SendToToolbarFromHTML(toolbarPost); } //if a callback was passed to login interstitial then fire it if(_data.callback){ eval(_data.callback); } //if "add to recipe box" triggered login else if($(document).data("addToRB")){ $(document).data("reloadPage",true); var recipeToAdd = $(document).data("addToRB"); $(recipeToAdd).trigger("click"); } //if drop event from search results triggered login else if($("div#recipe-drop-box").data("dropEvent")){ $("div#recipe-drop-box").data("closeLogin",true); if(json.response.url){ $("div#recipe-drop-box").data("redirectURL",json.response.url); } $("div#recipe-drop-box").trigger("drop"); } //check for facets on a search results page else if($(".refined .facetList").children().length > 0){ var facetLastItem = $(".refined .facetList").children("li:last").find("a"); var facetData = facetLastItem.attr("name").split(","); //submitFacets(facetData[0],facetData[1]); reloadResult(facetData[0],facetData[1]); } //if we have a success message, show it, otherwise redirect else if($(document).data("popupAfterLogin")){ InterstitialController.open($(document).data("popupAfterLogin")); } else if( _obj.success ) { _successRedirect( _obj.success, json.response.url ) } // Added by Abhinandan. To implement the New Login flow for the registration. 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.passwordChange == "currentPasswordNotmatch"){ _passwordChange(); } if(json.response.invitedUser == "success"){ if(document.forms.RegistrationForm.email){ document.forms.RegistrationForm.email.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.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.accountUpdate == "pass"){ _successRedirect(); //window.location = json.response.url } if(json.response.emailUpdate == "failed"){ _passwordChange(); } if(json.response.emailUpdate == "pass"){ _passwordChange(); } if(json.response.captchaValidation && json.response.captchaValidation == "fail"){ //_captchaValatationFail(); $("#recaptcha_response_field").siblings(".labelWrap").addClass("formError"); errorMessage += "The captcha was not entered correctly. Please try again. Spaces and capitalization do not matter.
    "; scrollToTop = true; } 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 } //Added for handling user registration if(json.response.register && json.response.register.search(/userexist/i) >= 0){ //_userExist(); $("#email_popup").siblings(".labelWrap").addClass("formError"); errorMessage += "You are already registered on Food.com. Please login to access the site.
    "; scrollToTop = true; } if(json.response.register && json.response.register.search(/aliasDuplicate/i) >= 0){ //_duplicateAlias(); $("#userName_popup").siblings(".labelWrap").addClass("formError"); errorMessage += "Someone already has that alias. Please provide a different one.
    "; scrollToTop = true; } if(json.response.register && json.response.register.search(/uninvitedUser/i) >= 0){ _uninvitedUser(); errorMessage += " We do not recognize that email address. If you think we've made a mistake send us a quick mail and we'll help sort it out.
    "; scrollToTop = true; } if(json.response.register && json.response.register.search(/profanityError/i) >= 0){ _profanityError(json); errorMessage += "Profanity Data found.
    "; scrollToTop = true; } if(scrollToTop){ // scroll to top window.scrollTo(0, 0); Recaptcha.reload(); $("#recaptcha_response_field").val(""); $("#RegistrationForm_popup .info").addClass("errorMessage").html(errorMessage); } }, error:function() { window.location = "exceptionController.do"; //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:"text", dataType:"text", type:"GET", success:function(text){ InterstitialController.clearContent(); InterstitialController.display(text); } }); } _loginFailed = function(){ if($("#LoginForm_popup").length > 0){ $(document).data("redirectURL",$("#RedirectURL").val()); $(document).data("RedirectURLQueryString",$("#RedirectURLQueryString").val()); } Login.Failed("jsp/interstitial_failed_login.jsp"); } _invitedUserSuccess = function(){ $.ajax({ url: "jsp/invitedUserSuccess.jsp", cache: false, dataType:"text", type:"GET", success:function(text){ $('body').append(text); _fixDimensions(); _addClose(); // InterstitialController.clearContent(); // InterstitialController.display(text); setTimeout( function(){ $(InterstitialController.interstitial.lightbox).fadeOut("fast"); }, 5000 ); } }); } _uploadRecipeInts = function(){ $.ajax({ url: "jsp/interstitial_upload_error.jsp", cache: false, dataType:"text", type:"GET", success:function(text){ InterstitialController.clearContent(); InterstitialController.display(text,null); _fixDimensions(); _addClose(); } }); } // Added by Abhinandan R..... // Code added here for forgot password interstitial popup Abhinandan R _forgotPassword = function(){ $.ajax({ url: "jsp/interstitial_forgot_password_success.jsp", cache: false, dataType:"text", type:"GET", success:function(text){ //InterstitialController.kill(); //$('body').append(text); //InterstitialController.clearContent(); InterstitialController.display(text,null); _fixDimensions(); _addClose(); } }); } _passwordChange = function(){ $.ajax({ url: "jsp/changePasswordInterstitial.jsp", cache: false, 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, dataType:"text", type:"GET", success:function(text){ $('body').append(text); _fixDimensions(); _addClose(); } }); } _captchaValatationFail = function(){ $.ajax({ url: "jsp/captchaValidationInterstitial.jsp", cache: false, dataType:"text", type:"GET", success:function(text){ $('body').append(text); _fixDimensions(); _addClose(); } }); } _showSystemError = function(){ $.ajax({ url: "jsp/systemerror.html", cache: false, dataType:"text", type:"GET", success:function(text){ $('body').append(text); _fixDimensions(); _addClose(); } }); } _uninvitedUser = function(){ $.ajax({ url: "jsp/uninvited.jsp", cache: false, dataType:"text", type:"GET", success:function(text){ $('body').append(text); _fixDimensions(); _addClose(); } }); } _userExist = function(){ $.ajax({ url: "jsp/userexist.jsp", cache: false, dataType:"text", type:"GET", success:function(text){ $('body').append(text); _fixDimensions(); _addClose(); } }); } _duplicateAlias = function(){ $.ajax({ url: "jsp/duplicateAlias.jsp", cache: false, dataType:"text", type:"GET", success:function(text){ $('body').append(text); _fixDimensions(); _addClose(); } }); } _profanityError = function(_json){ $.ajax({ url: "jsp/showProfanityErrors.jsp", cache: false, 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, 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){ //console.log(_errors); //TODO: inline error handling /* $.ajax({ url: "jsp/errors.html", cache: false, 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("*"); _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 = { "Armed Forces Americas": "AA", "Armed Forces Europe": "AE", "Armed Forces Pacific": "AP", "Alabama": "AL", "Alaska": "AK", "Arizona": "AZ", "Arkansas": "AR", "California": "CA", "Colorado": "CO", "Connecticut": "CT", "Delaware": "DE", "District of Columbia": "DC", "Florida": "FL", "Georgia": "GA", "Hawaii": "HI", "Idaho": "ID", "Illinois": "IL", "Indiana": "IN", "Iowa": "IA", "Kansas": "KS", "Kentucky": "KY", "Louisiana": "LA", "Maine": "ME", "Maryland": "MD", "Massachusetts": "MA", "Michigan": "MI", "Minnesota": "MN", "Mississippi": "MS", "Missouri": "MO", "Montana": "MT", "Nebraska": "NE", "Nevada": "NV", "New Hampshire": "NH", "New Jersey": "NJ", "New Mexico": "NM", "New York": "NY", "North Carolina": "NC", "North Dakota": "ND", "Ohio": "OH", "Oklahoma": "OK", "Oregon": "OR", "Pennsylvania": "PA", "Puerto Rico": "PR", "Rhode Island": "RI", "South Carolina": "SC", "South Dakota": "SD", "Tennessee": "TN", "Texas": "TX", "Utah": "UT", "Vermont": "VT", "Virginia": "VA", "Washington": "WA", "West Virginia": "WV", "Wisconsin": "WI", "Wyoming": "WY" }; 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, 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.search(/form/i) >= 0 && !_form){ _form = $(this); } }) : /* button */ "_onclick" : _href; /* // a better way to write ternary if(_link = !_href){ if(!_onclick){ $(this).parents().map(function(){ if(this.nodeName.search(/form/i) >= 0 && !_form){ _form = $(this); } }); } else { "_onclick" } } else { _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(""); } 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() var h = $(this.objects.image + " img").height() var params = "?source="+($(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.jsp"+params, "RecipeImage", "status=0, toolbar=0, resizable=1, 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 }).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')); 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; if ($.browser.safari) { moveLeft -= 155; } 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") }); }); } }, ieFix : function(elm) { if (($.browser.msie)&&(($.browser.version)==6)){ // IE6 Fix for background image flicker try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {} $(elm).each( function(){ $(this).css({ "background-color" : "transparent", "background-image" : "url(images/snackbar-overlay.gif)", "filter" : "none" }); // Need to position the image/link var img = $(this).find("li a img"); img.each(function(){ $($(this).parents()[0]).css({"display":"block","margin-left":"15px","width" : "112px"}) }); }); } } } $(document).ready(function(){ sfHover.create("#nav li") sfHover.create("#dwnld li") sfHover.ieFix("#dwnld ul.menu") 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", popupContent:"#lightbox .popup .popupContent", close:"#lightbox .close" }, // variables errormessage:{ load:{ title:"Oops!", message:"We did something wrong
    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]; //set an empty callback function instance["callback"] = function(){}; 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(); var $this = $(this); //var $thisID = $(this).attr("id"); //if($thisID == "NavCreateCollectionInterstitial" || $thisID == "DeleteRecipeFromRecipeBox" || $thisID == "DeleteRecipeFromCollection" || $thisID == "CreateCollectionAndRecipe" || $this.hasClass("btn-addto")){ /* if($this.hasClass("link-signin")){ if(!LOGIN){ $(document).data("popupAfterLogin",{togglePopup:true, trigger: $this ); } } */ //TODO: find out why all these params exist ??? object["paramString"] = $(this).attr("params") || ""; object["params"]={}; object["params"]["id"] = $(this).attr("rel") || ""; object["params"]["name"] = $(this).attr("title") || ""; //object["params"]["recipeUrl"] = $(this).attr("recipeUrl"); //object["params"]["collectionName"] = $(this).attr("collectionName"); InterstitialController.getParams( object["params"], $(this).attr("params") ); //if we need to trigger login interstitial then return false here to prevent unnecessary ajax calls if($this.hasClass("link-signin") && LOGIN == false){ $(document).data("popupAfterLogin",$this.attr("trigger")); return; } InterstitialController.open(this); return false; }); }, //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 0) { //this.kill(); getInterior(); } else { getShell(); } } // ajax call to retrieve shell function getShell(){ $.ajax({ url:InterstitialController.interstitial.shell, dataType:"text", type:"GET", success:function(html) { // append to body $('body').append(html); getInterior(); }, error:function() { InterstitialController.error(InterstitialController.errormessage.load) } }); } function getInterior(){ var currentURL = window.location.href; var queryString = ""; //append params as queryString if(params){ var paramSep = url.search("\\?") > 0 ? "&" : "?" ; queryString = paramSep+params; } //append curent url queryString as part of ajax querystring if(currentURL.search("\\?") > 0){ var currentQueryString = currentURL.slice(currentURL.lastIndexOf("?")+1); var paramSep = queryString.search("\\?") >= 0 ? "&" : "?" ; queryString += paramSep+currentQueryString; } $.ajax({ url:url+queryString, dataType:"text", type:"GET", success:function(html){ InterstitialController.display(html, instance); }, error:function(){ InterstitialController.error(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"); var popupContent = $(document.createElement("div")); $(popupContent).addClass("popupContent"); $(popup).append(close); $(popup).append(popupContent); $(lightbox).append(blocker); $(lightbox).append(popup); $('body').append(lightbox); }, error:function(copy) { InterstitialController.clearContent; this.parameters['LoadError'] = { type:"error" } var html = ""; html += "

    " + copy.title + "

    "; html += "

    " + copy.message + "

    "; html += "
    "; html += "
    "; html += ""; html += "
    "; html += "
    "; this.display(html, 'LoadError'); }, step:function(url, instance, type) { if (typeof(instance) == "object"){ instance = instance.getAttribute("trigger"); } $(document).data("routeFromStep", true); $.ajax({ url:url, cache: false, type:"GET", success:function(html){ InterstitialController.parameters[instance].type = type; InterstitialController.display(html, instance); }, 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 popupContent= $(this.interstitial.popupContent); var close = $(this.interstitial.close); // hide the select boxes on the page InterstitialController.toggleSelects(); // append data if(lightbox.length > 0){ //this.kill(); //TODO: add fading and resize effects popupContent.html(html); } else { popupContent.html(html); } // set post login forward paramater if (instance == "loginRequired" || instance == "register" || instance == "InterstitialRegistration"){ var postLogin; if(instance == "loginRequired"){ postLogin = $.trim($(document).data("targetUrl")); } else if (instance == "register" || instance == "InterstitialRegistration"){ postLogin = $.trim($(document).data("loginRedirectCopy")); } else { postLogin = ""; } if(postLogin == "#"){ $("#RedirectURL").val(""); } else if (postLogin.lastIndexOf("?") >= 0 ){ //querystring detected in our target URL and we need to split them var splitURL = postLogin.split("?"); var oldQueryString = $("#RedirectURLQueryString").val(); var newQueryString; if (oldQueryString.length > 0 && oldQueryString != "null"){ //check for "action" already in querystring and remove it if(oldQueryString.lastIndexOf("action=") >= 0 ){ var actionQuery = oldQueryString.substr(oldQueryString.lastIndexOf("action")-1,11); oldQueryString = oldQueryString.replace(actionQuery, ""); } // concatonate original querystring with action newQueryString = oldQueryString +"&"+ splitURL[1]; } else { newQueryString = splitURL[1]; } $("#RedirectURL").val(splitURL[0]); $("#RedirectURLQueryString").val(newQueryString); } else { $("#RedirectURL").val(postLogin); } //copy postLogin for registration popup $(document).data("loginRedirectCopy",postLogin); //set up iterstitial for forgot password link if(instance == "loginRequired"){ if($("#ForgotPassword_popup").length > 0){ InterstitialController.config({ instance:"ForgotPassword", trigger:".forgotPassword", url:"jsp/interstitial_forgot_password.jsp", step:{ success:"jsp/interstitial_forgot_password_success.jsp", error:"jsp/interstitial_load_error.jsp" }, type:"error" }); } } } // type if(instance != null && this.parameters[instance].type){ popup.addClass(this.parameters[instance].type) } else { //now setting width via css //$(this.interstitial.popupContent + " 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" }); popupContent.append(InterstitialController_instance); popupContent.append(InterstitialController_success); popupContent.append(InterstitialController_error); } // show lightbox lightbox.show(); this.dimensions(blocker, popup, instance); blocker.fadeIn('slow'); popup.fadeIn('slow'); close.bind('click',function(){ InterstitialController.close(); }); /* //clicking on blocking layer closes the popup blocker.bind('click',function(){ InterstitialController.close(); }); */ $(document).bind('keydown',function(key){ //bind escape key to close interstitials if(key.keyCode == 27){ InterstitialController.close(); } //bind enter key to submit forms if(key.keyCode == 13){ var $form = $("#lightbox .popup .popupContent form:first"); var $submitButton = $form.find("input[name=Submit]"); var $cancelButton = $form.find("input[name=Cancel]"); if ($submitButton.length > 0){ if($submitButton.attr("onclick")){ key.preventDefault(); $submitButton.trigger("click"); } } else if ($cancelButton.length > 0){ if($cancelButton.attr("onclick")){ key.preventDefault(); $cancelButton.trigger("click"); } } else { $form.submit(); } } }); if(popupContent.find("input:first").length > 0){ popupContent.find("input:first").focus(); } enableButton(); // trigger callback after display if(instance){ this.parameters[instance].callback.call(this); } }, 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; } if(instance && this.parameters[instance].positioned && this.parameters[instance].y_pos ){ y = this.parameters[instance].y_pos - popup.height(); h = h+25; } if(y < 0){ y = 0; } // 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(); InterstitialController.toggleSelects(true); //push recipe box bar back down if we're on search page and triggered a login interstitial by dropping a recipe var $recipeDropBox = $("#recipe-drop-box"); if($recipeDropBox.length > 0){ if($recipeDropBox.height() > 26){ //need to upgrade jQuery UI for this trigger to work as expected //$recipeDropBox.trigger("dropout"); // scale image $("#recipe-box").animate({top:"10"},{duration:"fast"}); $("#recipe-drop-box").animate({height: 26}); // show instructions $("#recipe-box-instructions").fadeIn("fast"); // hide plus $("#recipe-box-plus").fadeOut("fast"); } } }); }); $(document).unbind('keydown'); }, kill:function() { var lightbox = $(this.interstitial.lightbox); lightbox.remove(); $(document).unbind('keydown'); }, // process process:function(form1) { var form = $(form1); var error = false; var form = $(form1); var action = form.attr("action"); var post = {}; var doProcess = false; if($(document).data("routeFromOtherProcess")){ doProcess = true; } else if ($(document).data("clickDisabled") == false){ var submitButton = form.find("input[name=Submit]"); disableButton(submitButton); doProcess = true; } else { doProcess = false; } if(doProcess){ // collect POST $("input:hidden", form).each(function(){ field = $(this).attr("id"); post[field] = $(this).val(); }); $("input:not(:hidden)", form).each(function(){ if(this.type == "text" || this.type == "password"){ $(this).css({ "border":"1px solid", "border-color":"#8e8e8e #cecece #e3e3e3 #cecece" }); } // All interstitial forms will be processed for empty fields here if(this.type == "text" || this.type == "password"){ //attempt to use name as id so that this function is more reusable. if no name then fallback to using id var $this = $(this); var id = $this.attr("name") || $this.attr("id"); var val = $this.val(); if(id.search(/email/i) >= 0){ temp = true; if(ValidEmail(val) == false){ var val = false; } } if(!val || val.length < 1){ error = true; // processing errors here so that we can maintain $this variable $this.addClass("formError"); if($this.prev(".labelWrap").length > 0){ $this.siblings(".labelWrap").addClass("formError"); } } else { post[id] = val; $this.siblings(".labelWrap").removeClass("formError"); } } }); if(error){ enableButton(); return false; } else { if(form.attr("interstitial")){ switch(form.attr("interstitial")){ case "DoLogin": Login.Submit(Login.services.submit, post, form1); //Login_popup.Process(form1); break; case "DoLogin_popup": Login_popup.Process(form1); break; case "DoLogin_Failed": Login.Submit(Login.services.submit, post, form1); break; case "DoRegistration_popup": $(document).data("routeFromStep",true); if(InterstitialController.parameters.register){ InterstitialController.open("register"); } else { InterstitialController.config({ instance:"register", trigger:null, url:"jsp/interstitial_register.jsp", step:{ success:"jsp/interstitial_forgot_password_success.jsp", error:"jsp/interstitial_register_error.jsp" } }); // fire registration interstitial $("#register").trigger('click'); $("#register").remove(); } 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]; } // submit to action url var setDataType = action.indexOf(".do") == -1 ? "text" : "json"; $.ajax({ url:action, cache: false, data:post, dataType:setDataType, type:"POST", success:function(json){ enableButton(); var url = $("#InterstitialController_success").val(); var instance = $("#InterstitialController_instance").val(); // 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) } } else { // HAS json response JsonObjectResponse=json.response; //Copying the values of JSON response so that it can be used whenever required. //------------------------------------------ // 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 are gettig id from json and we don't have id already in our parameters if(json.response.id && (params.indexOf("&id=") == -1)){ params +="&id="+json.response.id; } //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:"POST", success:function(html){ //InterstitialController.clearContent(); InterstitialController.display(html, instance); } }); //this is for semantic errors }else if( json.response.success=="error" ){ if(json.response.message){ params+="&message="+json.response.message; } 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); } // Code added here for forgot password interstitial popup Abhinandan R if(json.response.passwordStatus == "true"){ //Forms._forgotPassword; $.ajax({ url: "jsp/interstitial_forgot_password_success.jsp", cache: false, dataType:"text", type:"GET", success:function(text){ //InterstitialController.kill(); //$('body').append(text); //InterstitialController.clearContent(); InterstitialController.display(text,null); //_fixDimensions(); _addClose(); } }); } // 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{ enableButton(); InterstitialController.error(InterstitialController.errormessage.load); } } }); } // add close var _addClose = function(){ var close = $("#lightbox .close, #lightbox #CancelButton"); close.bind('click',function(){ var lightbox = $("#lightbox"); var blocker = $(".blocker"); var popup = $(".popup"); popup.fadeOut("fast",function(){ blocker.fadeOut("fast",function(){ lightbox.remove(); }); }); }); } if(action == "addRecipe.do"){ Tracking({ Prop:{"prop22":"RecipeBox:Add"} },true); } else if(action == "deleteRecipe.do"){ Tracking({ Prop:{"prop22":"RecipeBox:Delete"}, Event:{"Event11":"deleteFromCollection"} },true); } } } }, // 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 + " #remember"); this.count = 0; }, // process Process:function(form) { var submitButton = $(form).find("input[name=Submit]"); if($(document).data("clickDisabled") == false){ disableButton(submitButton); 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.search(/email/i) >= 0){ 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:"1px solid #FFF" }); } } // if errors if(errors.length > 0){ //set flag to tell Interstitial Controller that we've already done some processing and disabled the trigger $(document).data("routeFromOtherProcess",true); // run interstial for incomplete if (this.showRequired) { this.Required(this.services.required, errors); } else{ this.interstitial = true; this.Failed(this.services.failed); } } else{ // run submit this.Submit(this.services.submit, post, form) } } }, 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" var prevFail = false; //See if Failed was triggered from a previous attempt $("#FailedLoginForm").length > 0 ? prevFail = true : prevFail = false; // InterstitialController InterstitialController.config({ instance:instance, trigger:null, url:url, type:"error", callback:function(){ enableButton(); //trigger error classes if(prevFail){ $("#email_popup, #password_popup").siblings(".labelWrap").addClass("formError").val(""); $("#lightbox p:first").fadeOut().fadeIn().fadeOut().fadeIn(); } $("#RedirectURL").val($(document).data("redirectURL")); $("#RedirectURLQueryString").val($(document).data("RedirectURLQueryString")); InterstitialController.config({ instance:"LinkForForgotPasswordFromJavascript", trigger:".forgotPassword", 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_popup"}); } }); // fire interstitial $("#" + instance).trigger('click') $("#" + instance).remove(); // 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", callback:function(){ $(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_Required"}); } }); // fire interstitial $("#" + instance).trigger('click') $("#" + instance).remove(); 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 var tzInput = $(document.createElement("input")); $(tzInput).attr("type","hidden"); $(tzInput).attr("id","tzOffset"); $(tzInput).attr("name","tzOffset"); $(tzInput).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'); } } //========================================================================================== // LOGIN SPECIFIC FUNCTION INSIDE INTERSTITIALS //========================================================================================== var Login_popup = { // errors and requirements will be returned to current form via ajax, no failed or required service required // services services:{ failed:"jsp/interstitial_failed_login.jsp", submit:"user-login.do" }, // from interstitial interstitial:true, // fields Fields:function(form) { Login.id = form; // variables this.parameters = { form:$(form) } // fields this.required = { Email:$(form + " .txtEmail"), Password:$(form + " .txtPassword") } this.errorMessage ={ Email:"Please provide a valid e-mail address", Password:"Please enter a password" } this.remember = $(form + " .chkRemember"); this.count = 0; }, // process Process:function(form) { this.Fields(form); var postLogin = $.trim($(document).data("targetUrl")) || ""; var postOnClick = $.trim($(document).data("targetOnClick")) || ""; var callback = false; if (postLogin.search(/javascript:/i) >= 0 && postOnClick == ""){ callback = postLogin; } else if (postOnClick.length > 0){ callback = postOnClick; } // run through form var post = {}; for(prop in this.required){ post[prop] = this.required[prop].val(); } this.Submit(this.services.submit, post, form, callback); }, GetPassword:function(e){ $.ajax({ url: "jsp/interstitial_forgot_password.jsp", cache: false, dataType:"html", type:"GET", success:function(result){ $("#lightbox .popupContent").html(result); }, error:function(){ alert("error retriving password form"); } }); }, ProcessPassword:function(){ }, // 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(function() { // listen for lightbox 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_Required" }); }, 100 ) // scroll to top window.scrollTo(0, 0) }, // Submit Submit:function(url, post, formId, callback) { /* 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:url, required:{ email:"string", password:"string" }, callback:callback }); DoLogin.processForm('true'); } } //========================================================================================== // REGISTER SPECIFIC FUNCTION //========================================================================================== var Register = { // services - submit should be directed to register java action services:{ required:"jsp/interstitial_required_field.jsp", submit:"register.do" }, // fields Fields:function(form) { Login.id = form; // variables this.parameters = { form:$(form) } // fields this.required = { Email:$(form + " .txtEmail"), FirstName:$(form + " .txtFirstName"), LastName:$(form + " .txtLastName"), Password:$(form + " .txtPassword"), //commented so it doesn't impact level 1 validation //RePassword:$(form + " #txtRePassword"), Alias:$(form + " .txtUserName"), //commented so it doesn't impact level 1 validation Terms:$(form + " .chkTerms"), Captcha:$(form + " .txtRecaptcha_response_field") } // fields Register.errorMessages = { Email:"Email", FirstName:"First Name", LastName:"Last Name", Password:"Password", //RePassword:"Re-enter Password", ValidEmail:"Please provide a valid e-mail address", PasswordNoMatch:"Your password fields did not match. Please enter your password again.", SmallPassword:"Password should be between 6-20 characters.", Alias:"Alias", Terms:"You must agree to the Terms of Use, Privacy Policy and Infringments Policy.", Captcha:"Captcha" } // fields Register.errorLevels = { Email:1, FirstName:1, LastName:1, Alias:1, Password:1, //RePassword:1, ValidEmail:2, PasswordNoMatch:2, SmallPassword:2, Terms:3, Captcha:1 } }, // 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) { $thisProp = this.required[prop]; $thisProp.css({ "border":"solid 1px", "border-color":"#8e8e8e #cecece #e3e3e3 #cecece" }) var value = $thisProp.val(); // assign errors if($thisProp.attr("type") == "text" || $thisProp.attr("type") == "password"){ if(value) { post[prop] = value; $thisProp.siblings(".labelWrap").removeClass("formError"); if($thisProp.attr("name").search(/password/i) >= 0 && $(form + " .txtRePassword").val().length <= 0){ $(form + " .txtRePassword").siblings(".labelWrap").addClass("formError"); } else if ($thisProp.attr("name").search(/password/i) >= 0 && $(form + " .txtRePassword").val().length > 0){ if(value == $(form + " .txtRePassword").val()){ $(form + " .txtRePassword").siblings(".labelWrap").removeClass("formError"); } } }else{ errors.push(prop) errorLevel = 1; $thisProp.siblings(".labelWrap").addClass("formError"); if($thisProp.attr("name").search(/password/i) >= 0){ $(form + " .txtRePassword").siblings(".labelWrap").addClass("formError"); } } } /* handled in level 3 errors if($thisProp.attr("type") == "checkbox"){ if(!$thisProp.is(":checked")) { $thisProp.siblings(".checkboxLabel").addClass("formCheckboxError"); } else { $thisProp.siblings(".checkboxLabel").removeClass("formCheckboxError"); } } */ } } //all fields have a value, now check for level 2,3 errors if (errorLevel > 3) { //email check level 2 if(ValidEmail(this.required.Email.val()) == false){ errorLevel = 2; invalidEmailOrZip = true; errors.push("ValidEmail"); this.required.Email.siblings(".labelWrap").addClass("formError"); } else { this.required.Email.siblings(".labelWrap").removeClass("formError"); } // password length check level 2 if(this.required.Password.val().length < 6 || this.required.Password.val().length > 20){ errorLevel = 2; errors.push("SmallPassword"); this.required.Password.siblings(".labelWrap").addClass("formError"); } else { this.required.Password.siblings(".labelWrap").removeClass("formError"); } // password match check level 2 if(this.required.Password.val() != $(form + " .txtRePassword").val()) { errorLevel = 2; errors.push("PasswordNoMatch"); this.required.Password.siblings(".labelWrap").addClass("formError"); } else { this.required.Password.siblings(".labelWrap").removeClass("formError"); } //terms check if(!this.required.Terms.is(":checked")) { errorLevel = 3; errors.push("Terms"); this.required.Terms.siblings(".checkboxLabel").addClass("formCheckboxError"); } else { this.required.Terms.siblings(".checkboxLabel").removeClass("formCheckboxError"); } } // if errors if(errors.length > 0){ // errors will be placed inline when form is submitted //this.Required(this.services.required, errors, errorLevel,invalidEmailOrZip) } else { // run submit this.Submit(this.services.submit, post, form) } }, // 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(function() { // listen for lightbox 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, form) { /* 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 (form){ id = form; }else{ id= "#RegistrationForm"; } //set time zone hidden var for Sanjeev //create new input if it doesn't exist if (!($(form + " #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{ $(form + " #tzOffset").attr("value", new Date().getTimezoneOffset()); } //add input to end of form $(form).append(tzInput); DoRegister = new Forms(); DoRegister.init({ id:id, url:url, required:{ email:"string", firstName:"string", lastName:"string", userName:"string", password:"string", rePassword:"string", recaptcha_response_field:"string", terms:"checkbox" } }); DoRegister.processForm('true'); } } //========================================================================================== // RECIPE UPLOAD //========================================================================================== var RecipeUpload = { // services services:{ required:"jsp/interstitial_upload_error.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:"Preparation Time", prepMins:"Preparation 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":" Step 1 of cooking instructions", "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 post = {}; var quantityError = false; var quantityErrors = Array(); //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(prop == "uploadTitle") { if(value == undefined || (document.getElementById("photoStatus").value == "photoDeleted")) { var value = true; } }else if(!$.trim(value)){ var value = false; } // assign errors if(prop != "prepHours" && prop != "prepMins" && prop != "cookHours" && prop != "cookMins" && prop != "mainIngred") { 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"); } } } } // 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) { if($(form + " " + ingredients[col] + row).length > 0){ var value = $(form + " " + ingredients[col] + row).val(); value = $.trim(value); 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(); value = $.trim(value); 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); return true; // added for form 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 -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(function() { // listen for lightbox // 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 this has been copied from http://bangbasil.sapient.com/pem/user-login.do */ //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") // 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.search(/password/i) >= 0){ if(ValidEmail(value) == false){ var value = false; } } //zip code if(prop.search(/zip/i) >= 0){ 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"; var errorText = "Please provide the following required information:"; // InterstitialController InterstitialController.config({ instance:instance, trigger:null, url:url+"?errorText="+escape(errorText), type:"error" }); // fire interstitial $("#" + instance).trigger('click'); $("#" + instance).remove(); // update interstitial var listen = setInterval(function() { // listen for lightbox 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 ResetPswd = { // services services:{ required:"jsp/interstitial_required_field.jsp", mismatch:"", submit:"resetPassword.do" }, // fields Fields:function(form) { Login.id = form; // variables this.parameters = { form:$(form) } // fields this.required = { Password:$(form + " #password"), RePassword:$(form + " #rePassword") } 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.search(/email/i) >= 0){ 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.length < 6 || pw.length > 20){ var errors = Array("Password should be between 6-20 characters"); } } // 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(function() { // listen for lightbox 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, formId) { //set time zone hidden var for Sanjeev Abhi //create new input var id; if (formId){ id = formId; } else { id= "#PasswordForm"; } var tzInput = $(document.createElement("input")); $(tzInput).attr("type","hidden"); $(tzInput).attr("id","tzOffset"); $(tzInput).attr("name","tzOffset"); $(tzInput).attr("value", new Date().getTimezoneOffset()); //add input to end of form $(id).append(tzInput); /* 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:ResetPswd.services.submit, required:{ password:"string", rePassword:"string" } }); DoPassword.processForm('true'); } } var Pswd = { // services services:{ required:"jsp/interstitial_required_field.jsp", mismatch:"", submit:"user-profile.do?varBtn=changePwd" }, // fields Fields:function(form) { Login.id = form; // variables this.parameters = { form:$(form) } // fields this.required = { CurrentPassword:$(form + " #currentPassword"), Password:$(form + " #password"), RePassword:$(form + " #rePassword") } 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.search(/email/i) >= 0){ 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.length < 6 || pw.length > 20){ var errors = Array("Password should be between 6-20 characters"); } } // 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(function() { // listen for lightbox 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_email_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 = {}; var emailFlag = true; // 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; emailFlag = true; } // email if(value && prop.search(/email/i) >= 0){ if(ValidEmail(value) == false){ value = false; emailFlag = 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,emailFlag); } else { // run submit this.Submit(this.services.submit, post); } }, // Required Required:function(url, errors,emailFlag) { // vars for InterstitialController var instance = "InterstitialFromJavascript"; var lightbox = "#lightbox"; var message = lightbox + " .fields"; // InterstitialController InterstitialController.config({ instance:instance, trigger:null, url:url+"?value="+emailFlag, type:"error" }); // fire interstitial $("#" + instance).trigger('click'); $("#" + instance).remove(); // update interstitial var listen = setInterval(function() { // listen for lightbox 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_upload_error.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; } // assign errors !value ? errors.push("Title") : 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 var uploadCaption = $(form + " #uploadCaption"); post["uploadCaption"] = uploadCaption.val(); post["userAction"] = "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(function() { // listen for lightbox 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) { var _url = "displayTitleCaption.do"; $.ajax({ url: _url, cache: false, data:post, dataType:"json", type:"POST", success:function(json){ if(json.response.isTitleCaptionSubmitted == "true"){ window.location = json.response.url } }, error:function(json) { window.location = "exceptionController.do"; //Commented Baseline JS line for Integration//InterstitialController.error(InterstitialController.errormessage.load) } }); } } //-- //========================================================================================== // 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,sendRequest,obj) { // query string var omni_evar = ""; var omni_props = ""; var omni_events = ""; var linkTrackEvents = ""; var linkTrackVars = ""; // loop Evar if(args.Evar){ for(prop in args.Evar){ omni_evar += "s." + prop + "= '" + args.Evar[prop] + "';"; linkTrackVars += (prop + ","); } } // loop Prop if(args.Prop){ for(prop in args.Prop){ omni_props += "s." + prop + "= '" + args.Prop[prop] + "';"; linkTrackVars += (prop + ","); } } var hasEvents = false; // loop Event if(args.Event){ for(prop in args.Event){ hasEvents = true; omni_events += prop + "= '" + args.Event[prop] + "';"; linkTrackEvents += prop; omni_events += "\n"; linkTrackEvents += ","; } //remove comma at the end linkTrackEvents = linkTrackEvents.substring(0,linkTrackEvents.length-1).toLowerCase(); } else{ linkTrackEvents = "None"; } //if hasEvents add events to the end of string, else remove comma linkTrackVars = (hasEvents) ? (linkTrackVars + "events") : linkTrackVars.substring(0,linkTrackVars.length-1); clearOmniData(); var s_account="scrippspem" var s=s_gi(s_account); s.s_doPlugins; //START:Omniture tracking javascript // Set omniture variables if(omni_evar.length >0) eval(omni_evar); if(omni_props.length >0) eval(omni_props); if(omni_events.length >0) eval(omni_events); eval("s.linkTrackVars ='"+ linkTrackVars + "'") ; eval("s.linkTrackEvents ='" + linkTrackEvents + "'"); if (linkTrackEvents.toLowerCase() != "none" ){ eval("s.events = '" + linkTrackEvents + "'"); } if(sendRequest){ if (obj){ s.tl(obj,'o','Link Name'); } else { s.tl(true,'o','Link Name'); } clearOmniData(); } //END:Omniture tracking javascript } function clearOmniData() { var clrProp = ""; var clrEvar = ""; for(i=7;i<41;i++){ clrProp += "s.prop" + i + "= '';"; } for(i=3;i<21;i++){ clrEvar += "s.eVar" + i + "= '';"; } eval(clrProp); eval(clrEvar); eval("s.events = ''"); eval("s.linkTrackVars = ''"); eval("s.linkTrackEvents = ''"); } //========================================================================================== // 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, top:0 }); // 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", ADD_TO_COLL_DETAIL_UPDATE : "addToCollDetail", DELETE_RECIPE_UPDATE : "deleteRecipe", FAVOURITE_RECIPE : "favourite", UNFAVOURITE_RECIPE : "unfavourite", FAVOURITE_RECIPE_TEXT : "Add to favorites", 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){ name=SpecialCharater.convert(name); var tmpHref=href.split("="); tmpHref[1]= escape(tmpHref[1]); //getting the collectionname and escaping it href=tmpHref.join("="); //add to left hand pane var text = "
  • " +""+name+" ("+num+")" +"
  • " $(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( ""+ ""+name+""+ ""+d.format("longDate")+""+ ""+num+""+ ""+ ""+ ""+ "" ); //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+" .collapsable 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 += "
  • "+html+"
  • "; } }); $(RBUpdater.CUST_COLLECTION_MENU + " .collapsable").empty(); $(RBUpdater.CUST_COLLECTION_MENU + " .collapsable").html(newElem); //add a hidden field with id for storing name var _tmpColelctioName=$("#" +id+" th:first").html(); $("#manageCollectionCommand").append( "" ); //remove from main table $(RBUpdater.CUST_COLLECTION_TABLE+" #"+id).remove(); $(RBUpdater.CUST_COLLECTION_TABLE).trigger("update"); }, renameCustomCollection : function( id, name, num ){ //add a hidden field with id for storing old name var _tmpColelctioName=$("#" +id+" th:first").html(); $("#manageCollectionCommand").append( "" ); //rename in left-hand pane $(RBUpdater.CUST_COLLECTION_MENU+ " [rel="+id+"] a span em").remove(); $(RBUpdater.CUST_COLLECTION_MENU+ " [rel="+id+"] a span").append(""+name +" ("+num+")"); $(RBUpdater.CUST_COLLECTION_MENU+ " [rel="+id+"]").attr("title", name); $(RBUpdater.CUST_COLLECTION_MENU+ " [rel="+id+"] a").attr("href", "recipeBox.do?collectionName="+escape(name) ); //rename in main table $(RBUpdater.CUST_COLLECTION_TABLE+" #"+id+" th").remove(); $(RBUpdater.CUST_COLLECTION_TABLE+" #"+id).prepend(""+name+""); $(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(); if( curText == "0" && $(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("

    This collection is empty.

    "); } } }, addToCollection : function ( id, recipeID, RBDetailUpdate ){ //find id of favourite collection var favID = $("#favorites", document).attr("rel"); if(id.length < 1){ return false;} id = id.split(","); //change count for each for( x=0; x
    " ); //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 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;} //add a hidden field with id for storing recipe name var _tmpRecipeName=$("#title_"+id).html(); $("#recipebox").append( "" ); 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; } //if there are no recipes left, we must change the text //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("

    This collection is empty. Go ahead and add some recipes to it or delete it

    "); } } }, 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); var prop23 = "Recipe: more Ingredient"; Tracking({ Prop:{"prop23":prop23} },true); } 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(""); }, out: function(ev, ui){ $("#recipe-drag-box .drag-plus").remove(); }, drop: function(ev, ui) { if (LOGIN) { // 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 : "addRecipe.do", MAKE_PUBLIC_CLASS : "icn-public-lg", MAKE_PRIVATE_CLASS : "icn-private-lg", SOURCE_ICON : "icon", SOURCE_LINK : "link", changeFavClick : function(e, source, forceState){ var choice,theElem,action,favouriteServiceURL; if(LOGIN){ if(forceState){ choice = forceState; theElem = $(".icn-fav-lg,.icn-unfav-lg"); } else { e.preventDefault(); //set local vars theElem = $(e.target); if( source=="icon" ){ 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; choice = theElem.hasClass(RBDetailUpdater.FAVOURITE_CLASS) ? RBDetailUpdater.FAVOURITE_RECIPE : RBDetailUpdater.UNFAVOURITE_RECIPE; } } if(choice == RBDetailUpdater.FAVOURITE_RECIPE){ if(theElem.hasClass("icn-unfav-lg")){ return false; } action = "add"; favouriteServiceURL = "addRecipe.do"; } else { if(theElem.hasClass("icn-fav-lg")){ return false; } action = "remove"; favouriteServiceURL = "deleteRecipe.do"; } var id = theElem.attr("rel"); var title = theElem.attr("title"); var recipeSource = theElem.attr("sourceName"); var recipeUrl = theElem.attr("recipeUrl"); var recipeId = theElem.attr("rel"); // make ajax call $.ajax({ url: favouriteServiceURL, cache: false, data:{ "id": id, "title":title, "action":action,"id":id, "recipeSource":recipeSource,"recipeURL":recipeUrl }, 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 ){ e.preventDefault(); if (LOGIN){ 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); } } }); } return false; }, addToBox : function ( id, title ){ //build new list of CTAs CTAString = ""; CTAString +=""; //add to page $(".ctaHolder-public").html(CTAString); //add the heart icon beside the title var headerString = "\"[FAVORITE]\""+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_recipe_existsin_collections.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; }); $("#searchText").bind('keypress',function(e){ if(e.which == 13 || e.keyCode == 13){ if($("#searchText").length > 0 && $("#searchText")[0].focused ){ $("#searchButton").click(); } } }); }); // Starting HomeBase Image Rotation var rand1 = 0; var useRand = 0; imagesSource = new Array; imagesSource[1] = "images/grp-homebase1.jpg"; imagesSource[2] = "images/grp-homebase2.jpg"; imagesSource[3] = "images/grp-homebase3.jpg"; imagesSource[4] = "images/grp-homebase4.jpg"; imagesSource[5] = "images/grp-homebase5.jpg"; imagesSource[6] = "images/grp-homebase6.jpg"; imagesSource[7] = "images/grp-homebase7.jpg"; imagesSource[8] = "images/grp-homebase8.jpg"; imagesSource[9] = "images/grp-homebase9.jpg"; imagesSource[10] = "images/grp-homebase10.jpg"; imagesSource[11] = "images/grp-homebase11.jpg"; imagesSource[12] = "images/grp-homebase12.jpg"; imagesSource[13] = "images/grp-homebase13.jpg"; imagesSource[14] = "images/grp-homebase14.jpg"; imagesSource[15] = "images/grp-homebase15.jpg"; imagesSource[16] = "images/grp-homebase16.jpg"; imagesSource[17] = "images/grp-homebase17.jpg"; imagesSource[18] = "images/grp-homebase18.jpg"; function swapPic(){ var imgnum = imagesSource.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" }); $(this).fadeIn(); }); useRand = rand1; document.randimg.src = imagesSource[useRand]; } } var rand2 = 0; var useRand1 = 0; imagesSource1 = new Array; imagesSource1[0] = "images/DYK_HP_1a.gif"; imagesSource1[1] = "images/DYK_HP_1b.gif"; imagesSource1[2] = "images/DYK_HP_1c.gif"; imagesSource1[3] = "images/DYK_HP_1d.gif"; imagesSource1[4] = "images/DYK_HP_2a.gif"; imagesSource1[5] = "images/DYK_HP_2b.gif"; imagesSource1[6] = "images/DYK_HP_2c.gif"; imagesSource1[7] = "images/DYK_HP_2d.gif"; imagesSource1[8] = "images/DYK_HP_2e.gif"; imagesSource1[9] = "images/DYK_HP_2f.gif"; // With toolbar starts imagesSource1[10] = "images/DYK_HP_3a.gif"; imagesSource1[11] = "images/DYK_HP_3b.gif"; imagesSource1[12] = "images/DYK_HP_3c.gif"; imagesSource1[13] = "images/DYK_HP_3d.gif"; imagesSource1[14] = "images/DYK_HP_3e.gif"; imagesSource1[15] = "images/DYK_HP_3f.gif"; imagesSource1[16] = "images/DYK_HP_3g.gif"; imagesSource1[17] = "images/DYK_HP_4a.gif"; imagesSource1[18] = "images/DYK_HP_4b.gif"; imagesSource1[19] = "images/DYK_HP_4c.gif"; imagesSource1[20] = "images/DYK_HP_4d.gif"; imagesSource1[21] = "images/DYK_HP_4e.gif"; imagesSource1[22] = "images/DYK_HP_4f.gif"; imagesSource1[23] = "images/DYK_HP_5a.gif"; imagesSource1[24] = "images/DYK_HP_5b.gif"; imagesSource1[25] = "images/DYK_HP_5c.gif"; imagesSource1[26] = "images/DYK_HP_5d.gif"; imagesSource1[27] = "images/DYK_HP_5e.gif"; imagesSource1[28] = "images/DYK_HP_5f.gif"; imagesSource1[29] = "images/DYK_HP_5g.gif"; imagesSource1[30] = "images/DYK_HP_6a.gif"; imagesSource1[31] = "images/DYK_HP_6b.gif"; imagesSource1[32] = "images/DYK_HP_7a.gif"; imagesSource1[33] = "images/DYK_HP_7b.gif"; imagesSource1[34] = "images/DYK_HP_7c.gif"; //With toolbar ends //Without toolbar starts imagesSource1[10] = "images/DYK_HP_4a.gif"; imagesSource1[11] = "images/DYK_HP_4b.gif"; imagesSource1[12] = "images/DYK_HP_4c.gif"; imagesSource1[13] = "images/DYK_HP_4d.gif"; imagesSource1[14] = "images/DYK_HP_4e.gif"; imagesSource1[15] = "images/DYK_HP_4f.gif"; imagesSource1[16] = "images/DYK_HP_5a.gif"; imagesSource1[17] = "images/DYK_HP_5b.gif"; imagesSource1[18] = "images/DYK_HP_5c.gif"; imagesSource1[19] = "images/DYK_HP_5d.gif"; imagesSource1[20] = "images/DYK_HP_5e.gif"; imagesSource1[21] = "images/DYK_HP_5f.gif"; imagesSource1[22] = "images/DYK_HP_5g.gif"; imagesSource1[23] = "images/DYK_HP_6a.gif"; imagesSource1[24] = "images/DYK_HP_6b.gif"; imagesSource1[25] = "images/DYK_HP_7a.gif"; imagesSource1[26] = "images/DYK_HP_7b.gif"; imagesSource1[27] = "images/DYK_HP_7c.gif"; // Without toolbar starts ends function swapPic1() { var imgnum1 = imagesSource1.length - 1; do { var randnum1 = Math.random(); rand2 = Math.round((imgnum1 - 1) * randnum1) + 1; } while (rand2 == useRand1){ 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" }).bind('click',function(){ // change the location from # to corresponding page please window.location = "#"; }); useRand1 = rand2; //document.randimg1.src = imagesSource1[useRand1]; } } // 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 datatransfer.js * * @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 Communicator.ELWMS_ELEMENT_NAME */ 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 returnvalue-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= 0) { var idx = _secText.indexOf(":"); _secText = _secText.substring(0,idx); } var omTrk = _secText + ":" + p38 + ":Previous"; Tracking({ Prop:{"prop38":omTrk} },true); Carousel.slide($(this).attr("trigger"), 1); }); $(next).bind('click',function(){ // add tracking for next var p38 = $(this).attr("trigger"); var _secText = $(this).parent().parent().find("h3").text(); if(_secText.indexOf(":") >= 0) { var idx = _secText.indexOf(":"); _secText = _secText.substring(0,idx); } var omTrk = _secText + ":" + p38 + ":Next"; Tracking({ Prop:{"prop38":omTrk} },true); 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"}); } } // Carousel - end // Special Characters- start var SpecialCharater = { convert: function(sStr){ sStr=sStr.split(""); //converting into array for IE compatability. var Dictionary = { splChar: [" ", "&","<", ">", "\"", "\'", "\\"], htmlEntity: [" ", "&","<", ">", ""","'","\"] }; var aNewStringArray=new Array(); //This will store new values $.each(sStr, function(indexStr,itemStr) { $.each(Dictionary.splChar, function(indexSpecialChar, itemSpecialChar) { if(itemSpecialChar == itemStr) { itemStr=Dictionary.htmlEntity[indexSpecialChar]; } }); aNewStringArray.push(itemStr); }); return aNewStringArray.join(""); } } // Special Characters- end var JsonObjectResponse={};// This variable will carry the response //_tmpObjectSelectedCollection will hold ID and text of selected collections when a recipe is added to the collection. var _tmpObjectSelectedCollection={ id:[], text:[] }; //Function fGetCollectionNames will return the collection names as a form of string. function fGetCollectionNames(sCollectionIds, _tmpObjectSelectedCollection) { sCollectionIds=sCollectionIds.split(","); var _tmpCollectionString=""; $.each(sCollectionIds, function(index, val) { val=$.trim(val); var separator = (index == (sCollectionIds.length-2)) ? " and " : (index == (sCollectionIds.length-1)) ? "" : ", "; _tmpCollectionString +=_tmpObjectSelectedCollection.text[$.inArray(val, _tmpObjectSelectedCollection.id)] + separator; }); return _tmpCollectionString; } function disableButton(button){ //button arg should be a jQuery object if($(document).data("ajaxButton")){ enableButton(); } button.addClass("disabled"); $(document).data("ajaxButton",button); $(document).data("clickDisabled",true); } function enableButton(button){ var $button = $(document).data("ajaxButton") || button; $button.removeClass("disabled"); $(document).data("clickDisabled",false); $(document).data("routeFromOtherProcess",false); $(document).data("routeFromStep",false); }