/*
 * jQuery JavaScript Library v1.3.2
 * http://jquery.com/
 *
 * Copyright (c) 2009 John Resig
 * Dual licensed under the MIT and GPL licenses.
 * http://docs.jquery.com/License
 *
 * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
 * Revision: 6246
 */
(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],"find",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),"find",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement("div");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find("*").andSelf(),F=0;E.find("*").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],"events");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,"closest",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F<J;F++){var G=M[F];if(G.selected){K=o(G).val();if(H){return K}L.push(K)}}return L}return(E.value||"").replace(/\r/g,"")}return g}if(typeof K==="number"){K+=""}return this.each(function(){if(this.nodeType!=1){return}if(o.isArray(K)&&/radio|checkbox/.test(this.type)){this.checked=(o.inArray(this.value,K)>=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(J,M,L){if(this[0]){var I=(this[0].ownerDocument||this[0]).createDocumentFragment(),F=o.clean(J,(this[0].ownerDocument||this[0]),I),H=I.firstChild;if(H){for(var G=0,E=this.length;G<E;G++){L.call(K(this[G],H),this.length>1||G>0?I.cloneNode(true):I)}}if(F){o.each(F,z)}}return this;function K(N,O){return M&&o.nodeName(N,"table")&&o.nodeName(O,"tr")?(N.getElementsByTagName("tbody")[0]||N.appendChild(N.ownerDocument.createElement("tbody"))):N}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H<I;H++){if((G=arguments[H])!=null){for(var F in G){var K=J[F],L=G[F];if(J===L){continue}if(E&&L&&typeof L==="object"&&!L.nodeType){J[F]=o.extend(E,K||(L.length!=null?[]:{}),L)}else{if(L!==g){J[F]=L}}}}}return J};var b=/z-?index|font-?weight|opacity|zoom|line-?height/i,q=document.defaultView||{},s=Object.prototype.toString;o.extend({noConflict:function(E){l.$=p;if(E){l.jQuery=y}return o},isFunction:function(E){return s.call(E)==="[object Function]"},isArray:function(E){return s.call(E)==="[object Array]"},isXMLDoc:function(E){return E.nodeType===9&&E.documentElement.nodeName!=="HTML"||!!E.ownerDocument&&o.isXMLDoc(E.ownerDocument)},globalEval:function(G){if(G&&/\S/.test(G)){var F=document.getElementsByTagName("head")[0]||document.documentElement,E=document.createElement("script");E.type="text/javascript";if(o.support.scriptEval){E.appendChild(document.createTextNode(G))}else{E.text=G}F.insertBefore(E,F.firstChild);F.removeChild(E)}},nodeName:function(F,E){return F.nodeName&&F.nodeName.toUpperCase()==E.toUpperCase()},each:function(G,K,F){var E,H=0,I=G.length;if(F){if(I===g){for(E in G){if(K.apply(G[E],F)===false){break}}}else{for(;H<I;){if(K.apply(G[H++],F)===false){break}}}}else{if(I===g){for(E in G){if(K.call(G[E],E,G[E])===false){break}}}else{for(var J=G[0];H<I&&K.call(J,H,J)!==false;J=G[++H]){}}}return G},prop:function(H,I,G,F,E){if(o.isFunction(I)){I=I.call(H,F)}return typeof I==="number"&&G=="curCSS"&&!b.test(E)?I+"px":I},className:{add:function(E,F){o.each((F||"").split(/\s+/),function(G,H){if(E.nodeType==1&&!o.className.has(E.className,H)){E.className+=(E.className?" ":"")+H}})},remove:function(E,F){if(E.nodeType==1){E.className=F!==g?o.grep(E.className.split(/\s+/),function(G){return !o.className.has(F,G)}).join(" "):""}},has:function(F,E){return F&&o.inArray(E,(F.className||F).toString().split(/\s+/))>-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(H,F,J,E){if(F=="width"||F=="height"){var L,G={position:"absolute",visibility:"hidden",display:"block"},K=F=="width"?["Left","Right"]:["Top","Bottom"];function I(){L=F=="width"?H.offsetWidth:H.offsetHeight;if(E==="border"){return}o.each(K,function(){if(!E){L-=parseFloat(o.curCSS(H,"padding"+this,true))||0}if(E==="margin"){L+=parseFloat(o.curCSS(H,"margin"+this,true))||0}else{L-=parseFloat(o.curCSS(H,"border"+this+"Width",true))||0}})}if(H.offsetWidth!==0){I()}else{o.swap(H,G,I)}return Math.max(0,Math.round(L))}return o.curCSS(H,F,J)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,S){if(typeof S==="number"){S+=""}if(!S){return}if(typeof S==="string"){S=S.replace(/(<(\w+)[^>]*?)\/>/g,function(U,V,T){return T.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?U:V+"></"+T+">"});var O=S.replace(/^\s+/,"").substring(0,10).toLowerCase();var Q=!O.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!O.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!O.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!O.indexOf("<td")||!O.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!O.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||!o.support.htmlSerialize&&[1,"div<div>","</div>"]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/<tbody/i.test(S),N=!O.indexOf("<table")&&!R?L.firstChild&&L.firstChild.childNodes:Q[1]=="<table>"&&!R?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(S)){L.insertBefore(K.createTextNode(S.match(/^\s*/)[0]),L.firstChild)}S=o.makeArray(L.childNodes)}if(S.nodeType){G.push(S)}else{G=o.merge(G,S)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E<F;E++){if(H[E]===G){return E}}return -1},merge:function(H,E){var F=0,G,I=H.length;if(!o.support.getAll){while((G=E[F++])!=null){if(G.nodeType!=8){H[I++]=G}}}else{while((G=E[F++])!=null){H[I++]=G}}return H},unique:function(K){var F=[],E={};try{for(var G=0,H=K.length;G<H;G++){var J=o.data(K[G]);if(!E[J]){E[J]=true;F.push(K[G])}}}catch(I){F=K}return F},grep:function(F,J,E){var G=[];for(var H=0,I=F.length;H<I;H++){if(!E!=!J(F[H],H)){G.push(F[H])}}return G},map:function(E,J){var F=[];for(var G=0,H=E.length;G<H;G++){var I=J(E[G],G);if(I!=null){F[F.length]=I}}return F.concat.apply([],F)}});var C=navigator.userAgent.toLowerCase();o.browser={version:(C.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1],safari:/webkit/.test(C),opera:/opera/.test(C),msie:/msie/.test(C)&&!/opera/.test(C),mozilla:/mozilla/.test(C)&&!/(compatible|webkit)/.test(C)};o.each({parent:function(E){return E.parentNode},parents:function(E){return o.dir(E,"parentNode")},next:function(E){return o.nth(E,2,"nextSibling")},prev:function(E){return o.nth(E,2,"previousSibling")},nextAll:function(E){return o.dir(E,"nextSibling")},prevAll:function(E){return o.dir(E,"previousSibling")},siblings:function(E){return o.sibling(E.parentNode.firstChild,E)},children:function(E){return o.sibling(E.firstChild)},contents:function(E){return o.nodeName(E,"iframe")?E.contentDocument||E.contentWindow.document:o.makeArray(E.childNodes)}},function(E,F){o.fn[E]=function(G){var H=o.map(this,F);if(G&&typeof G=="string"){H=o.multiFilter(G,H)}return this.pushStack(o.unique(H),E,G)}});o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(E,F){o.fn[E]=function(G){var J=[],L=o(G);for(var K=0,H=L.length;K<H;K++){var I=(K>0?this.clone(true):this).get();o.fn[F].apply(o(L[K]),I);J=J.concat(I)}return this.pushStack(J,E,G)}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}});
/*
 * Sizzle CSS Selector Engine - v0.9.3
 *  Copyright 2009, The Dojo Foundation
 *  Released under the MIT, BSD, and GPL Licenses.
 *  More information: http://sizzlejs.com/
 */
(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa<ab.length;aa++){if(ab[aa]===ab[aa-1]){ab.splice(aa--,1)}}}}}return ab};F.matches=function(T,U){return F(T,null,null,U)};F.find=function(aa,T,ab){var Z,X;if(!aa){return[]}for(var W=0,V=I.order.length;W<V;W++){var Y=I.order[W],X;if((X=I.match[Y].exec(aa))){var U=RegExp.leftContext;if(U.substr(U.length-1)!=="\\"){X[1]=(X[1]||"").replace(/\\/g,"");Z=I.find[Y](X,T,ab);if(Z!=null){aa=aa.replace(I.match[Y],"");break}}}}if(!Z){Z=T.getElementsByTagName("*")}return{set:Z,expr:aa}};F.filter=function(ad,ac,ag,W){var V=ad,ai=[],aa=ac,Y,T,Z=ac&&ac[0]&&Q(ac[0]);while(ad&&ac.length){for(var ab in I.filter){if((Y=I.match[ab].exec(ad))!=null){var U=I.filter[ab],ah,af;T=false;if(aa==ai){ai=[]}if(I.preFilter[ab]){Y=I.preFilter[ab](Y,aa,ag,ai,W,Z);if(!Y){T=ah=true}else{if(Y===true){continue}}}if(Y){for(var X=0;(af=aa[X])!=null;X++){if(af){ah=U(af,Y,X,aa);var ae=W^!!ah;if(ag&&ah!=null){if(ae){T=true}else{aa[X]=false}}else{if(ae){ai.push(af);T=true}}}}}if(ah!==g){if(!ag){aa=ai}ad=ad.replace(I.match[ab],"");if(!T){return[]}break}}}if(ad==V){if(T==null){throw"Syntax error, unrecognized expression: "+ad}else{break}}V=ad}return aa};var I=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(T){return T.getAttribute("href")}},relative:{"+":function(aa,T,Z){var X=typeof T==="string",ab=X&&!/\W/.test(T),Y=X&&!ab;if(ab&&!Z){T=T.toUpperCase()}for(var W=0,V=aa.length,U;W<V;W++){if((U=aa[W])){while((U=U.previousSibling)&&U.nodeType!==1){}aa[W]=Y||U&&U.nodeName===T?U||false:U===T}}if(Y){F.filter(T,aa,true)}},">":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){var W=Y.parentNode;Z[V]=W.nodeName===U?W:false}}}else{for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){Z[V]=X?Y.parentNode:Y.parentNode===U}}if(X){F.filter(U,Z,true)}}},"":function(W,U,Y){var V=L++,T=S;if(!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("parentNode",U,V,W,X,Y)},"~":function(W,U,Y){var V=L++,T=S;if(typeof U==="string"&&!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("previousSibling",U,V,W,X,Y)}},find:{ID:function(U,V,W){if(typeof V.getElementById!=="undefined"&&!W){var T=V.getElementById(U[1]);return T?[T]:[]}},NAME:function(V,Y,Z){if(typeof Y.getElementsByName!=="undefined"){var U=[],X=Y.getElementsByName(V[1]);for(var W=0,T=X.length;W<T;W++){if(X[W].getAttribute("name")===V[1]){U.push(X[W])}}return U.length===0?null:U}},TAG:function(T,U){return U.getElementsByTagName(T[1])}},preFilter:{CLASS:function(W,U,V,T,Z,aa){W=" "+W[1].replace(/\\/g,"")+" ";if(aa){return W}for(var X=0,Y;(Y=U[X])!=null;X++){if(Y){if(Z^(Y.className&&(" "+Y.className+" ").indexOf(W)>=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return U<T[3]-0},gt:function(V,U,T){return U>T[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W<T;W++){if(Y[W]===Z){return false}}return true}}}},CHILD:function(T,W){var Z=W[1],U=T;switch(Z){case"only":case"first":while(U=U.previousSibling){if(U.nodeType===1){return false}}if(Z=="first"){return true}U=T;case"last":while(U=U.nextSibling){if(U.nodeType===1){return false}}return true;case"nth":var V=W[2],ac=W[3];if(V==1&&ac==0){return true}var Y=W[0],ab=T.parentNode;if(ab&&(ab.sizcache!==Y||!T.nodeIndex)){var X=0;for(U=ab.firstChild;U;U=U.nextSibling){if(U.nodeType===1){U.nodeIndex=++X}}ab.sizcache=Y}var aa=T.nodeIndex-ac;if(V==0){return aa==0}else{return(aa%V==0&&aa/V>=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V<T;V++){U.push(X[V])}}else{for(var V=0;X[V];V++){U.push(X[V])}}}return U}}var G;if(document.documentElement.compareDocumentPosition){G=function(U,T){var V=U.compareDocumentPosition(T)&4?-1:U===T?0:1;if(V===0){hasDuplicate=true}return V}}else{if("sourceIndex" in document.documentElement){G=function(U,T){var V=U.sourceIndex-T.sourceIndex;if(V===0){hasDuplicate=true}return V}}else{if(document.createRange){G=function(W,U){var V=W.ownerDocument.createRange(),T=U.ownerDocument.createRange();V.selectNode(W);V.collapse(true);T.selectNode(U);T.collapse(true);var X=V.compareBoundaryPoints(Range.START_TO_END,T);if(X===0){hasDuplicate=true}return X}}}}(function(){var U=document.createElement("form"),V="script"+(new Date).getTime();U.innerHTML="<input name='"+V+"'/>";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="<a href='#'></a>";if(T.firstChild&&typeof T.firstChild.getAttribute!=="undefined"&&T.firstChild.getAttribute("href")!=="#"){I.attrHandle.href=function(U){return U.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement("div");U.innerHTML="<p class='TEST'></p>";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="<div class='test e'></div><div class='test'></div>";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1&&!ac){T.sizcache=Y;T.sizset=W}if(T.nodeName===Z){X=T;break}T=T[U]}ad[W]=X}}}function S(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1){if(!ac){T.sizcache=Y;T.sizset=W}if(typeof Z!=="string"){if(T===Z){X=true;break}}else{if(F.filter(Z,[T]).length>0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z<U;Z++){F(T,V[Z],W)}return F.filter(X,W)};o.find=F;o.filter=F.filter;o.expr=F.selectors;o.expr[":"]=o.expr.filters;F.selectors.filters.hidden=function(T){return T.offsetWidth===0||T.offsetHeight===0};F.selectors.filters.visible=function(T){return T.offsetWidth>0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F<E.length){o.event.proxy(G,E[F++])}return this.click(o.event.proxy(G,function(H){this.lastToggle=(this.lastToggle||0)%F;H.preventDefault();return E[this.lastToggle++].apply(this,arguments)||false}))},hover:function(E,F){return this.mouseenter(E).mouseleave(F)},ready:function(E){B();if(o.isReady){E.call(document,o)}else{o.readyList.push(E)}return this},live:function(G,F){var E=o.event.proxy(F);E.guid+=this.selector+G;o(document).bind(i(G,this.selector),this.selector,E);return this},die:function(F,E){o(document).unbind(i(F,this.selector),E?{guid:E.guid+this.selector+F}:null);return this}});function c(H){var E=RegExp("(^|\\.)"+H.type+"(\\.|$)"),G=true,F=[];o.each(o.data(this,"events").live||[],function(I,J){if(E.test(J.type)){var K=o(H.target).closest(J.data)[0];if(K){F.push({elem:K,fn:J})}}});F.sort(function(J,I){return o.data(J.elem,"closest")-o.data(I.elem,"closest")});o.each(F,function(){if(this.fn.call(this.elem,H,this.fn.data)===false){return(G=false)}});return G}function i(F,E){return["live",F,E.replace(/\./g,"`").replace(/ /g,"|")].join(".")}o.extend({isReady:false,readyList:[],ready:function(){if(!o.isReady){o.isReady=true;if(o.readyList){o.each(o.readyList,function(){this.call(document,o)});o.readyList=null}o(document).triggerHandler("ready")}}});var x=false;function B(){if(x){return}x=true;if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);o.ready()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",arguments.callee);o.ready()}});if(document.documentElement.doScroll&&l==l.top){(function(){if(o.isReady){return}try{document.documentElement.doScroll("left")}catch(E){setTimeout(arguments.callee,0);return}o.ready()})()}}}o.event.add(l,"load",o.ready)}o.each(("blur,focus,load,resize,scroll,unload,click,dblclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error").split(","),function(F,E){o.fn[E]=function(G){return G?this.bind(E,G):this.trigger(E)}});o(l).bind("unload",function(){for(var E in o.cache){if(E!=1&&o.cache[E].handle){o.event.remove(o.cache[E].handle.elem)}}});(function(){o.support={};var F=document.documentElement,G=document.createElement("script"),K=document.createElement("div"),J="script"+(new Date).getTime();K.style.display="none";K.innerHTML='   <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';var H=K.getElementsByTagName("*"),E=K.getElementsByTagName("a")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName("tbody").length,objectAll:!!K.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!K.getElementsByTagName("link").length,style:/red/.test(E.getAttribute("style")),hrefNormalized:E.getAttribute("href")==="/a",opacity:E.style.opacity==="0.5",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type="text/javascript";try{G.appendChild(document.createTextNode("window."+J+"=1;"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent("onclick",function(){o.support.noCloneEvent=false;K.detachEvent("onclick",arguments.callee)});K.cloneNode(true).fireEvent("onclick")}o(function(){var L=document.createElement("div");L.style.width=L.style.paddingLeft="1px";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L).style.display="none"})})();var w=o.support.cssFloat?"cssFloat":"styleFloat";o.props={"for":"htmlFor","class":"className","float":w,cssFloat:w,styleFloat:w,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!=="string"){return this._load(G)}var I=G.indexOf(" ");if(I>=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("<div/>").append(M.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},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(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H<F;H++){var E=o.data(this[H],"olddisplay");this[H].style.display=E||"";if(o.css(this[H],"display")==="none"){var G=this[H].tagName,K;if(m[G]){K=m[G]}else{var I=o("<"+G+" />").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H<F;H++){this[H].style.display=o.data(this[H],"olddisplay")||""}return this}},hide:function(H,I){if(H){return this.animate(t("hide",3),H,I)}else{for(var G=0,F=this.length;G<F;G++){var E=o.data(this[G],"olddisplay");if(!E&&E!=="none"){o.data(this[G],"olddisplay",o.css(this[G],"display"))}}for(var G=0,F=this.length;G<F;G++){this[G].style.display="none"}return this}},_toggle:o.fn.toggle,toggle:function(G,F){var E=typeof G==="boolean";return o.isFunction(G)&&o.isFunction(F)?this._toggle.apply(this,arguments):G==null||E?this.each(function(){var H=E?G:o(this).is(":hidden");o(this)[H?"show":"hide"]()}):this.animate(t("toggle",3),G,F)},fadeTo:function(E,G,F){return this.animate({opacity:G},E,F)},animate:function(I,F,H,G){var E=o.speed(F,H,G);return this[E.queue===false?"each":"queue"](function(){var K=o.extend({},E),M,L=this.nodeType==1&&o(this).is(":hidden"),J=this;for(M in I){if(I[M]=="hide"&&L||I[M]=="show"&&!L){return K.complete.call(this)}if((M=="height"||M=="width")&&this.style){K.display=o.css(this,"display");K.overflow=this.style.overflow}}if(K.overflow!=null){this.style.overflow="hidden"}K.curAnim=o.extend({},I);o.each(I,function(O,S){var R=new o.fx(J,K,O);if(/toggle|show|hide/.test(S)){R[S=="toggle"?L?"show":"hide":S](I)}else{var Q=S.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),T=R.cur(true)||0;if(Q){var N=parseFloat(Q[2]),P=Q[3]||"px";if(P!="px"){J.style[O]=(N||1)+P;T=((N||1)/R.cur(true))*T;J.style[O]=T+P}if(Q[1]){N=((Q[1]=="-="?-1:1)*N)+T}R.custom(T,N,P)}else{R.custom(T,S,"")}}});return true})},stop:function(F,E){var G=o.timers;if(F){this.queue([])}this.each(function(){for(var H=G.length-1;H>=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J<K.length;J++){if(!K[J]()){K.splice(J--,1)}}if(!K.length){clearInterval(n);n=g}},13)}},show:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.show=true;this.custom(this.prop=="width"||this.prop=="height"?1:0,this.cur());o(this.elem).show()},hide:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(H){var G=e();if(H||G>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})();
/*
 * jQuery UI 1.7
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */jQuery.ui||(function(c){var i=c.fn.remove,d=c.browser.mozilla&&(parseFloat(c.browser.version)<1.9);c.ui={version:"1.7",plugin:{add:function(k,l,n){var m=c.ui[k].prototype;for(var j in n){m.plugins[j]=m.plugins[j]||[];m.plugins[j].push([l,n[j]])}},call:function(j,l,k){var n=j.plugins[l];if(!n||!j.element[0].parentNode){return}for(var m=0;m<n.length;m++){if(j.options[n[m][0]]){n[m][1].apply(j.element,k)}}}},contains:function(k,j){return document.compareDocumentPosition?k.compareDocumentPosition(j)&16:k!==j&&k.contains(j)},hasScroll:function(m,k){if(c(m).css("overflow")=="hidden"){return false}var j=(k&&k=="left")?"scrollLeft":"scrollTop",l=false;if(m[j]>0){return true}m[j]=1;l=(m[j]>0);m[j]=0;return l},isOverAxis:function(k,j,l){return(k>j)&&(k<(j+l))},isOver:function(o,k,n,m,j,l){return c.ui.isOverAxis(o,n,j)&&c.ui.isOverAxis(k,m,l)},keyCode:{BACKSPACE:8,CAPS_LOCK:20,COMMA:188,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38}};if(d){var f=c.attr,e=c.fn.removeAttr,h="http://www.w3.org/2005/07/aaa",a=/^aria-/,b=/^wairole:/;c.attr=function(k,j,l){var m=l!==undefined;return(j=="role"?(m?f.call(this,k,j,"wairole:"+l):(f.apply(this,arguments)||"").replace(b,"")):(a.test(j)?(m?k.setAttributeNS(h,j.replace(a,"aaa:"),l):f.call(this,k,j.replace(a,"aaa:"))):f.apply(this,arguments)))};c.fn.removeAttr=function(j){return(a.test(j)?this.each(function(){this.removeAttributeNS(h,j.replace(a,""))}):e.call(this,j))}}c.fn.extend({remove:function(){c("*",this).add(this).each(function(){c(this).triggerHandler("remove")});return i.apply(this,arguments)},enableSelection:function(){return this.attr("unselectable","off").css("MozUserSelect","").unbind("selectstart.ui")},disableSelection:function(){return this.attr("unselectable","on").css("MozUserSelect","none").bind("selectstart.ui",function(){return false})},scrollParent:function(){var j;if((c.browser.msie&&(/(static|relative)/).test(this.css("position")))||(/absolute/).test(this.css("position"))){j=this.parents().filter(function(){return(/(relative|absolute|fixed)/).test(c.curCSS(this,"position",1))&&(/(auto|scroll)/).test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0)}else{j=this.parents().filter(function(){return(/(auto|scroll)/).test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0)}return(/fixed/).test(this.css("position"))||!j.length?c(document):j}});c.extend(c.expr[":"],{data:function(l,k,j){return !!c.data(l,j[3])},focusable:function(k){var l=k.nodeName.toLowerCase(),j=c.attr(k,"tabindex");return(/input|select|textarea|button|object/.test(l)?!k.disabled:"a"==l||"area"==l?k.href||!isNaN(j):!isNaN(j))&&!c(k)["area"==l?"parents":"closest"](":hidden").length},tabbable:function(k){var j=c.attr(k,"tabindex");return(isNaN(j)||j>=0)&&c(k).is(":focusable")}});function g(m,n,o,l){function k(q){var p=c[m][n][q]||[];return(typeof p=="string"?p.split(/,?\s+/):p)}var j=k("getter");if(l.length==1&&typeof l[0]=="string"){j=j.concat(k("getterSetter"))}return(c.inArray(o,j)!=-1)}c.widget=function(k,j){var l=k.split(".")[0];k=k.split(".")[1];c.fn[k]=function(p){var n=(typeof p=="string"),o=Array.prototype.slice.call(arguments,1);if(n&&p.substring(0,1)=="_"){return this}if(n&&g(l,k,p,o)){var m=c.data(this[0],k);return(m?m[p].apply(m,o):undefined)}return this.each(function(){var q=c.data(this,k);(!q&&!n&&c.data(this,k,new c[l][k](this,p))._init());(q&&n&&c.isFunction(q[p])&&q[p].apply(q,o))})};c[l]=c[l]||{};c[l][k]=function(o,n){var m=this;this.namespace=l;this.widgetName=k;this.widgetEventPrefix=c[l][k].eventPrefix||k;this.widgetBaseClass=l+"-"+k;this.options=c.extend({},c.widget.defaults,c[l][k].defaults,c.metadata&&c.metadata.get(o)[k],n);this.element=c(o).bind("setData."+k,function(q,p,r){if(q.target==o){return m._setData(p,r)}}).bind("getData."+k,function(q,p){if(q.target==o){return m._getData(p)}}).bind("remove",function(){return m.destroy()})};c[l][k].prototype=c.extend({},c.widget.prototype,j);c[l][k].getterSetter="option"};c.widget.prototype={_init:function(){},destroy:function(){this.element.removeData(this.widgetName).removeClass(this.widgetBaseClass+"-disabled "+this.namespace+"-state-disabled").removeAttr("aria-disabled")},option:function(l,m){var k=l,j=this;if(typeof l=="string"){if(m===undefined){return this._getData(l)}k={};k[l]=m}c.each(k,function(n,o){j._setData(n,o)})},_getData:function(j){return this.options[j]},_setData:function(j,k){this.options[j]=k;if(j=="disabled"){this.element[k?"addClass":"removeClass"](this.widgetBaseClass+"-disabled "+this.namespace+"-state-disabled").attr("aria-disabled",k)}},enable:function(){this._setData("disabled",false)},disable:function(){this._setData("disabled",true)},_trigger:function(l,m,n){var p=this.options[l],j=(l==this.widgetEventPrefix?l:this.widgetEventPrefix+l);m=c.Event(m);m.type=j;if(m.originalEvent){for(var k=c.event.props.length,o;k;){o=c.event.props[--k];m[o]=m.originalEvent[o]}}this.element.trigger(m,n);return !(c.isFunction(p)&&p.call(this.element[0],m,n)===false||m.isDefaultPrevented())}};c.widget.defaults={disabled:false};c.ui.mouse={_mouseInit:function(){var j=this;this.element.bind("mousedown."+this.widgetName,function(k){return j._mouseDown(k)}).bind("click."+this.widgetName,function(k){if(j._preventClickEvent){j._preventClickEvent=false;k.stopImmediatePropagation();return false}});if(c.browser.msie){this._mouseUnselectable=this.element.attr("unselectable");this.element.attr("unselectable","on")}this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName);(c.browser.msie&&this.element.attr("unselectable",this._mouseUnselectable))},_mouseDown:function(l){l.originalEvent=l.originalEvent||{};if(l.originalEvent.mouseHandled){return}(this._mouseStarted&&this._mouseUp(l));this._mouseDownEvent=l;var k=this,m=(l.which==1),j=(typeof this.options.cancel=="string"?c(l.target).parents().add(l.target).filter(this.options.cancel).length:false);if(!m||j||!this._mouseCapture(l)){return true}this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet){this._mouseDelayTimer=setTimeout(function(){k.mouseDelayMet=true},this.options.delay)}if(this._mouseDistanceMet(l)&&this._mouseDelayMet(l)){this._mouseStarted=(this._mouseStart(l)!==false);if(!this._mouseStarted){l.preventDefault();return true}}this._mouseMoveDelegate=function(n){return k._mouseMove(n)};this._mouseUpDelegate=function(n){return k._mouseUp(n)};c(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);(c.browser.safari||l.preventDefault());l.originalEvent.mouseHandled=true;return true},_mouseMove:function(j){if(c.browser.msie&&!j.button){return this._mouseUp(j)}if(this._mouseStarted){this._mouseDrag(j);return j.preventDefault()}if(this._mouseDistanceMet(j)&&this._mouseDelayMet(j)){this._mouseStarted=(this._mouseStart(this._mouseDownEvent,j)!==false);(this._mouseStarted?this._mouseDrag(j):this._mouseUp(j))}return !this._mouseStarted},_mouseUp:function(j){c(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;this._preventClickEvent=(j.target==this._mouseDownEvent.target);this._mouseStop(j)}return false},_mouseDistanceMet:function(j){return(Math.max(Math.abs(this._mouseDownEvent.pageX-j.pageX),Math.abs(this._mouseDownEvent.pageY-j.pageY))>=this.options.distance)},_mouseDelayMet:function(j){return this.mouseDelayMet},_mouseStart:function(j){},_mouseDrag:function(j){},_mouseStop:function(j){},_mouseCapture:function(j){return true}};c.ui.mouse.defaults={cancel:null,distance:1,delay:0}})(jQuery);;/*
 * jQuery UI Accordion 1.7
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Accordion
 *
 * Depends:
 *	ui.core.js
 */(function(a){a.widget("ui.accordion",{_init:function(){var d=this.options,b=this;this.running=0;if(d.collapsible==a.ui.accordion.defaults.collapsible&&d.alwaysOpen!=a.ui.accordion.defaults.alwaysOpen){d.collapsible=!d.alwaysOpen}if(d.navigation){var c=this.element.find("a").filter(d.navigationFilter);if(c.length){if(c.filter(d.header).length){this.active=c}else{this.active=c.parent().parent().prev();c.addClass("ui-accordion-content-active")}}}this.element.addClass("ui-accordion ui-widget ui-helper-reset");if(this.element[0].nodeName=="UL"){this.element.children("li").addClass("ui-accordion-li-fix")}this.headers=this.element.find(d.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all").bind("mouseenter.accordion",function(){a(this).addClass("ui-state-hover")}).bind("mouseleave.accordion",function(){a(this).removeClass("ui-state-hover")}).bind("focus.accordion",function(){a(this).addClass("ui-state-focus")}).bind("blur.accordion",function(){a(this).removeClass("ui-state-focus")});this.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom");this.active=this._findActive(this.active||d.active).toggleClass("ui-state-default").toggleClass("ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top");this.active.next().addClass("ui-accordion-content-active");a("<span/>").addClass("ui-icon "+d.icons.header).prependTo(this.headers);this.active.find(".ui-icon").toggleClass(d.icons.header).toggleClass(d.icons.headerSelected);if(a.browser.msie){this.element.find("a").css("zoom","1")}this.resize();this.element.attr("role","tablist");this.headers.attr("role","tab").bind("keydown",function(e){return b._keydown(e)}).next().attr("role","tabpanel");this.headers.not(this.active||"").attr("aria-expanded","false").attr("tabIndex","-1").next().hide();if(!this.active.length){this.headers.eq(0).attr("tabIndex","0")}else{this.active.attr("aria-expanded","true").attr("tabIndex","0")}if(!a.browser.safari){this.headers.find("a").attr("tabIndex","-1")}if(d.event){this.headers.bind((d.event)+".accordion",function(e){return b._clickHandler.call(b,e,this)})}},destroy:function(){var c=this.options;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role").unbind(".accordion").removeData("accordion");this.headers.unbind(".accordion").removeClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-corner-top").removeAttr("role").removeAttr("aria-expanded").removeAttr("tabindex");this.headers.find("a").removeAttr("tabindex");this.headers.children(".ui-icon").remove();var b=this.headers.next().css("display","").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active");if(c.autoHeight||c.fillHeight){b.css("height","")}},_setData:function(b,c){if(b=="alwaysOpen"){b="collapsible";c=!c}a.widget.prototype._setData.apply(this,arguments)},_keydown:function(e){var g=this.options,f=a.ui.keyCode;if(g.disabled||e.altKey||e.ctrlKey){return}var d=this.headers.length;var b=this.headers.index(e.target);var c=false;switch(e.keyCode){case f.RIGHT:case f.DOWN:c=this.headers[(b+1)%d];break;case f.LEFT:case f.UP:c=this.headers[(b-1+d)%d];break;case f.SPACE:case f.ENTER:return this._clickHandler({target:e.target},e.target)}if(c){a(e.target).attr("tabIndex","-1");a(c).attr("tabIndex","0");c.focus();return false}return true},resize:function(){var e=this.options,d;if(e.fillSpace){if(a.browser.msie){var b=this.element.parent().css("overflow");this.element.parent().css("overflow","hidden")}d=this.element.parent().height();if(a.browser.msie){this.element.parent().css("overflow",b)}this.headers.each(function(){d-=a(this).outerHeight()});var c=0;this.headers.next().each(function(){c=Math.max(c,a(this).innerHeight()-a(this).height())}).height(Math.max(0,d-c)).css("overflow","auto")}else{if(e.autoHeight){d=0;this.headers.next().each(function(){d=Math.max(d,a(this).outerHeight())}).height(d)}}},activate:function(b){var c=this._findActive(b)[0];this._clickHandler({target:c},c)},_findActive:function(b){return b?typeof b=="number"?this.headers.filter(":eq("+b+")"):this.headers.not(this.headers.not(b)):b===false?a([]):this.headers.filter(":eq(0)")},_clickHandler:function(b,f){var d=this.options;if(d.disabled){return false}if(!b.target&&d.collapsible){this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").find(".ui-icon").removeClass(d.icons.headerSelected).addClass(d.icons.header);this.active.next().addClass("ui-accordion-content-active");var h=this.active.next(),e={options:d,newHeader:a([]),oldHeader:d.active,newContent:a([]),oldContent:h},c=(this.active=a([]));this._toggle(c,h,e);return false}var g=a(b.currentTarget||f);var i=g[0]==this.active[0];if(this.running||(!d.collapsible&&i)){return false}this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").find(".ui-icon").removeClass(d.icons.headerSelected).addClass(d.icons.header);this.active.next().addClass("ui-accordion-content-active");if(!i){g.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top").find(".ui-icon").removeClass(d.icons.header).addClass(d.icons.headerSelected);g.next().addClass("ui-accordion-content-active")}var c=g.next(),h=this.active.next(),e={options:d,newHeader:i&&d.collapsible?a([]):g,oldHeader:this.active,newContent:i&&d.collapsible?a([]):c.find("> *"),oldContent:h.find("> *")},j=this.headers.index(this.active[0])>this.headers.index(g[0]);this.active=i?a([]):g;this._toggle(c,h,e,i,j);return false},_toggle:function(b,i,g,j,k){var d=this.options,m=this;this.toShow=b;this.toHide=i;this.data=g;var c=function(){if(!m){return}return m._completed.apply(m,arguments)};this._trigger("changestart",null,this.data);this.running=i.size()===0?b.size():i.size();if(d.animated){var f={};if(d.collapsible&&j){f={toShow:a([]),toHide:i,complete:c,down:k,autoHeight:d.autoHeight||d.fillSpace}}else{f={toShow:b,toHide:i,complete:c,down:k,autoHeight:d.autoHeight||d.fillSpace}}if(!d.proxied){d.proxied=d.animated}if(!d.proxiedDuration){d.proxiedDuration=d.duration}d.animated=a.isFunction(d.proxied)?d.proxied(f):d.proxied;d.duration=a.isFunction(d.proxiedDuration)?d.proxiedDuration(f):d.proxiedDuration;var l=a.ui.accordion.animations,e=d.duration,h=d.animated;if(!l[h]){l[h]=function(n){this.slide(n,{easing:h,duration:e||700})}}l[h](f)}else{if(d.collapsible&&j){b.toggle()}else{i.hide();b.show()}c(true)}i.prev().attr("aria-expanded","false").attr("tabIndex","-1").blur();b.prev().attr("aria-expanded","true").attr("tabIndex","0").focus()},_completed:function(b){var c=this.options;this.running=b?0:--this.running;if(this.running){return}if(c.clearStyle){this.toShow.add(this.toHide).css({height:"",overflow:""})}this._trigger("change",null,this.data)}});a.extend(a.ui.accordion,{version:"1.7",defaults:{active:null,alwaysOpen:true,animated:"slide",autoHeight:true,clearStyle:false,collapsible:false,event:"click",fillSpace:false,header:"> li > :first-child,> :not(li):even",icons:{header:"ui-icon-triangle-1-e",headerSelected:"ui-icon-triangle-1-s"},navigation:false,navigationFilter:function(){return this.href.toLowerCase()==location.href.toLowerCase()}},animations:{slide:function(j,h){j=a.extend({easing:"swing",duration:300},j,h);if(!j.toHide.size()){j.toShow.animate({height:"show"},j);return}if(!j.toShow.size()){j.toHide.animate({height:"hide"},j);return}var c=j.toShow.css("overflow"),g,d={},f={},e=["height","paddingTop","paddingBottom"],b;var i=j.toShow;b=i[0].style.width;i.width(parseInt(i.parent().width(),10)-parseInt(i.css("paddingLeft"),10)-parseInt(i.css("paddingRight"),10)-parseInt(i.css("borderLeftWidth"),10)-parseInt(i.css("borderRightWidth"),10));a.each(e,function(k,m){f[m]="hide";var l=(""+a.css(j.toShow[0],m)).match(/^([\d+-.]+)(.*)$/);d[m]={value:l[1],unit:l[2]||"px"}});j.toShow.css({height:0,overflow:"hidden"}).show();j.toHide.filter(":hidden").each(j.complete).end().filter(":visible").animate(f,{step:function(k,l){if(l.prop=="height"){g=(l.now-l.start)/(l.end-l.start)}j.toShow[0].style[l.prop]=(g*d[l.prop].value)+d[l.prop].unit},duration:j.duration,easing:j.easing,complete:function(){if(!j.autoHeight){j.toShow.css("height","")}j.toShow.css("width",b);j.toShow.css({overflow:c});j.complete()}})},bounceslide:function(b){this.slide(b,{easing:b.down?"easeOutBounce":"swing",duration:b.down?1000:200})},easeslide:function(b){this.slide(b,{easing:"easeinout",duration:700})}}})})(jQuery);;/*
 * jQuery UI Dialog 1.7
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Dialog
 *
 * Depends:
 *	ui.core.js
 *	ui.draggable.js
 *	ui.resizable.js
 */(function(c){var b={dragStart:"start.draggable",drag:"drag.draggable",dragStop:"stop.draggable",maxHeight:"maxHeight.resizable",minHeight:"minHeight.resizable",maxWidth:"maxWidth.resizable",minWidth:"minWidth.resizable",resizeStart:"start.resizable",resize:"drag.resizable",resizeStop:"stop.resizable"},a="ui-dialog ui-widget ui-widget-content ui-corner-all ";c.widget("ui.dialog",{_init:function(){this.originalTitle=this.element.attr("title");var l=this,m=this.options,j=m.title||this.originalTitle||"&nbsp;",e=c.ui.dialog.getTitleId(this.element),k=(this.uiDialog=c("<div/>")).appendTo(document.body).hide().addClass(a+m.dialogClass).css({position:"absolute",overflow:"hidden",zIndex:m.zIndex}).attr("tabIndex",-1).css("outline",0).keydown(function(n){(m.closeOnEscape&&n.keyCode&&n.keyCode==c.ui.keyCode.ESCAPE&&l.close(n))}).attr({role:"dialog","aria-labelledby":e}).mousedown(function(n){l.moveToTop(false,n)}),g=this.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(k),f=(this.uiDialogTitlebar=c("<div></div>")).addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(k),i=c('<a href="#"/>').addClass("ui-dialog-titlebar-close ui-corner-all").attr("role","button").hover(function(){i.addClass("ui-state-hover")},function(){i.removeClass("ui-state-hover")}).focus(function(){i.addClass("ui-state-focus")}).blur(function(){i.removeClass("ui-state-focus")}).mousedown(function(n){n.stopPropagation()}).click(function(n){l.close(n);return false}).appendTo(f),h=(this.uiDialogTitlebarCloseText=c("<span/>")).addClass("ui-icon ui-icon-closethick").text(m.closeText).appendTo(i),d=c("<span/>").addClass("ui-dialog-title").attr("id",e).html(j).prependTo(f);f.find("*").add(f).disableSelection();(m.draggable&&c.fn.draggable&&this._makeDraggable());(m.resizable&&c.fn.resizable&&this._makeResizable());this._createButtons(m.buttons);this._isOpen=false;(m.bgiframe&&c.fn.bgiframe&&k.bgiframe());(m.autoOpen&&this.open())},destroy:function(){(this.overlay&&this.overlay.destroy());this.uiDialog.hide();this.element.unbind(".dialog").removeData("dialog").removeClass("ui-dialog-content ui-widget-content").hide().appendTo("body");this.uiDialog.remove();(this.originalTitle&&this.element.attr("title",this.originalTitle))},close:function(e){var d=this;if(false===d._trigger("beforeclose",e)){return}(d.overlay&&d.overlay.destroy());d.uiDialog.unbind("keypress.ui-dialog");(d.options.hide?d.uiDialog.hide(d.options.hide,function(){d._trigger("close",e)}):d.uiDialog.hide()&&d._trigger("close",e));c.ui.dialog.overlay.resize();d._isOpen=false},isOpen:function(){return this._isOpen},moveToTop:function(f,e){if((this.options.modal&&!f)||(!this.options.stack&&!this.options.modal)){return this._trigger("focus",e)}if(this.options.zIndex>c.ui.dialog.maxZ){c.ui.dialog.maxZ=this.options.zIndex}(this.overlay&&this.overlay.$el.css("z-index",c.ui.dialog.overlay.maxZ=++c.ui.dialog.maxZ));var d={scrollTop:this.element.attr("scrollTop"),scrollLeft:this.element.attr("scrollLeft")};this.uiDialog.css("z-index",++c.ui.dialog.maxZ);this.element.attr(d);this._trigger("focus",e)},open:function(){if(this._isOpen){return}var e=this.options,d=this.uiDialog;this.overlay=e.modal?new c.ui.dialog.overlay(this):null;(d.next().length&&d.appendTo("body"));this._size();this._position(e.position);d.show(e.show);this.moveToTop(true);(e.modal&&d.bind("keypress.ui-dialog",function(h){if(h.keyCode!=c.ui.keyCode.TAB){return}var g=c(":tabbable",this),i=g.filter(":first")[0],f=g.filter(":last")[0];if(h.target==f&&!h.shiftKey){setTimeout(function(){i.focus()},1)}else{if(h.target==i&&h.shiftKey){setTimeout(function(){f.focus()},1)}}}));c([]).add(d.find(".ui-dialog-content :tabbable:first")).add(d.find(".ui-dialog-buttonpane :tabbable:first")).add(d).filter(":first").focus();this._trigger("open");this._isOpen=true},_createButtons:function(g){var f=this,d=false,e=c("<div></div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix");this.uiDialog.find(".ui-dialog-buttonpane").remove();(typeof g=="object"&&g!==null&&c.each(g,function(){return !(d=true)}));if(d){c.each(g,function(h,i){c('<button type="button"></button>').addClass("ui-state-default ui-corner-all").text(h).click(function(){i.apply(f.element[0],arguments)}).hover(function(){c(this).addClass("ui-state-hover")},function(){c(this).removeClass("ui-state-hover")}).focus(function(){c(this).addClass("ui-state-focus")}).blur(function(){c(this).removeClass("ui-state-focus")}).appendTo(e)});e.appendTo(this.uiDialog)}},_makeDraggable:function(){var d=this,f=this.options,e;this.uiDialog.draggable({cancel:".ui-dialog-content",handle:".ui-dialog-titlebar",containment:"document",start:function(){e=f.height;c(this).height(c(this).height()).addClass("ui-dialog-dragging");(f.dragStart&&f.dragStart.apply(d.element[0],arguments))},drag:function(){(f.drag&&f.drag.apply(d.element[0],arguments))},stop:function(){c(this).removeClass("ui-dialog-dragging").height(e);(f.dragStop&&f.dragStop.apply(d.element[0],arguments));c.ui.dialog.overlay.resize()}})},_makeResizable:function(g){g=(g===undefined?this.options.resizable:g);var d=this,f=this.options,e=typeof g=="string"?g:"n,e,s,w,se,sw,ne,nw";this.uiDialog.resizable({cancel:".ui-dialog-content",alsoResize:this.element,maxWidth:f.maxWidth,maxHeight:f.maxHeight,minWidth:f.minWidth,minHeight:f.minHeight,start:function(){c(this).addClass("ui-dialog-resizing");(f.resizeStart&&f.resizeStart.apply(d.element[0],arguments))},resize:function(){(f.resize&&f.resize.apply(d.element[0],arguments))},handles:e,stop:function(){c(this).removeClass("ui-dialog-resizing");f.height=c(this).height();f.width=c(this).width();(f.resizeStop&&f.resizeStop.apply(d.element[0],arguments));c.ui.dialog.overlay.resize()}}).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se")},_position:function(i){var e=c(window),f=c(document),g=f.scrollTop(),d=f.scrollLeft(),h=g;if(c.inArray(i,["center","top","right","bottom","left"])>=0){i=[i=="right"||i=="left"?i:"center",i=="top"||i=="bottom"?i:"middle"]}if(i.constructor!=Array){i=["center","middle"]}if(i[0].constructor==Number){d+=i[0]}else{switch(i[0]){case"left":d+=0;break;case"right":d+=e.width()-this.uiDialog.outerWidth();break;default:case"center":d+=(e.width()-this.uiDialog.outerWidth())/2}}if(i[1].constructor==Number){g+=i[1]}else{switch(i[1]){case"top":g+=0;break;case"bottom":g+=e.height()-this.uiDialog.outerHeight();break;default:case"middle":g+=(e.height()-this.uiDialog.outerHeight())/2}}g=Math.max(g,h);this.uiDialog.css({top:g,left:d})},_setData:function(e,f){(b[e]&&this.uiDialog.data(b[e],f));switch(e){case"buttons":this._createButtons(f);break;case"closeText":this.uiDialogTitlebarCloseText.text(f);break;case"dialogClass":this.uiDialog.removeClass(this.options.dialogClass).addClass(a+f);break;case"draggable":(f?this._makeDraggable():this.uiDialog.draggable("destroy"));break;case"height":this.uiDialog.height(f);break;case"position":this._position(f);break;case"resizable":var d=this.uiDialog,g=this.uiDialog.is(":data(resizable)");(g&&!f&&d.resizable("destroy"));(g&&typeof f=="string"&&d.resizable("option","handles",f));(g||this._makeResizable(f));break;case"title":c(".ui-dialog-title",this.uiDialogTitlebar).html(f||"&nbsp;");break;case"width":this.uiDialog.width(f);break}c.widget.prototype._setData.apply(this,arguments)},_size:function(){var e=this.options;this.element.css({height:0,minHeight:0,width:"auto"});var d=this.uiDialog.css({height:"auto",width:e.width}).height();this.element.css({minHeight:Math.max(e.minHeight-d,0),height:e.height=="auto"?"auto":Math.max(e.height-d,0)})}});c.extend(c.ui.dialog,{version:"1.7",defaults:{autoOpen:true,bgiframe:false,buttons:{},closeOnEscape:true,closeText:"close",dialogClass:"",draggable:true,hide:null,height:"auto",maxHeight:false,maxWidth:false,minHeight:150,minWidth:150,modal:false,position:"center",resizable:true,show:null,stack:true,title:"",width:300,zIndex:1000},getter:"isOpen",uuid:0,maxZ:0,getTitleId:function(d){return"ui-dialog-title-"+(d.attr("id")||++this.uuid)},overlay:function(d){this.$el=c.ui.dialog.overlay.create(d)}});c.extend(c.ui.dialog.overlay,{instances:[],maxZ:0,events:c.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(d){return d+".dialog-overlay"}).join(" "),create:function(e){if(this.instances.length===0){setTimeout(function(){c(document).bind(c.ui.dialog.overlay.events,function(f){var g=c(f.target).parents(".ui-dialog").css("zIndex")||0;return(g>c.ui.dialog.overlay.maxZ)})},1);c(document).bind("keydown.dialog-overlay",function(f){(e.options.closeOnEscape&&f.keyCode&&f.keyCode==c.ui.keyCode.ESCAPE&&e.close(f))});c(window).bind("resize.dialog-overlay",c.ui.dialog.overlay.resize)}var d=c("<div></div>").appendTo(document.body).addClass("ui-widget-overlay").css({width:this.width(),height:this.height()});(e.options.bgiframe&&c.fn.bgiframe&&d.bgiframe());this.instances.push(d);return d},destroy:function(d){this.instances.splice(c.inArray(this.instances,d),1);if(this.instances.length===0){c([document,window]).unbind(".dialog-overlay")}d.remove()},height:function(){if(c.browser.msie&&c.browser.version<7){var e=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);var d=Math.max(document.documentElement.offsetHeight,document.body.offsetHeight);if(e<d){return c(window).height()+"px"}else{return e+"px"}}else{return c(document).height()+"px"}},width:function(){if(c.browser.msie&&c.browser.version<7){var d=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth);var e=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth);if(d<e){return c(window).width()+"px"}else{return d+"px"}}else{return c(document).width()+"px"}},resize:function(){var d=c([]);c.each(c.ui.dialog.overlay.instances,function(){d=d.add(this)});d.css({width:0,height:0}).css({width:c.ui.dialog.overlay.width(),height:c.ui.dialog.overlay.height()})}});c.extend(c.ui.dialog.overlay.prototype,{destroy:function(){c.ui.dialog.overlay.destroy(this.$el)}})})(jQuery);;/*
 * jQuery UI Slider 1.7
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Slider
 *
 * Depends:
 *	ui.core.js
 */(function(a){a.widget("ui.slider",a.extend({},a.ui.mouse,{_init:function(){var b=this,c=this.options;this._keySliding=false;this._handleIndex=null;this._detectOrientation();this._mouseInit();this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget ui-widget-content ui-corner-all");this.range=a([]);if(c.range){if(c.range===true){this.range=a("<div></div>");if(!c.values){c.values=[this._valueMin(),this._valueMin()]}if(c.values.length&&c.values.length!=2){c.values=[c.values[0],c.values[0]]}}else{this.range=a("<div></div>")}this.range.appendTo(this.element).addClass("ui-slider-range");if(c.range=="min"||c.range=="max"){this.range.addClass("ui-slider-range-"+c.range)}this.range.addClass("ui-widget-header")}if(a(".ui-slider-handle",this.element).length==0){a('<a href="#"></a>').appendTo(this.element).addClass("ui-slider-handle")}if(c.values&&c.values.length){while(a(".ui-slider-handle",this.element).length<c.values.length){a('<a href="#"></a>').appendTo(this.element).addClass("ui-slider-handle")}}this.handles=a(".ui-slider-handle",this.element).addClass("ui-state-default ui-corner-all");this.handle=this.handles.eq(0);this.handles.add(this.range).filter("a").click(function(d){d.preventDefault()}).hover(function(){a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")}).focus(function(){a(".ui-slider .ui-state-focus").removeClass("ui-state-focus");a(this).addClass("ui-state-focus")}).blur(function(){a(this).removeClass("ui-state-focus")});this.handles.each(function(d){a(this).data("index.ui-slider-handle",d)});this.handles.keydown(function(i){var f=true;var e=a(this).data("index.ui-slider-handle");if(b.options.disabled){return}switch(i.keyCode){case a.ui.keyCode.HOME:case a.ui.keyCode.END:case a.ui.keyCode.UP:case a.ui.keyCode.RIGHT:case a.ui.keyCode.DOWN:case a.ui.keyCode.LEFT:f=false;if(!b._keySliding){b._keySliding=true;a(this).addClass("ui-state-active");b._start(i,e)}break}var g,d,h=b._step();if(b.options.values&&b.options.values.length){g=d=b.values(e)}else{g=d=b.value()}switch(i.keyCode){case a.ui.keyCode.HOME:d=b._valueMin();break;case a.ui.keyCode.END:d=b._valueMax();break;case a.ui.keyCode.UP:case a.ui.keyCode.RIGHT:if(g==b._valueMax()){return}d=g+h;break;case a.ui.keyCode.DOWN:case a.ui.keyCode.LEFT:if(g==b._valueMin()){return}d=g-h;break}b._slide(i,e,d);return f}).keyup(function(e){var d=a(this).data("index.ui-slider-handle");if(b._keySliding){b._stop(e,d);b._change(e,d);b._keySliding=false;a(this).removeClass("ui-state-active")}});this._refreshValue()},destroy:function(){this.handles.remove();this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all").removeData("slider").unbind(".slider");this._mouseDestroy()},_mouseCapture:function(d){var e=this.options;if(e.disabled){return false}this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()};this.elementOffset=this.element.offset();var h={x:d.pageX,y:d.pageY};var j=this._normValueFromMouse(h);var c=this._valueMax()+1,f;var k=this,i;this.handles.each(function(l){var m=Math.abs(j-k.values(l));if(c>m){c=m;f=a(this);i=l}});if(e.range==true&&this.values(1)==e.min){f=a(this.handles[++i])}this._start(d,i);k._handleIndex=i;f.addClass("ui-state-active").focus();var g=f.offset();var b=!a(d.target).parents().andSelf().is(".ui-slider-handle");this._clickOffset=b?{left:0,top:0}:{left:d.pageX-g.left-(f.width()/2),top:d.pageY-g.top-(f.height()/2)-(parseInt(f.css("borderTopWidth"),10)||0)-(parseInt(f.css("borderBottomWidth"),10)||0)+(parseInt(f.css("marginTop"),10)||0)};j=this._normValueFromMouse(h);this._slide(d,i,j);return true},_mouseStart:function(b){return true},_mouseDrag:function(d){var b={x:d.pageX,y:d.pageY};var c=this._normValueFromMouse(b);this._slide(d,this._handleIndex,c);return false},_mouseStop:function(b){this.handles.removeClass("ui-state-active");this._stop(b,this._handleIndex);this._change(b,this._handleIndex);this._handleIndex=null;this._clickOffset=null;return false},_detectOrientation:function(){this.orientation=this.options.orientation=="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(d){var c,h;if("horizontal"==this.orientation){c=this.elementSize.width;h=d.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)}else{c=this.elementSize.height;h=d.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)}var f=(h/c);if(f>1){f=1}if(f<0){f=0}if("vertical"==this.orientation){f=1-f}var e=this._valueMax()-this._valueMin(),i=f*e,b=i%this.options.step,g=this._valueMin()+i-b;if(b>(this.options.step/2)){g+=this.options.step}return parseFloat(g.toFixed(5))},_start:function(c,b){this._trigger("start",c,this._uiHash(b))},_slide:function(f,e,d){var g=this.handles[e];if(this.options.values&&this.options.values.length){var b=this.values(e?0:1);if((e==0&&d>=b)||(e==1&&d<=b)){d=b}if(d!=this.values(e)){var c=this.values();c[e]=d;var h=this._trigger("slide",f,this._uiHash(e,d,c));var b=this.values(e?0:1);if(h!==false){this.values(e,d,(f.type=="mousedown"&&this.options.animate),true)}}}else{if(d!=this.value()){var h=this._trigger("slide",f,this._uiHash(e,d));if(h!==false){this._setData("value",d,(f.type=="mousedown"&&this.options.animate))}}}},_stop:function(c,b){this._trigger("stop",c,this._uiHash(b))},_change:function(c,b){this._trigger("change",c,this._uiHash(b))},value:function(b){if(arguments.length){this._setData("value",b);this._change(null,0)}return this._value()},values:function(b,e,c,d){if(arguments.length>1){this.options.values[b]=e;this._refreshValue(c);if(!d){this._change(null,b)}}if(arguments.length){if(this.options.values&&this.options.values.length){return this._values(b)}else{return this.value()}}else{return this._values()}},_setData:function(b,d,c){a.widget.prototype._setData.apply(this,arguments);switch(b){case"orientation":this._detectOrientation();this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation);this._refreshValue(c);break;case"value":this._refreshValue(c);break}},_step:function(){var b=this.options.step;return b},_value:function(){var b=this.options.value;if(b<this._valueMin()){b=this._valueMin()}if(b>this._valueMax()){b=this._valueMax()}return b},_values:function(b){if(arguments.length){var c=this.options.values[b];if(c<this._valueMin()){c=this._valueMin()}if(c>this._valueMax()){c=this._valueMax()}return c}else{return this.options.values}},_valueMin:function(){var b=this.options.min;return b},_valueMax:function(){var b=this.options.max;return b},_refreshValue:function(c){var f=this.options.range,d=this.options,l=this;if(this.options.values&&this.options.values.length){var i,h;this.handles.each(function(p,n){var o=(l.values(p)-l._valueMin())/(l._valueMax()-l._valueMin())*100;var m={};m[l.orientation=="horizontal"?"left":"bottom"]=o+"%";a(this).stop(1,1)[c?"animate":"css"](m,d.animate);if(l.options.range===true){if(l.orientation=="horizontal"){(p==0)&&l.range.stop(1,1)[c?"animate":"css"]({left:o+"%"},d.animate);(p==1)&&l.range[c?"animate":"css"]({width:(o-lastValPercent)+"%"},{queue:false,duration:d.animate})}else{(p==0)&&l.range.stop(1,1)[c?"animate":"css"]({bottom:(o)+"%"},d.animate);(p==1)&&l.range[c?"animate":"css"]({height:(o-lastValPercent)+"%"},{queue:false,duration:d.animate})}}lastValPercent=o})}else{var j=this.value(),g=this._valueMin(),k=this._valueMax(),e=k!=g?(j-g)/(k-g)*100:0;var b={};b[l.orientation=="horizontal"?"left":"bottom"]=e+"%";this.handle.stop(1,1)[c?"animate":"css"](b,d.animate);(f=="min")&&(this.orientation=="horizontal")&&this.range.stop(1,1)[c?"animate":"css"]({width:e+"%"},d.animate);(f=="max")&&(this.orientation=="horizontal")&&this.range[c?"animate":"css"]({width:(100-e)+"%"},{queue:false,duration:d.animate});(f=="min")&&(this.orientation=="vertical")&&this.range.stop(1,1)[c?"animate":"css"]({height:e+"%"},d.animate);(f=="max")&&(this.orientation=="vertical")&&this.range[c?"animate":"css"]({height:(100-e)+"%"},{queue:false,duration:d.animate})}},_uiHash:function(d,e,c){var b=this.options.values&&this.options.values.length;return{handle:this.handles[d],value:e||(b?this.values(d):this.value()),values:c||(b&&this.values())}}}));a.extend(a.ui.slider,{getter:"value values",version:"1.7",eventPrefix:"slide",defaults:{animate:false,delay:0,distance:0,max:100,min:0,orientation:"horizontal",range:false,step:1,value:0,values:null}})})(jQuery);;/*
 * jQuery UI Tabs 1.7
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Tabs
 *
 * Depends:
 *	ui.core.js
 */(function(a){a.widget("ui.tabs",{_init:function(){if(this.options.deselectable!==undefined){this.options.collapsible=this.options.deselectable}this._tabify(true)},_setData:function(b,c){if(b=="selected"){if(this.options.collapsible&&c==this.options.selected){return}this.select(c)}else{this.options[b]=c;if(b=="deselectable"){this.options.collapsible=c}this._tabify()}},_tabId:function(b){return b.title&&b.title.replace(/\s/g,"_").replace(/[^A-Za-z0-9\-_:\.]/g,"")||this.options.idPrefix+a.data(b)},_sanitizeSelector:function(b){return b.replace(/:/g,"\\:")},_cookie:function(){var b=this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+a.data(this.list[0]));return a.cookie.apply(null,[b].concat(a.makeArray(arguments)))},_ui:function(c,b){return{tab:c,panel:b,index:this.anchors.index(c)}},_cleanup:function(){this.lis.filter(".ui-state-processing").removeClass("ui-state-processing").find("span:data(label.tabs)").each(function(){var b=a(this);b.html(b.data("label.tabs")).removeData("label.tabs")})},_tabify:function(n){this.list=this.element.children("ul:first");this.lis=a("li:has(a[href])",this.list);this.anchors=this.lis.map(function(){return a("a",this)[0]});this.panels=a([]);var p=this,d=this.options;var c=/^#.+/;this.anchors.each(function(r,o){var q=a(o).attr("href");var s=q.split("#")[0],u;if(s&&(s===location.toString().split("#")[0]||(u=a("base")[0])&&s===u.href)){q=o.hash;o.href=q}if(c.test(q)){p.panels=p.panels.add(p._sanitizeSelector(q))}else{if(q!="#"){a.data(o,"href.tabs",q);a.data(o,"load.tabs",q.replace(/#.*$/,""));var w=p._tabId(o);o.href="#"+w;var v=a("#"+w);if(!v.length){v=a(d.panelTemplate).attr("id",w).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").insertAfter(p.panels[r-1]||p.list);v.data("destroy.tabs",true)}p.panels=p.panels.add(v)}else{d.disabled.push(r)}}});if(n){this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all");this.list.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.lis.addClass("ui-state-default ui-corner-top");this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom");if(d.selected===undefined){if(location.hash){this.anchors.each(function(q,o){if(o.hash==location.hash){d.selected=q;return false}})}if(typeof d.selected!="number"&&d.cookie){d.selected=parseInt(p._cookie(),10)}if(typeof d.selected!="number"&&this.lis.filter(".ui-tabs-selected").length){d.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"))}d.selected=d.selected||0}else{if(d.selected===null){d.selected=-1}}d.selected=((d.selected>=0&&this.anchors[d.selected])||d.selected<0)?d.selected:0;d.disabled=a.unique(d.disabled.concat(a.map(this.lis.filter(".ui-state-disabled"),function(q,o){return p.lis.index(q)}))).sort();if(a.inArray(d.selected,d.disabled)!=-1){d.disabled.splice(a.inArray(d.selected,d.disabled),1)}this.panels.addClass("ui-tabs-hide");this.lis.removeClass("ui-tabs-selected ui-state-active");if(d.selected>=0&&this.anchors.length){this.panels.eq(d.selected).removeClass("ui-tabs-hide");this.lis.eq(d.selected).addClass("ui-tabs-selected ui-state-active");p.element.queue("tabs",function(){p._trigger("show",null,p._ui(p.anchors[d.selected],p.panels[d.selected]))});this.load(d.selected)}a(window).bind("unload",function(){p.lis.add(p.anchors).unbind(".tabs");p.lis=p.anchors=p.panels=null})}else{d.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"))}this.element[d.collapsible?"addClass":"removeClass"]("ui-tabs-collapsible");if(d.cookie){this._cookie(d.selected,d.cookie)}for(var g=0,m;(m=this.lis[g]);g++){a(m)[a.inArray(g,d.disabled)!=-1&&!a(m).hasClass("ui-tabs-selected")?"addClass":"removeClass"]("ui-state-disabled")}if(d.cache===false){this.anchors.removeData("cache.tabs")}this.lis.add(this.anchors).unbind(".tabs");if(d.event!="mouseover"){var f=function(o,i){if(i.is(":not(.ui-state-disabled)")){i.addClass("ui-state-"+o)}};var j=function(o,i){i.removeClass("ui-state-"+o)};this.lis.bind("mouseover.tabs",function(){f("hover",a(this))});this.lis.bind("mouseout.tabs",function(){j("hover",a(this))});this.anchors.bind("focus.tabs",function(){f("focus",a(this).closest("li"))});this.anchors.bind("blur.tabs",function(){j("focus",a(this).closest("li"))})}var b,h;if(d.fx){if(a.isArray(d.fx)){b=d.fx[0];h=d.fx[1]}else{b=h=d.fx}}function e(i,o){i.css({display:""});if(a.browser.msie&&o.opacity){i[0].style.removeAttribute("filter")}}var k=h?function(i,o){a(i).closest("li").removeClass("ui-state-default").addClass("ui-tabs-selected ui-state-active");o.hide().removeClass("ui-tabs-hide").animate(h,h.duration||"normal",function(){e(o,h);p._trigger("show",null,p._ui(i,o[0]))})}:function(i,o){a(i).closest("li").removeClass("ui-state-default").addClass("ui-tabs-selected ui-state-active");o.removeClass("ui-tabs-hide");p._trigger("show",null,p._ui(i,o[0]))};var l=b?function(o,i){i.animate(b,b.duration||"normal",function(){p.lis.removeClass("ui-tabs-selected ui-state-active").addClass("ui-state-default");i.addClass("ui-tabs-hide");e(i,b);p.element.dequeue("tabs")})}:function(o,i,q){p.lis.removeClass("ui-tabs-selected ui-state-active").addClass("ui-state-default");i.addClass("ui-tabs-hide");p.element.dequeue("tabs")};this.anchors.bind(d.event+".tabs",function(){var o=this,r=a(this).closest("li"),i=p.panels.filter(":not(.ui-tabs-hide)"),q=a(p._sanitizeSelector(this.hash));if((r.hasClass("ui-tabs-selected")&&!d.collapsible)||r.hasClass("ui-state-disabled")||r.hasClass("ui-state-processing")||p._trigger("select",null,p._ui(this,q[0]))===false){this.blur();return false}d.selected=p.anchors.index(this);p.abort();if(d.collapsible){if(r.hasClass("ui-tabs-selected")){d.selected=-1;if(d.cookie){p._cookie(d.selected,d.cookie)}p.element.queue("tabs",function(){l(o,i)}).dequeue("tabs");this.blur();return false}else{if(!i.length){if(d.cookie){p._cookie(d.selected,d.cookie)}p.element.queue("tabs",function(){k(o,q)});p.load(p.anchors.index(this));this.blur();return false}}}if(d.cookie){p._cookie(d.selected,d.cookie)}if(q.length){if(i.length){p.element.queue("tabs",function(){l(o,i)})}p.element.queue("tabs",function(){k(o,q)});p.load(p.anchors.index(this))}else{throw"jQuery UI Tabs: Mismatching fragment identifier."}if(a.browser.msie){this.blur()}});this.anchors.bind("click.tabs",function(){return false})},destroy:function(){var b=this.options;this.abort();this.element.unbind(".tabs").removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible").removeData("tabs");this.list.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.anchors.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.unbind(".tabs").add(this.panels).each(function(){if(a.data(this,"destroy.tabs")){a(this).remove()}else{a(this).removeClass(["ui-state-default","ui-corner-top","ui-tabs-selected","ui-state-active","ui-state-hover","ui-state-focus","ui-state-disabled","ui-tabs-panel","ui-widget-content","ui-corner-bottom","ui-tabs-hide"].join(" "))}});if(b.cookie){this._cookie(null,b.cookie)}},add:function(e,d,c){if(c===undefined){c=this.anchors.length}var b=this,g=this.options,i=a(g.tabTemplate.replace(/#\{href\}/g,e).replace(/#\{label\}/g,d)),h=!e.indexOf("#")?e.replace("#",""):this._tabId(a("a",i)[0]);i.addClass("ui-state-default ui-corner-top").data("destroy.tabs",true);var f=a("#"+h);if(!f.length){f=a(g.panelTemplate).attr("id",h).data("destroy.tabs",true)}f.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide");if(c>=this.lis.length){i.appendTo(this.list);f.appendTo(this.list[0].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.anchors.length==1){i.addClass("ui-tabs-selected ui-state-active");f.removeClass("ui-tabs-hide");this.element.queue("tabs",function(){b._trigger("show",null,b._ui(b.anchors[0],b.panels[0]))});this.load(0)}this._trigger("add",null,this._ui(this.anchors[c],this.panels[c]))},remove:function(b){var d=this.options,e=this.lis.eq(b).remove(),c=this.panels.eq(b).remove();if(e.hasClass("ui-tabs-selected")&&this.anchors.length>1){this.select(b+(b+1<this.anchors.length?1:-1))}d.disabled=a.map(a.grep(d.disabled,function(g,f){return g!=b}),function(g,f){return g>=b?--g:g});this._tabify();this._trigger("remove",null,this._ui(e.find("a")[0],c[0]))},enable:function(b){var c=this.options;if(a.inArray(b,c.disabled)==-1){return}this.lis.eq(b).removeClass("ui-state-disabled");c.disabled=a.grep(c.disabled,function(e,d){return e!=b});this._trigger("enable",null,this._ui(this.anchors[b],this.panels[b]))},disable:function(c){var b=this,d=this.options;if(c!=d.selected){this.lis.eq(c).addClass("ui-state-disabled");d.disabled.push(c);d.disabled.sort();this._trigger("disable",null,this._ui(this.anchors[c],this.panels[c]))}},select:function(b){if(typeof b=="string"){b=this.anchors.index(this.anchors.filter("[href$="+b+"]"))}else{if(b===null){b=-1}}if(b==-1&&this.options.collapsible){b=this.options.selected}this.anchors.eq(b).trigger(this.options.event+".tabs")},load:function(e){var c=this,g=this.options,b=this.anchors.eq(e)[0],d=a.data(b,"load.tabs");this.abort();if(!d||this.element.queue("tabs").length!==0&&a.data(b,"cache.tabs")){this.element.dequeue("tabs");return}this.lis.eq(e).addClass("ui-state-processing");if(g.spinner){var f=a("span",b);f.data("label.tabs",f.html()).html(g.spinner)}this.xhr=a.ajax(a.extend({},g.ajaxOptions,{url:d,success:function(i,h){a(c._sanitizeSelector(b.hash)).html(i);c._cleanup();if(g.cache){a.data(b,"cache.tabs",true)}c._trigger("load",null,c._ui(c.anchors[e],c.panels[e]));try{g.ajaxOptions.success(i,h)}catch(j){}c.element.dequeue("tabs")}}))},abort:function(){this.element.queue([]);this.panels.stop(false,true);if(this.xhr){this.xhr.abort();delete this.xhr}this._cleanup()},url:function(c,b){this.anchors.eq(c).removeData("cache.tabs").data("load.tabs",b)},length:function(){return this.anchors.length}});a.extend(a.ui.tabs,{version:"1.7",getter:"length",defaults:{ajaxOptions:null,cache:false,cookie:null,collapsible:false,disabled:[],event:"click",fx:null,idPrefix:"ui-tabs-",panelTemplate:"<div></div>",spinner:"<em>Loading&#8230;</em>",tabTemplate:'<li><a href="#{href}"><span>#{label}</span></a></li>'}});a.extend(a.ui.tabs.prototype,{rotation:null,rotate:function(d,f){var b=this,g=this.options;var c=b._rotate||(b._rotate=function(h){clearTimeout(b.rotation);b.rotation=setTimeout(function(){var i=g.selected;b.select(++i<b.anchors.length?i:0)},d);if(h){h.stopPropagation()}});var e=b._unrotate||(b._unrotate=!f?function(h){if(h.clientX){b.rotate(null)}}:function(h){t=g.selected;c()});if(d){this.element.bind("tabsshow",c);this.anchors.bind(g.event+".tabs",e);c()}else{clearTimeout(b.rotation);this.element.unbind("tabsshow",c);this.anchors.unbind(g.event+".tabs",e);delete this._rotate;delete this._unrotate}}})})(jQuery);;/*
 * jQuery UI Datepicker 1.7
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Datepicker
 *
 * Depends:
 *	ui.core.js
 */(function($){$.extend($.ui,{datepicker:{version:"1.7"}});var PROP_NAME="datepicker";function Datepicker(){this.debug=false;this._curInst=null;this._keyEvent=false;this._disabledInputs=[];this._datepickerShowing=false;this._inDialog=false;this._mainDivId="ui-datepicker-div";this._inlineClass="ui-datepicker-inline";this._appendClass="ui-datepicker-append";this._triggerClass="ui-datepicker-trigger";this._dialogClass="ui-datepicker-dialog";this._disableClass="ui-datepicker-disabled";this._unselectableClass="ui-datepicker-unselectable";this._currentClass="ui-datepicker-current-day";this._dayOverClass="ui-datepicker-days-cell-over";this.regional=[];this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],dateFormat:"mm/dd/yy",firstDay:0,isRTL:false};this._defaults={showOn:"focus",showAnim:"show",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:false,hideIfNoPrevNext:false,navigationAsDateFormat:false,gotoCurrent:false,changeMonth:false,changeYear:false,showMonthAfterYear:false,yearRange:"-10:+10",showOtherMonths:false,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"normal",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:true,showButtonPanel:false};$.extend(this._defaults,this.regional[""]);this.dpDiv=$('<div id="'+this._mainDivId+'" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible"></div>')}$.extend(Datepicker.prototype,{markerClassName:"hasDatepicker",log:function(){if(this.debug){console.log.apply("",arguments)}},setDefaults:function(settings){extendRemove(this._defaults,settings||{});return this},_attachDatepicker:function(target,settings){var inlineSettings=null;for(var 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 inline=(nodeName=="div"||nodeName=="span");if(!target.id){target.id="dp"+(++this.uuid)}var inst=this._newInst($(target),inline);inst.settings=$.extend({},settings||{},inlineSettings||{});if(nodeName=="input"){this._connectDatepicker(target,inst)}else{if(inline){this._inlineDatepicker(target,inst)}}},_newInst:function(target,inline){var id=target[0].id.replace(/([:\[\]\.])/g,"\\\\$1");return{id:id,input:target,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:inline,dpDiv:(!inline?this.dpDiv:$('<div class="'+this._inlineClass+' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))}},_connectDatepicker:function(target,inst){var input=$(target);if(input.hasClass(this.markerClassName)){return}var appendText=this._get(inst,"appendText");var isRTL=this._get(inst,"isRTL");if(appendText){input[isRTL?"before":"after"]('<span class="'+this._appendClass+'">'+appendText+"</span>")}var showOn=this._get(inst,"showOn");if(showOn=="focus"||showOn=="both"){input.focus(this._showDatepicker)}if(showOn=="button"||showOn=="both"){var buttonText=this._get(inst,"buttonText");var buttonImage=this._get(inst,"buttonImage");var trigger=$(this._get(inst,"buttonImageOnly")?$("<img/>").addClass(this._triggerClass).attr({src:buttonImage,alt:buttonText,title:buttonText}):$('<button type="button"></button>').addClass(this._triggerClass).html(buttonImage==""?buttonText:$("<img/>").attr({src:buttonImage,alt:buttonText,title:buttonText})));input[isRTL?"before":"after"](trigger);trigger.click(function(){if($.datepicker._datepickerShowing&&$.datepicker._lastInput==target){$.datepicker._hideDatepicker()}else{$.datepicker._showDatepicker(target)}return false})}input.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).bind("setData.datepicker",function(event,key,value){inst.settings[key]=value}).bind("getData.datepicker",function(event,key){return this._get(inst,key)});$.data(target,PROP_NAME,inst)},_inlineDatepicker:function(target,inst){var divSpan=$(target);if(divSpan.hasClass(this.markerClassName)){return}divSpan.addClass(this.markerClassName).append(inst.dpDiv).bind("setData.datepicker",function(event,key,value){inst.settings[key]=value}).bind("getData.datepicker",function(event,key){return this._get(inst,key)});$.data(target,PROP_NAME,inst);this._setDate(inst,this._getDefaultDate(inst));this._updateDatepicker(inst);this._updateAlternate(inst)},_dialogDatepicker:function(input,dateText,onSelect,settings,pos){var inst=this._dialogInst;if(!inst){var id="dp"+(++this.uuid);this._dialogInput=$('<input type="text" id="'+id+'" size="1" style="position: absolute; top: -100px;"/>');this._dialogInput.keydown(this._doKeyDown);$("body").append(this._dialogInput);inst=this._dialogInst=this._newInst(this._dialogInput,false);inst.settings={};$.data(this._dialogInput[0],PROP_NAME,inst)}extendRemove(inst.settings,settings||{});this._dialogInput.val(dateText);this._pos=(pos?(pos.length?pos:[pos.pageX,pos.pageY]):null);if(!this._pos){var browserWidth=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth;var browserHeight=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight;var scrollX=document.documentElement.scrollLeft||document.body.scrollLeft;var scrollY=document.documentElement.scrollTop||document.body.scrollTop;this._pos=[(browserWidth/2)-100+scrollX,(browserHeight/2)-150+scrollY]}this._dialogInput.css("left",this._pos[0]+"px").css("top",this._pos[1]+"px");inst.settings.onSelect=onSelect;this._inDialog=true;this.dpDiv.addClass(this._dialogClass);this._showDatepicker(this._dialogInput[0]);if($.blockUI){$.blockUI(this.dpDiv)}$.data(this._dialogInput[0],PROP_NAME,inst);return this},_destroyDatepicker:function(target){var $target=$(target);if(!$target.hasClass(this.markerClassName)){return}var nodeName=target.nodeName.toLowerCase();$.removeData(target,PROP_NAME);if(nodeName=="input"){$target.siblings("."+this._appendClass).remove().end().siblings("."+this._triggerClass).remove().end().removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress)}else{if(nodeName=="div"||nodeName=="span"){$target.removeClass(this.markerClassName).empty()}}},_enableDatepicker:function(target){var $target=$(target);if(!$target.hasClass(this.markerClassName)){return}var nodeName=target.nodeName.toLowerCase();if(nodeName=="input"){target.disabled=false;$target.siblings("button."+this._triggerClass).each(function(){this.disabled=false}).end().siblings("img."+this._triggerClass).css({opacity:"1.0",cursor:""})}else{if(nodeName=="div"||nodeName=="span"){var inline=$target.children("."+this._inlineClass);inline.children().removeClass("ui-state-disabled")}}this._disabledInputs=$.map(this._disabledInputs,function(value){return(value==target?null:value)})},_disableDatepicker:function(target){var $target=$(target);if(!$target.hasClass(this.markerClassName)){return}var nodeName=target.nodeName.toLowerCase();if(nodeName=="input"){target.disabled=true;$target.siblings("button."+this._triggerClass).each(function(){this.disabled=true}).end().siblings("img."+this._triggerClass).css({opacity:"0.5",cursor:"default"})}else{if(nodeName=="div"||nodeName=="span"){var inline=$target.children("."+this._inlineClass);inline.children().addClass("ui-state-disabled")}}this._disabledInputs=$.map(this._disabledInputs,function(value){return(value==target?null:value)});this._disabledInputs[this._disabledInputs.length]=target},_isDisabledDatepicker:function(target){if(!target){return false}for(var i=0;i<this._disabledInputs.length;i++){if(this._disabledInputs[i]==target){return true}}return false},_getInst:function(target){try{return $.data(target,PROP_NAME)}catch(err){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(target,name,value){var settings=name||{};if(typeof name=="string"){settings={};settings[name]=value}var inst=this._getInst(target);if(inst){if(this._curInst==inst){this._hideDatepicker(null)}extendRemove(inst.settings,settings);var date=new Date();extendRemove(inst,{rangeStart:null,endDay:null,endMonth:null,endYear:null,selectedDay:date.getDate(),selectedMonth:date.getMonth(),selectedYear:date.getFullYear(),currentDay:date.getDate(),currentMonth:date.getMonth(),currentYear:date.getFullYear(),drawMonth:date.getMonth(),drawYear:date.getFullYear()});this._updateDatepicker(inst)}},_changeDatepicker:function(target,name,value){this._optionDatepicker(target,name,value)},_refreshDatepicker:function(target){var inst=this._getInst(target);if(inst){this._updateDatepicker(inst)}},_setDateDatepicker:function(target,date,endDate){var inst=this._getInst(target);if(inst){this._setDate(inst,date,endDate);this._updateDatepicker(inst);this._updateAlternate(inst)}},_getDateDatepicker:function(target){var inst=this._getInst(target);if(inst&&!inst.inline){this._setDateFromField(inst)}return(inst?this._getDate(inst):null)},_doKeyDown:function(event){var inst=$.datepicker._getInst(event.target);var handled=true;var isRTL=inst.dpDiv.is(".ui-datepicker-rtl");inst._keyEvent=true;if($.datepicker._datepickerShowing){switch(event.keyCode){case 9:$.datepicker._hideDatepicker(null,"");break;case 13:var sel=$("td."+$.datepicker._dayOverClass+", td."+$.datepicker._currentClass,inst.dpDiv);if(sel[0]){$.datepicker._selectDay(event.target,inst.selectedMonth,inst.selectedYear,sel[0])}else{$.datepicker._hideDatepicker(null,$.datepicker._get(inst,"duration"))}return false;break;case 27:$.datepicker._hideDatepicker(null,$.datepicker._get(inst,"duration"));break;case 33:$.datepicker._adjustDate(event.target,(event.ctrlKey?-$.datepicker._get(inst,"stepBigMonths"):-$.datepicker._get(inst,"stepMonths")),"M");break;case 34:$.datepicker._adjustDate(event.target,(event.ctrlKey?+$.datepicker._get(inst,"stepBigMonths"):+$.datepicker._get(inst,"stepMonths")),"M");break;case 35:if(event.ctrlKey||event.metaKey){$.datepicker._clearDate(event.target)}handled=event.ctrlKey||event.metaKey;break;case 36:if(event.ctrlKey||event.metaKey){$.datepicker._gotoToday(event.target)}handled=event.ctrlKey||event.metaKey;break;case 37:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,(isRTL?+1:-1),"D")}handled=event.ctrlKey||event.metaKey;if(event.originalEvent.altKey){$.datepicker._adjustDate(event.target,(event.ctrlKey?-$.datepicker._get(inst,"stepBigMonths"):-$.datepicker._get(inst,"stepMonths")),"M")}break;case 38:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,-7,"D")}handled=event.ctrlKey||event.metaKey;break;case 39:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,(isRTL?-1:+1),"D")}handled=event.ctrlKey||event.metaKey;if(event.originalEvent.altKey){$.datepicker._adjustDate(event.target,(event.ctrlKey?+$.datepicker._get(inst,"stepBigMonths"):+$.datepicker._get(inst,"stepMonths")),"M")}break;case 40:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,+7,"D")}handled=event.ctrlKey||event.metaKey;break;default:handled=false}}else{if(event.keyCode==36&&event.ctrlKey){$.datepicker._showDatepicker(this)}else{handled=false}}if(handled){event.preventDefault();event.stopPropagation()}},_doKeyPress:function(event){var inst=$.datepicker._getInst(event.target);if($.datepicker._get(inst,"constrainInput")){var chars=$.datepicker._possibleChars($.datepicker._get(inst,"dateFormat"));var chr=String.fromCharCode(event.charCode==undefined?event.keyCode:event.charCode);return event.ctrlKey||(chr<" "||!chars||chars.indexOf(chr)>-1)}},_showDatepicker:function(input){input=input.target||input;if(input.nodeName.toLowerCase()!="input"){input=$("input",input.parentNode)[0]}if($.datepicker._isDisabledDatepicker(input)||$.datepicker._lastInput==input){return}var inst=$.datepicker._getInst(input);var beforeShow=$.datepicker._get(inst,"beforeShow");extendRemove(inst.settings,(beforeShow?beforeShow.apply(input,[input,inst]):{}));$.datepicker._hideDatepicker(null,"");$.datepicker._lastInput=input;$.datepicker._setDateFromField(inst);if($.datepicker._inDialog){input.value=""}if(!$.datepicker._pos){$.datepicker._pos=$.datepicker._findPos(input);$.datepicker._pos[1]+=input.offsetHeight}var isFixed=false;$(input).parents().each(function(){isFixed|=$(this).css("position")=="fixed";return !isFixed});if(isFixed&&$.browser.opera){$.datepicker._pos[0]-=document.documentElement.scrollLeft;$.datepicker._pos[1]-=document.documentElement.scrollTop}var offset={left:$.datepicker._pos[0],top:$.datepicker._pos[1]};$.datepicker._pos=null;inst.rangeStart=null;inst.dpDiv.css({position:"absolute",display:"block",top:"-1000px"});$.datepicker._updateDatepicker(inst);offset=$.datepicker._checkOffset(inst,offset,isFixed);inst.dpDiv.css({position:($.datepicker._inDialog&&$.blockUI?"static":(isFixed?"fixed":"absolute")),display:"none",left:offset.left+"px",top:offset.top+"px"});if(!inst.inline){var showAnim=$.datepicker._get(inst,"showAnim")||"show";var duration=$.datepicker._get(inst,"duration");var postProcess=function(){$.datepicker._datepickerShowing=true;if($.browser.msie&&parseInt($.browser.version,10)<7){$("iframe.ui-datepicker-cover").css({width:inst.dpDiv.width()+4,height:inst.dpDiv.height()+4})}};if($.effects&&$.effects[showAnim]){inst.dpDiv.show(showAnim,$.datepicker._get(inst,"showOptions"),duration,postProcess)}else{inst.dpDiv[showAnim](duration,postProcess)}if(duration==""){postProcess()}if(inst.input[0].type!="hidden"){inst.input[0].focus()}$.datepicker._curInst=inst}},_updateDatepicker:function(inst){var dims={width:inst.dpDiv.width()+4,height:inst.dpDiv.height()+4};var self=this;inst.dpDiv.empty().append(this._generateHTML(inst)).find("iframe.ui-datepicker-cover").css({width:dims.width,height:dims.height}).end().find("button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a").bind("mouseout",function(){$(this).removeClass("ui-state-hover");if(this.className.indexOf("ui-datepicker-prev")!=-1){$(this).removeClass("ui-datepicker-prev-hover")}if(this.className.indexOf("ui-datepicker-next")!=-1){$(this).removeClass("ui-datepicker-next-hover")}}).bind("mouseover",function(){if(!self._isDisabledDatepicker(inst.inline?inst.dpDiv.parent()[0]:inst.input[0])){$(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");$(this).addClass("ui-state-hover");if(this.className.indexOf("ui-datepicker-prev")!=-1){$(this).addClass("ui-datepicker-prev-hover")}if(this.className.indexOf("ui-datepicker-next")!=-1){$(this).addClass("ui-datepicker-next-hover")}}}).end().find("."+this._dayOverClass+" a").trigger("mouseover").end();var numMonths=this._getNumberOfMonths(inst);var cols=numMonths[1];var width=17;if(cols>1){inst.dpDiv.addClass("ui-datepicker-multi-"+cols).css("width",(width*cols)+"em")}else{inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("")}inst.dpDiv[(numMonths[0]!=1||numMonths[1]!=1?"add":"remove")+"Class"]("ui-datepicker-multi");inst.dpDiv[(this._get(inst,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl");if(inst.input&&inst.input[0].type!="hidden"&&inst==$.datepicker._curInst){$(inst.input[0]).focus()}},_checkOffset:function(inst,offset,isFixed){var dpWidth=inst.dpDiv.outerWidth();var dpHeight=inst.dpDiv.outerHeight();var inputWidth=inst.input?inst.input.outerWidth():0;var inputHeight=inst.input?inst.input.outerHeight():0;var viewWidth=(window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth)+$(document).scrollLeft();var viewHeight=(window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight)+$(document).scrollTop();offset.left-=(this._get(inst,"isRTL")?(dpWidth-inputWidth):0);offset.left-=(isFixed&&offset.left==inst.input.offset().left)?$(document).scrollLeft():0;offset.top-=(isFixed&&offset.top==(inst.input.offset().top+inputHeight))?$(document).scrollTop():0;offset.left-=(offset.left+dpWidth>viewWidth&&viewWidth>dpWidth)?Math.abs(offset.left+dpWidth-viewWidth):0;offset.top-=(offset.top+dpHeight>viewHeight&&viewHeight>dpHeight)?Math.abs(offset.top+dpHeight+inputHeight*2-viewHeight):0;return offset},_findPos:function(obj){while(obj&&(obj.type=="hidden"||obj.nodeType!=1)){obj=obj.nextSibling}var position=$(obj).offset();return[position.left,position.top]},_hideDatepicker:function(input,duration){var inst=this._curInst;if(!inst||(input&&inst!=$.data(input,PROP_NAME))){return}if(inst.stayOpen){this._selectDate("#"+inst.id,this._formatDate(inst,inst.currentDay,inst.currentMonth,inst.currentYear))}inst.stayOpen=false;if(this._datepickerShowing){duration=(duration!=null?duration:this._get(inst,"duration"));var showAnim=this._get(inst,"showAnim");var postProcess=function(){$.datepicker._tidyDialog(inst)};if(duration!=""&&$.effects&&$.effects[showAnim]){inst.dpDiv.hide(showAnim,$.datepicker._get(inst,"showOptions"),duration,postProcess)}else{inst.dpDiv[(duration==""?"hide":(showAnim=="slideDown"?"slideUp":(showAnim=="fadeIn"?"fadeOut":"hide")))](duration,postProcess)}if(duration==""){this._tidyDialog(inst)}var onClose=this._get(inst,"onClose");if(onClose){onClose.apply((inst.input?inst.input[0]:null),[(inst.input?inst.input.val():""),inst])}this._datepickerShowing=false;this._lastInput=null;if(this._inDialog){this._dialogInput.css({position:"absolute",left:"0",top:"-100px"});if($.blockUI){$.unblockUI();$("body").append(this.dpDiv)}}this._inDialog=false}this._curInst=null},_tidyDialog:function(inst){inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(event){if(!$.datepicker._curInst){return}var $target=$(event.target);if(($target.parents("#"+$.datepicker._mainDivId).length==0)&&!$target.hasClass($.datepicker.markerClassName)&&!$target.hasClass($.datepicker._triggerClass)&&$.datepicker._datepickerShowing&&!($.datepicker._inDialog&&$.blockUI)){$.datepicker._hideDatepicker(null,"")}},_adjustDate:function(id,offset,period){var target=$(id);var inst=this._getInst(target[0]);if(this._isDisabledDatepicker(target[0])){return}this._adjustInstDate(inst,offset+(period=="M"?this._get(inst,"showCurrentAtPos"):0),period);this._updateDatepicker(inst)},_gotoToday:function(id){var target=$(id);var inst=this._getInst(target[0]);if(this._get(inst,"gotoCurrent")&&inst.currentDay){inst.selectedDay=inst.currentDay;inst.drawMonth=inst.selectedMonth=inst.currentMonth;inst.drawYear=inst.selectedYear=inst.currentYear}else{var date=new Date();inst.selectedDay=date.getDate();inst.drawMonth=inst.selectedMonth=date.getMonth();inst.drawYear=inst.selectedYear=date.getFullYear()}this._notifyChange(inst);this._adjustDate(target)},_selectMonthYear:function(id,select,period){var target=$(id);var inst=this._getInst(target[0]);inst._selectingMonthYear=false;inst["selected"+(period=="M"?"Month":"Year")]=inst["draw"+(period=="M"?"Month":"Year")]=parseInt(select.options[select.selectedIndex].value,10);this._notifyChange(inst);this._adjustDate(target)},_clickMonthYear:function(id){var target=$(id);var inst=this._getInst(target[0]);if(inst.input&&inst._selectingMonthYear&&!$.browser.msie){inst.input[0].focus()}inst._selectingMonthYear=!inst._selectingMonthYear},_selectDay:function(id,month,year,td){var target=$(id);if($(td).hasClass(this._unselectableClass)||this._isDisabledDatepicker(target[0])){return}var inst=this._getInst(target[0]);inst.selectedDay=inst.currentDay=$("a",td).html();inst.selectedMonth=inst.currentMonth=month;inst.selectedYear=inst.currentYear=year;if(inst.stayOpen){inst.endDay=inst.endMonth=inst.endYear=null}this._selectDate(id,this._formatDate(inst,inst.currentDay,inst.currentMonth,inst.currentYear));if(inst.stayOpen){inst.rangeStart=this._daylightSavingAdjust(new Date(inst.currentYear,inst.currentMonth,inst.currentDay));this._updateDatepicker(inst)}},_clearDate:function(id){var target=$(id);var inst=this._getInst(target[0]);inst.stayOpen=false;inst.endDay=inst.endMonth=inst.endYear=inst.rangeStart=null;this._selectDate(target,"")},_selectDate:function(id,dateStr){var target=$(id);var inst=this._getInst(target[0]);dateStr=(dateStr!=null?dateStr:this._formatDate(inst));if(inst.input){inst.input.val(dateStr)}this._updateAlternate(inst);var onSelect=this._get(inst,"onSelect");if(onSelect){onSelect.apply((inst.input?inst.input[0]:null),[dateStr,inst])}else{if(inst.input){inst.input.trigger("change")}}if(inst.inline){this._updateDatepicker(inst)}else{if(!inst.stayOpen){this._hideDatepicker(null,this._get(inst,"duration"));this._lastInput=inst.input[0];if(typeof(inst.input[0])!="object"){inst.input[0].focus()}this._lastInput=null}}},_updateAlternate:function(inst){var altField=this._get(inst,"altField");if(altField){var altFormat=this._get(inst,"altFormat")||this._get(inst,"dateFormat");var date=this._getDate(inst);dateStr=this.formatDate(altFormat,date,this._getFormatConfig(inst));$(altField).each(function(){$(this).val(dateStr)})}},noWeekends:function(date){var day=date.getDay();return[(day>0&&day<6),""]},iso8601Week:function(date){var checkDate=new Date(date.getFullYear(),date.getMonth(),date.getDate());var firstMon=new Date(checkDate.getFullYear(),1-1,4);var firstDay=firstMon.getDay()||7;firstMon.setDate(firstMon.getDate()+1-firstDay);if(firstDay<4&&checkDate<firstMon){checkDate.setDate(checkDate.getDate()-3);return $.datepicker.iso8601Week(checkDate)}else{if(checkDate>new Date(checkDate.getFullYear(),12-1,28)){firstDay=new Date(checkDate.getFullYear()+1,1-1,4).getDay()||7;if(firstDay>4&&(checkDate.getDay()||7)<firstDay-3){return 1}}}return Math.floor(((checkDate-firstMon)/86400000)/7)+1},parseDate:function(format,value,settings){if(format==null||value==null){throw"Invalid arguments"}value=(typeof value=="object"?value.toString():value+"");if(value==""){return null}var shortYearCutoff=(settings?settings.shortYearCutoff:null)||this._defaults.shortYearCutoff;var dayNamesShort=(settings?settings.dayNamesShort:null)||this._defaults.dayNamesShort;var dayNames=(settings?settings.dayNames:null)||this._defaults.dayNames;var monthNamesShort=(settings?settings.monthNamesShort:null)||this._defaults.monthNamesShort;var monthNames=(settings?settings.monthNames:null)||this._defaults.monthNames;var year=-1;var month=-1;var day=-1;var doy=-1;var literal=false;var lookAhead=function(match){var matches=(iFormat+1<format.length&&format.charAt(iFormat+1)==match);if(matches){iFormat++}return matches};var getNumber=function(match){lookAhead(match);var origSize=(match=="@"?14:(match=="y"?4:(match=="o"?3:2)));var size=origSize;var num=0;while(size>0&&iValue<value.length&&value.charAt(iValue)>="0"&&value.charAt(iValue)<="9"){num=num*10+parseInt(value.charAt(iValue++),10);size--}if(size==origSize){throw"Missing number at position "+iValue}return num};var getName=function(match,shortNames,longNames){var names=(lookAhead(match)?longNames:shortNames);var size=0;for(var j=0;j<names.length;j++){size=Math.max(size,names[j].length)}var name="";var iInit=iValue;while(size>0&&iValue<value.length){name+=value.charAt(iValue++);for(var i=0;i<names.length;i++){if(name==names[i]){return i+1}}size--}throw"Unknown name at position "+iInit};var checkLiteral=function(){if(value.charAt(iValue)!=format.charAt(iFormat)){throw"Unexpected literal at position "+iValue}iValue++};var iValue=0;for(var iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)=="'"&&!lookAhead("'")){literal=false}else{checkLiteral()}}else{switch(format.charAt(iFormat)){case"d":day=getNumber("d");break;case"D":getName("D",dayNamesShort,dayNames);break;case"o":doy=getNumber("o");break;case"m":month=getNumber("m");break;case"M":month=getName("M",monthNamesShort,monthNames);break;case"y":year=getNumber("y");break;case"@":var date=new Date(getNumber("@"));year=date.getFullYear();month=date.getMonth()+1;day=date.getDate();break;case"'":if(lookAhead("'")){checkLiteral()}else{literal=true}break;default:checkLiteral()}}}if(year==-1){year=new Date().getFullYear()}else{if(year<100){year+=new Date().getFullYear()-new Date().getFullYear()%100+(year<=shortYearCutoff?0:-100)}}if(doy>-1){month=1;day=doy;do{var dim=this._getDaysInMonth(year,month-1);if(day<=dim){break}month++;day-=dim}while(true)}var date=this._daylightSavingAdjust(new Date(year,month-1,day));if(date.getFullYear()!=year||date.getMonth()+1!=month||date.getDate()!=day){throw"Invalid date"}return date},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TIMESTAMP:"@",W3C:"yy-mm-dd",formatDate:function(format,date,settings){if(!date){return""}var dayNamesShort=(settings?settings.dayNamesShort:null)||this._defaults.dayNamesShort;var dayNames=(settings?settings.dayNames:null)||this._defaults.dayNames;var monthNamesShort=(settings?settings.monthNamesShort:null)||this._defaults.monthNamesShort;var monthNames=(settings?settings.monthNames:null)||this._defaults.monthNames;var lookAhead=function(match){var matches=(iFormat+1<format.length&&format.charAt(iFormat+1)==match);if(matches){iFormat++}return matches};var formatNumber=function(match,value,len){var num=""+value;if(lookAhead(match)){while(num.length<len){num="0"+num}}return num};var formatName=function(match,value,shortNames,longNames){return(lookAhead(match)?longNames[value]:shortNames[value])};var output="";var literal=false;if(date){for(var iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)=="'"&&!lookAhead("'")){literal=false}else{output+=format.charAt(iFormat)}}else{switch(format.charAt(iFormat)){case"d":output+=formatNumber("d",date.getDate(),2);break;case"D":output+=formatName("D",date.getDay(),dayNamesShort,dayNames);break;case"o":var doy=date.getDate();for(var m=date.getMonth()-1;m>=0;m--){doy+=this._getDaysInMonth(date.getFullYear(),m)}output+=formatNumber("o",doy,3);break;case"m":output+=formatNumber("m",date.getMonth()+1,2);break;case"M":output+=formatName("M",date.getMonth(),monthNamesShort,monthNames);break;case"y":output+=(lookAhead("y")?date.getFullYear():(date.getYear()%100<10?"0":"")+date.getYear()%100);break;case"@":output+=date.getTime();break;case"'":if(lookAhead("'")){output+="'"}else{literal=true}break;default:output+=format.charAt(iFormat)}}}}return output},_possibleChars:function(format){var chars="";var literal=false;for(var iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)=="'"&&!lookAhead("'")){literal=false}else{chars+=format.charAt(iFormat)}}else{switch(format.charAt(iFormat)){case"d":case"m":case"y":case"@":chars+="0123456789";break;case"D":case"M":return null;case"'":if(lookAhead("'")){chars+="'"}else{literal=true}break;default:chars+=format.charAt(iFormat)}}}return chars},_get:function(inst,name){return inst.settings[name]!==undefined?inst.settings[name]:this._defaults[name]},_setDateFromField:function(inst){var dateFormat=this._get(inst,"dateFormat");var dates=inst.input?inst.input.val():null;inst.endDay=inst.endMonth=inst.endYear=null;var date=defaultDate=this._getDefaultDate(inst);var settings=this._getFormatConfig(inst);try{date=this.parseDate(dateFormat,dates,settings)||defaultDate}catch(event){this.log(event);date=defaultDate}inst.selectedDay=date.getDate();inst.drawMonth=inst.selectedMonth=date.getMonth();inst.drawYear=inst.selectedYear=date.getFullYear();inst.currentDay=(dates?date.getDate():0);inst.currentMonth=(dates?date.getMonth():0);inst.currentYear=(dates?date.getFullYear():0);this._adjustInstDate(inst)},_getDefaultDate:function(inst){var date=this._determineDate(this._get(inst,"defaultDate"),new Date());var minDate=this._getMinMaxDate(inst,"min",true);var maxDate=this._getMinMaxDate(inst,"max");date=(minDate&&date<minDate?minDate:date);date=(maxDate&&date>maxDate?maxDate:date);return date},_determineDate:function(date,defaultDate){var offsetNumeric=function(offset){var date=new Date();date.setDate(date.getDate()+offset);return date};var offsetString=function(offset,getDaysInMonth){var date=new Date();var year=date.getFullYear();var month=date.getMonth();var day=date.getDate();var pattern=/([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;var matches=pattern.exec(offset);while(matches){switch(matches[2]||"d"){case"d":case"D":day+=parseInt(matches[1],10);break;case"w":case"W":day+=parseInt(matches[1],10)*7;break;case"m":case"M":month+=parseInt(matches[1],10);day=Math.min(day,getDaysInMonth(year,month));break;case"y":case"Y":year+=parseInt(matches[1],10);day=Math.min(day,getDaysInMonth(year,month));break}matches=pattern.exec(offset)}return new Date(year,month,day)};date=(date==null?defaultDate:(typeof date=="string"?offsetString(date,this._getDaysInMonth):(typeof date=="number"?(isNaN(date)?defaultDate:offsetNumeric(date)):date)));date=(date&&date.toString()=="Invalid Date"?defaultDate:date);if(date){date.setHours(0);date.setMinutes(0);date.setSeconds(0);date.setMilliseconds(0)}return this._daylightSavingAdjust(date)},_daylightSavingAdjust:function(date){if(!date){return null}date.setHours(date.getHours()>12?date.getHours()+2:0);return date},_setDate:function(inst,date,endDate){var clear=!(date);var origMonth=inst.selectedMonth;var origYear=inst.selectedYear;date=this._determineDate(date,new Date());inst.selectedDay=inst.currentDay=date.getDate();inst.drawMonth=inst.selectedMonth=inst.currentMonth=date.getMonth();inst.drawYear=inst.selectedYear=inst.currentYear=date.getFullYear();if(origMonth!=inst.selectedMonth||origYear!=inst.selectedYear){this._notifyChange(inst)}this._adjustInstDate(inst);if(inst.input){inst.input.val(clear?"":this._formatDate(inst))}},_getDate:function(inst){var startDate=(!inst.currentYear||(inst.input&&inst.input.val()=="")?null:this._daylightSavingAdjust(new Date(inst.currentYear,inst.currentMonth,inst.currentDay)));return startDate},_generateHTML:function(inst){var today=new Date();today=this._daylightSavingAdjust(new Date(today.getFullYear(),today.getMonth(),today.getDate()));var isRTL=this._get(inst,"isRTL");var showButtonPanel=this._get(inst,"showButtonPanel");var hideIfNoPrevNext=this._get(inst,"hideIfNoPrevNext");var navigationAsDateFormat=this._get(inst,"navigationAsDateFormat");var numMonths=this._getNumberOfMonths(inst);var showCurrentAtPos=this._get(inst,"showCurrentAtPos");var stepMonths=this._get(inst,"stepMonths");var stepBigMonths=this._get(inst,"stepBigMonths");var isMultiMonth=(numMonths[0]!=1||numMonths[1]!=1);var currentDate=this._daylightSavingAdjust((!inst.currentDay?new Date(9999,9,9):new Date(inst.currentYear,inst.currentMonth,inst.currentDay)));var minDate=this._getMinMaxDate(inst,"min",true);var maxDate=this._getMinMaxDate(inst,"max");var drawMonth=inst.drawMonth-showCurrentAtPos;var drawYear=inst.drawYear;if(drawMonth<0){drawMonth+=12;drawYear--}if(maxDate){var maxDraw=this._daylightSavingAdjust(new Date(maxDate.getFullYear(),maxDate.getMonth()-numMonths[1]+1,maxDate.getDate()));maxDraw=(minDate&&maxDraw<minDate?minDate:maxDraw);while(this._daylightSavingAdjust(new Date(drawYear,drawMonth,1))>maxDraw){drawMonth--;if(drawMonth<0){drawMonth=11;drawYear--}}}inst.drawMonth=drawMonth;inst.drawYear=drawYear;var prevText=this._get(inst,"prevText");prevText=(!navigationAsDateFormat?prevText:this.formatDate(prevText,this._daylightSavingAdjust(new Date(drawYear,drawMonth-stepMonths,1)),this._getFormatConfig(inst)));var prev=(this._canAdjustMonth(inst,-1,drawYear,drawMonth)?'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#'+inst.id+"', -"+stepMonths+", 'M');\" title=\""+prevText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"e":"w")+'">'+prevText+"</span></a>":(hideIfNoPrevNext?"":'<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+prevText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"e":"w")+'">'+prevText+"</span></a>"));var nextText=this._get(inst,"nextText");nextText=(!navigationAsDateFormat?nextText:this.formatDate(nextText,this._daylightSavingAdjust(new Date(drawYear,drawMonth+stepMonths,1)),this._getFormatConfig(inst)));var next=(this._canAdjustMonth(inst,+1,drawYear,drawMonth)?'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#'+inst.id+"', +"+stepMonths+", 'M');\" title=\""+nextText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"w":"e")+'">'+nextText+"</span></a>":(hideIfNoPrevNext?"":'<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+nextText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"w":"e")+'">'+nextText+"</span></a>"));var currentText=this._get(inst,"currentText");var gotoDate=(this._get(inst,"gotoCurrent")&&inst.currentDay?currentDate:today);currentText=(!navigationAsDateFormat?currentText:this.formatDate(currentText,gotoDate,this._getFormatConfig(inst)));var controls=(!inst.inline?'<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery.datepicker._hideDatepicker();">'+this._get(inst,"closeText")+"</button>":"");var buttonPanel=(showButtonPanel)?'<div class="ui-datepicker-buttonpane ui-widget-content">'+(isRTL?controls:"")+(this._isInRange(inst,gotoDate)?'<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery.datepicker._gotoToday(\'#'+inst.id+"');\">"+currentText+"</button>":"")+(isRTL?"":controls)+"</div>":"";var firstDay=parseInt(this._get(inst,"firstDay"),10);firstDay=(isNaN(firstDay)?0:firstDay);var dayNames=this._get(inst,"dayNames");var dayNamesShort=this._get(inst,"dayNamesShort");var dayNamesMin=this._get(inst,"dayNamesMin");var monthNames=this._get(inst,"monthNames");var monthNamesShort=this._get(inst,"monthNamesShort");var beforeShowDay=this._get(inst,"beforeShowDay");var showOtherMonths=this._get(inst,"showOtherMonths");var calculateWeek=this._get(inst,"calculateWeek")||this.iso8601Week;var endDate=inst.endDay?this._daylightSavingAdjust(new Date(inst.endYear,inst.endMonth,inst.endDay)):currentDate;var defaultDate=this._getDefaultDate(inst);var html="";for(var row=0;row<numMonths[0];row++){var group="";for(var col=0;col<numMonths[1];col++){var selectedDate=this._daylightSavingAdjust(new Date(drawYear,drawMonth,inst.selectedDay));var cornerClass=" ui-corner-all";var calender="";if(isMultiMonth){calender+='<div class="ui-datepicker-group ui-datepicker-group-';switch(col){case 0:calender+="first";cornerClass=" ui-corner-"+(isRTL?"right":"left");break;case numMonths[1]-1:calender+="last";cornerClass=" ui-corner-"+(isRTL?"left":"right");break;default:calender+="middle";cornerClass="";break}calender+='">'}calender+='<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix'+cornerClass+'">'+(/all|left/.test(cornerClass)&&row==0?(isRTL?next:prev):"")+(/all|right/.test(cornerClass)&&row==0?(isRTL?prev:next):"")+this._generateMonthYearHeader(inst,drawMonth,drawYear,minDate,maxDate,selectedDate,row>0||col>0,monthNames,monthNamesShort)+'</div><table class="ui-datepicker-calendar"><thead><tr>';var thead="";for(var dow=0;dow<7;dow++){var day=(dow+firstDay)%7;thead+="<th"+((dow+firstDay+6)%7>=5?' class="ui-datepicker-week-end"':"")+'><span title="'+dayNames[day]+'">'+dayNamesMin[day]+"</span></th>"}calender+=thead+"</tr></thead><tbody>";var daysInMonth=this._getDaysInMonth(drawYear,drawMonth);if(drawYear==inst.selectedYear&&drawMonth==inst.selectedMonth){inst.selectedDay=Math.min(inst.selectedDay,daysInMonth)}var leadDays=(this._getFirstDayOfMonth(drawYear,drawMonth)-firstDay+7)%7;var numRows=(isMultiMonth?6:Math.ceil((leadDays+daysInMonth)/7));var printDate=this._daylightSavingAdjust(new Date(drawYear,drawMonth,1-leadDays));for(var dRow=0;dRow<numRows;dRow++){calender+="<tr>";var tbody="";for(var dow=0;dow<7;dow++){var daySettings=(beforeShowDay?beforeShowDay.apply((inst.input?inst.input[0]:null),[printDate]):[true,""]);var otherMonth=(printDate.getMonth()!=drawMonth);var unselectable=otherMonth||!daySettings[0]||(minDate&&printDate<minDate)||(maxDate&&printDate>maxDate);tbody+='<td class="'+((dow+firstDay+6)%7>=5?" ui-datepicker-week-end":"")+(otherMonth?" ui-datepicker-other-month":"")+((printDate.getTime()==selectedDate.getTime()&&drawMonth==inst.selectedMonth&&inst._keyEvent)||(defaultDate.getTime()==printDate.getTime()&&defaultDate.getTime()==selectedDate.getTime())?" "+this._dayOverClass:"")+(unselectable?" "+this._unselectableClass+" ui-state-disabled":"")+(otherMonth&&!showOtherMonths?"":" "+daySettings[1]+(printDate.getTime()>=currentDate.getTime()&&printDate.getTime()<=endDate.getTime()?" "+this._currentClass:"")+(printDate.getTime()==today.getTime()?" ui-datepicker-today":""))+'"'+((!otherMonth||showOtherMonths)&&daySettings[2]?' title="'+daySettings[2]+'"':"")+(unselectable?"":" onclick=\"DP_jQuery.datepicker._selectDay('#"+inst.id+"',"+drawMonth+","+drawYear+', this);return false;"')+">"+(otherMonth?(showOtherMonths?printDate.getDate():"&#xa0;"):(unselectable?'<span class="ui-state-default">'+printDate.getDate()+"</span>":'<a class="ui-state-default'+(printDate.getTime()==today.getTime()?" ui-state-highlight":"")+(printDate.getTime()>=currentDate.getTime()&&printDate.getTime()<=endDate.getTime()?" ui-state-active":"")+'" href="#">'+printDate.getDate()+"</a>"))+"</td>";printDate.setDate(printDate.getDate()+1);printDate=this._daylightSavingAdjust(printDate)}calender+=tbody+"</tr>"}drawMonth++;if(drawMonth>11){drawMonth=0;drawYear++}calender+="</tbody></table>"+(isMultiMonth?"</div>"+((numMonths[0]>0&&col==numMonths[1]-1)?'<div class="ui-datepicker-row-break"></div>':""):"");group+=calender}html+=group}html+=buttonPanel+($.browser.msie&&parseInt($.browser.version,10)<7&&!inst.inline?'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>':"");inst._keyEvent=false;return html},_generateMonthYearHeader:function(inst,drawMonth,drawYear,minDate,maxDate,selectedDate,secondary,monthNames,monthNamesShort){minDate=(inst.rangeStart&&minDate&&selectedDate<minDate?selectedDate:minDate);var changeMonth=this._get(inst,"changeMonth");var changeYear=this._get(inst,"changeYear");var showMonthAfterYear=this._get(inst,"showMonthAfterYear");var html='<div class="ui-datepicker-title">';var monthHtml="";if(secondary||!changeMonth){monthHtml+='<span class="ui-datepicker-month">'+monthNames[drawMonth]+"</span> "}else{var inMinYear=(minDate&&minDate.getFullYear()==drawYear);var inMaxYear=(maxDate&&maxDate.getFullYear()==drawYear);monthHtml+='<select class="ui-datepicker-month" onchange="DP_jQuery.datepicker._selectMonthYear(\'#'+inst.id+"', this, 'M');\" onclick=\"DP_jQuery.datepicker._clickMonthYear('#"+inst.id+"');\">";for(var month=0;month<12;month++){if((!inMinYear||month>=minDate.getMonth())&&(!inMaxYear||month<=maxDate.getMonth())){monthHtml+='<option value="'+month+'"'+(month==drawMonth?' selected="selected"':"")+">"+monthNamesShort[month]+"</option>"}}monthHtml+="</select>"}if(!showMonthAfterYear){html+=monthHtml+((secondary||changeMonth||changeYear)&&(!(changeMonth&&changeYear))?"&#xa0;":"")}if(secondary||!changeYear){html+='<span class="ui-datepicker-year">'+drawYear+"</span>"}else{var years=this._get(inst,"yearRange").split(":");var year=0;var endYear=0;if(years.length!=2){year=drawYear-10;endYear=drawYear+10}else{if(years[0].charAt(0)=="+"||years[0].charAt(0)=="-"){year=drawYear+parseInt(years[0],10);endYear=drawYear+parseInt(years[1],10)}else{year=parseInt(years[0],10);endYear=parseInt(years[1],10)}}year=(minDate?Math.max(year,minDate.getFullYear()):year);endYear=(maxDate?Math.min(endYear,maxDate.getFullYear()):endYear);html+='<select class="ui-datepicker-year" onchange="DP_jQuery.datepicker._selectMonthYear(\'#'+inst.id+"', this, 'Y');\" onclick=\"DP_jQuery.datepicker._clickMonthYear('#"+inst.id+"');\">";for(;year<=endYear;year++){html+='<option value="'+year+'"'+(year==drawYear?' selected="selected"':"")+">"+year+"</option>"}html+="</select>"}if(showMonthAfterYear){html+=(secondary||changeMonth||changeYear?"&#xa0;":"")+monthHtml}html+="</div>";return html},_adjustInstDate:function(inst,offset,period){var year=inst.drawYear+(period=="Y"?offset:0);var month=inst.drawMonth+(period=="M"?offset:0);var day=Math.min(inst.selectedDay,this._getDaysInMonth(year,month))+(period=="D"?offset:0);var date=this._daylightSavingAdjust(new Date(year,month,day));var minDate=this._getMinMaxDate(inst,"min",true);var maxDate=this._getMinMaxDate(inst,"max");date=(minDate&&date<minDate?minDate:date);date=(maxDate&&date>maxDate?maxDate:date);inst.selectedDay=date.getDate();inst.drawMonth=inst.selectedMonth=date.getMonth();inst.drawYear=inst.selectedYear=date.getFullYear();if(period=="M"||period=="Y"){this._notifyChange(inst)}},_notifyChange:function(inst){var onChange=this._get(inst,"onChangeMonthYear");if(onChange){onChange.apply((inst.input?inst.input[0]:null),[inst.selectedYear,inst.selectedMonth+1,inst])}},_getNumberOfMonths:function(inst){var numMonths=this._get(inst,"numberOfMonths");return(numMonths==null?[1,1]:(typeof numMonths=="number"?[1,numMonths]:numMonths))},_getMinMaxDate:function(inst,minMax,checkRange){var date=this._determineDate(this._get(inst,minMax+"Date"),null);return(!checkRange||!inst.rangeStart?date:(!date||inst.rangeStart>date?inst.rangeStart:date))},_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(inst,offset,curYear,curMonth){var numMonths=this._getNumberOfMonths(inst);var date=this._daylightSavingAdjust(new Date(curYear,curMonth+(offset<0?offset:numMonths[1]),1));if(offset<0){date.setDate(this._getDaysInMonth(date.getFullYear(),date.getMonth()))}return this._isInRange(inst,date)},_isInRange:function(inst,date){var newMinDate=(!inst.rangeStart?null:this._daylightSavingAdjust(new Date(inst.selectedYear,inst.selectedMonth,inst.selectedDay)));newMinDate=(newMinDate&&inst.rangeStart<newMinDate?inst.rangeStart:newMinDate);var minDate=newMinDate||this._getMinMaxDate(inst,"min");var maxDate=this._getMinMaxDate(inst,"max");return((!minDate||date>=minDate)&&(!maxDate||date<=maxDate))},_getFormatConfig:function(inst){var shortYearCutoff=this._get(inst,"shortYearCutoff");shortYearCutoff=(typeof shortYearCutoff!="string"?shortYearCutoff:new Date().getFullYear()%100+parseInt(shortYearCutoff,10));return{shortYearCutoff:shortYearCutoff,dayNamesShort:this._get(inst,"dayNamesShort"),dayNames:this._get(inst,"dayNames"),monthNamesShort:this._get(inst,"monthNamesShort"),monthNames:this._get(inst,"monthNames")}},_formatDate:function(inst,day,month,year){if(!day){inst.currentDay=inst.selectedDay;inst.currentMonth=inst.selectedMonth;inst.currentYear=inst.selectedYear}var date=(day?(typeof day=="object"?day:this._daylightSavingAdjust(new Date(year,month,day))):this._daylightSavingAdjust(new Date(inst.currentYear,inst.currentMonth,inst.currentDay)));return this.formatDate(this._get(inst,"dateFormat"),date,this._getFormatConfig(inst))}});function extendRemove(target,props){$.extend(target,props);for(var name in props){if(props[name]==null||props[name]==undefined){target[name]=props[name]}}return target}function isArray(a){return(a&&(($.browser.safari&&typeof a=="object"&&a.length)||(a.constructor&&a.constructor.toString().match(/\Array\(\)/))))}$.fn.datepicker=function(options){if(!$.datepicker.initialized){$(document).mousedown($.datepicker._checkExternalClick).find("body").append($.datepicker.dpDiv);$.datepicker.initialized=true}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)})};$.datepicker=new Datepicker();$.datepicker.initialized=false;$.datepicker.uuid=new Date().getTime();$.datepicker.version="1.7";window.DP_jQuery=$})(jQuery);;/*
 * jQuery UI Progressbar 1.7
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Progressbar
 *
 * Depends:
 *   ui.core.js
 */(function(a){a.widget("ui.progressbar",{_init:function(){this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this._valueMin(),"aria-valuemax":this._valueMax(),"aria-valuenow":this._value()});this.valueDiv=a('<div class="ui-progressbar-value ui-widget-header ui-corner-left"></div>').appendTo(this.element);this._refreshValue()},destroy:function(){this.element.removeClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow").removeData("progressbar").unbind(".progressbar");this.valueDiv.remove();a.widget.prototype.destroy.apply(this,arguments)},value:function(b){arguments.length&&this._setData("value",b);return this._value()},_setData:function(b,c){switch(b){case"value":this.options.value=c;this._refreshValue();this._trigger("change",null,{});break}a.widget.prototype._setData.apply(this,arguments)},_value:function(){var b=this.options.value;if(b<this._valueMin()){b=this._valueMin()}if(b>this._valueMax()){b=this._valueMax()}return b},_valueMin:function(){var b=0;return b},_valueMax:function(){var b=100;return b},_refreshValue:function(){var b=this.value();this.valueDiv[b==this._valueMax()?"addClass":"removeClass"]("ui-corner-right");this.valueDiv.width(b+"%");this.element.attr("aria-valuenow",b)}});a.extend(a.ui.progressbar,{version:"1.7",defaults:{value:0}})})(jQuery);;/*
 * jQuery UI Effects 1.7
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/
 */jQuery.effects||(function(d){d.effects={version:"1.7",save:function(g,h){for(var f=0;f<h.length;f++){if(h[f]!==null){g.data("ec.storage."+h[f],g[0].style[h[f]])}}},restore:function(g,h){for(var f=0;f<h.length;f++){if(h[f]!==null){g.css(h[f],g.data("ec.storage."+h[f]))}}},setMode:function(f,g){if(g=="toggle"){g=f.is(":hidden")?"show":"hide"}return g},getBaseline:function(g,h){var i,f;switch(g[0]){case"top":i=0;break;case"middle":i=0.5;break;case"bottom":i=1;break;default:i=g[0]/h.height}switch(g[1]){case"left":f=0;break;case"center":f=0.5;break;case"right":f=1;break;default:f=g[1]/h.width}return{x:f,y:i}},createWrapper:function(f){if(f.parent().is(".ui-effects-wrapper")){return f.parent()}var g={width:f.outerWidth(true),height:f.outerHeight(true),"float":f.css("float")};f.wrap('<div class="ui-effects-wrapper" style="font-size:100%;background:transparent;border:none;margin:0;padding:0"></div>');var j=f.parent();if(f.css("position")=="static"){j.css({position:"relative"});f.css({position:"relative"})}else{var i=f.css("top");if(isNaN(parseInt(i,10))){i="auto"}var h=f.css("left");if(isNaN(parseInt(h,10))){h="auto"}j.css({position:f.css("position"),top:i,left:h,zIndex:f.css("z-index")}).show();f.css({position:"relative",top:0,left:0})}j.css(g);return j},removeWrapper:function(f){if(f.parent().is(".ui-effects-wrapper")){return f.parent().replaceWith(f)}return f},setTransition:function(g,i,f,h){h=h||{};d.each(i,function(k,j){unit=g.cssUnit(j);if(unit[0]>0){h[j]=unit[0]*f+unit[1]}});return h},animateClass:function(h,i,k,j){var f=(typeof k=="function"?k:(j?j:null));var g=(typeof k=="string"?k:null);return this.each(function(){var q={};var o=d(this);var p=o.attr("style")||"";if(typeof p=="object"){p=p.cssText}if(h.toggle){o.hasClass(h.toggle)?h.remove=h.toggle:h.add=h.toggle}var l=d.extend({},(document.defaultView?document.defaultView.getComputedStyle(this,null):this.currentStyle));if(h.add){o.addClass(h.add)}if(h.remove){o.removeClass(h.remove)}var m=d.extend({},(document.defaultView?document.defaultView.getComputedStyle(this,null):this.currentStyle));if(h.add){o.removeClass(h.add)}if(h.remove){o.addClass(h.remove)}for(var r in m){if(typeof m[r]!="function"&&m[r]&&r.indexOf("Moz")==-1&&r.indexOf("length")==-1&&m[r]!=l[r]&&(r.match(/color/i)||(!r.match(/color/i)&&!isNaN(parseInt(m[r],10))))&&(l.position!="static"||(l.position=="static"&&!r.match(/left|top|bottom|right/)))){q[r]=m[r]}}o.animate(q,i,g,function(){if(typeof d(this).attr("style")=="object"){d(this).attr("style")["cssText"]="";d(this).attr("style")["cssText"]=p}else{d(this).attr("style",p)}if(h.add){d(this).addClass(h.add)}if(h.remove){d(this).removeClass(h.remove)}if(f){f.apply(this,arguments)}})})}};function c(g,f){var i=g[1]&&g[1].constructor==Object?g[1]:{};if(f){i.mode=f}var h=g[1]&&g[1].constructor!=Object?g[1]:(i.duration?i.duration:g[2]);h=d.fx.off?0:typeof h==="number"?h:d.fx.speeds[h]||d.fx.speeds._default;var j=i.callback||(d.isFunction(g[1])&&g[1])||(d.isFunction(g[2])&&g[2])||(d.isFunction(g[3])&&g[3]);return[g[0],i,h,j]}d.fn.extend({_show:d.fn.show,_hide:d.fn.hide,__toggle:d.fn.toggle,_addClass:d.fn.addClass,_removeClass:d.fn.removeClass,_toggleClass:d.fn.toggleClass,effect:function(g,f,h,i){return d.effects[g]?d.effects[g].call(this,{method:g,options:f||{},duration:h,callback:i}):null},show:function(){if(!arguments[0]||(arguments[0].constructor==Number||(/(slow|normal|fast)/).test(arguments[0]))){return this._show.apply(this,arguments)}else{return this.effect.apply(this,c(arguments,"show"))}},hide:function(){if(!arguments[0]||(arguments[0].constructor==Number||(/(slow|normal|fast)/).test(arguments[0]))){return this._hide.apply(this,arguments)}else{return this.effect.apply(this,c(arguments,"hide"))}},toggle:function(){if(!arguments[0]||(arguments[0].constructor==Number||(/(slow|normal|fast)/).test(arguments[0]))||(arguments[0].constructor==Function)){return this.__toggle.apply(this,arguments)}else{return this.effect.apply(this,c(arguments,"toggle"))}},addClass:function(g,f,i,h){return f?d.effects.animateClass.apply(this,[{add:g},f,i,h]):this._addClass(g)},removeClass:function(g,f,i,h){return f?d.effects.animateClass.apply(this,[{remove:g},f,i,h]):this._removeClass(g)},toggleClass:function(g,f,i,h){return((typeof f!=="boolean")&&f)?d.effects.animateClass.apply(this,[{toggle:g},f,i,h]):this._toggleClass(g,f)},morph:function(f,h,g,j,i){return d.effects.animateClass.apply(this,[{add:h,remove:f},g,j,i])},switchClass:function(){return this.morph.apply(this,arguments)},cssUnit:function(f){var g=this.css(f),h=[];d.each(["em","px","%","pt"],function(j,k){if(g.indexOf(k)>0){h=[parseFloat(g),k]}});return h}});d.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","color","outlineColor"],function(g,f){d.fx.step[f]=function(h){if(h.state==0){h.start=e(h.elem,f);h.end=b(h.end)}h.elem.style[f]="rgb("+[Math.max(Math.min(parseInt((h.pos*(h.end[0]-h.start[0]))+h.start[0],10),255),0),Math.max(Math.min(parseInt((h.pos*(h.end[1]-h.start[1]))+h.start[1],10),255),0),Math.max(Math.min(parseInt((h.pos*(h.end[2]-h.start[2]))+h.start[2],10),255),0)].join(",")+")"}});function b(g){var f;if(g&&g.constructor==Array&&g.length==3){return g}if(f=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(g)){return[parseInt(f[1],10),parseInt(f[2],10),parseInt(f[3],10)]}if(f=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(g)){return[parseFloat(f[1])*2.55,parseFloat(f[2])*2.55,parseFloat(f[3])*2.55]}if(f=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(g)){return[parseInt(f[1],16),parseInt(f[2],16),parseInt(f[3],16)]}if(f=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(g)){return[parseInt(f[1]+f[1],16),parseInt(f[2]+f[2],16),parseInt(f[3]+f[3],16)]}if(f=/rgba\(0, 0, 0, 0\)/.exec(g)){return a.transparent}return a[d.trim(g).toLowerCase()]}function e(h,f){var g;do{g=d.curCSS(h,f);if(g!=""&&g!="transparent"||d.nodeName(h,"body")){break}f="backgroundColor"}while(h=h.parentNode);return b(g)}var a={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]};d.easing.jswing=d.easing.swing;d.extend(d.easing,{def:"easeOutQuad",swing:function(g,h,f,j,i){return d.easing[d.easing.def](g,h,f,j,i)},easeInQuad:function(g,h,f,j,i){return j*(h/=i)*h+f},easeOutQuad:function(g,h,f,j,i){return -j*(h/=i)*(h-2)+f},easeInOutQuad:function(g,h,f,j,i){if((h/=i/2)<1){return j/2*h*h+f}return -j/2*((--h)*(h-2)-1)+f},easeInCubic:function(g,h,f,j,i){return j*(h/=i)*h*h+f},easeOutCubic:function(g,h,f,j,i){return j*((h=h/i-1)*h*h+1)+f},easeInOutCubic:function(g,h,f,j,i){if((h/=i/2)<1){return j/2*h*h*h+f}return j/2*((h-=2)*h*h+2)+f},easeInQuart:function(g,h,f,j,i){return j*(h/=i)*h*h*h+f},easeOutQuart:function(g,h,f,j,i){return -j*((h=h/i-1)*h*h*h-1)+f},easeInOutQuart:function(g,h,f,j,i){if((h/=i/2)<1){return j/2*h*h*h*h+f}return -j/2*((h-=2)*h*h*h-2)+f},easeInQuint:function(g,h,f,j,i){return j*(h/=i)*h*h*h*h+f},easeOutQuint:function(g,h,f,j,i){return j*((h=h/i-1)*h*h*h*h+1)+f},easeInOutQuint:function(g,h,f,j,i){if((h/=i/2)<1){return j/2*h*h*h*h*h+f}return j/2*((h-=2)*h*h*h*h+2)+f},easeInSine:function(g,h,f,j,i){return -j*Math.cos(h/i*(Math.PI/2))+j+f},easeOutSine:function(g,h,f,j,i){return j*Math.sin(h/i*(Math.PI/2))+f},easeInOutSine:function(g,h,f,j,i){return -j/2*(Math.cos(Math.PI*h/i)-1)+f},easeInExpo:function(g,h,f,j,i){return(h==0)?f:j*Math.pow(2,10*(h/i-1))+f},easeOutExpo:function(g,h,f,j,i){return(h==i)?f+j:j*(-Math.pow(2,-10*h/i)+1)+f},easeInOutExpo:function(g,h,f,j,i){if(h==0){return f}if(h==i){return f+j}if((h/=i/2)<1){return j/2*Math.pow(2,10*(h-1))+f}return j/2*(-Math.pow(2,-10*--h)+2)+f},easeInCirc:function(g,h,f,j,i){return -j*(Math.sqrt(1-(h/=i)*h)-1)+f},easeOutCirc:function(g,h,f,j,i){return j*Math.sqrt(1-(h=h/i-1)*h)+f},easeInOutCirc:function(g,h,f,j,i){if((h/=i/2)<1){return -j/2*(Math.sqrt(1-h*h)-1)+f}return j/2*(Math.sqrt(1-(h-=2)*h)+1)+f},easeInElastic:function(g,i,f,m,l){var j=1.70158;var k=0;var h=m;if(i==0){return f}if((i/=l)==1){return f+m}if(!k){k=l*0.3}if(h<Math.abs(m)){h=m;var j=k/4}else{var j=k/(2*Math.PI)*Math.asin(m/h)}return -(h*Math.pow(2,10*(i-=1))*Math.sin((i*l-j)*(2*Math.PI)/k))+f},easeOutElastic:function(g,i,f,m,l){var j=1.70158;var k=0;var h=m;if(i==0){return f}if((i/=l)==1){return f+m}if(!k){k=l*0.3}if(h<Math.abs(m)){h=m;var j=k/4}else{var j=k/(2*Math.PI)*Math.asin(m/h)}return h*Math.pow(2,-10*i)*Math.sin((i*l-j)*(2*Math.PI)/k)+m+f},easeInOutElastic:function(g,i,f,m,l){var j=1.70158;var k=0;var h=m;if(i==0){return f}if((i/=l/2)==2){return f+m}if(!k){k=l*(0.3*1.5)}if(h<Math.abs(m)){h=m;var j=k/4}else{var j=k/(2*Math.PI)*Math.asin(m/h)}if(i<1){return -0.5*(h*Math.pow(2,10*(i-=1))*Math.sin((i*l-j)*(2*Math.PI)/k))+f}return h*Math.pow(2,-10*(i-=1))*Math.sin((i*l-j)*(2*Math.PI)/k)*0.5+m+f},easeInBack:function(g,h,f,k,j,i){if(i==undefined){i=1.70158}return k*(h/=j)*h*((i+1)*h-i)+f},easeOutBack:function(g,h,f,k,j,i){if(i==undefined){i=1.70158}return k*((h=h/j-1)*h*((i+1)*h+i)+1)+f},easeInOutBack:function(g,h,f,k,j,i){if(i==undefined){i=1.70158}if((h/=j/2)<1){return k/2*(h*h*(((i*=(1.525))+1)*h-i))+f}return k/2*((h-=2)*h*(((i*=(1.525))+1)*h+i)+2)+f},easeInBounce:function(g,h,f,j,i){return j-d.easing.easeOutBounce(g,i-h,0,j,i)+f},easeOutBounce:function(g,h,f,j,i){if((h/=i)<(1/2.75)){return j*(7.5625*h*h)+f}else{if(h<(2/2.75)){return j*(7.5625*(h-=(1.5/2.75))*h+0.75)+f}else{if(h<(2.5/2.75)){return j*(7.5625*(h-=(2.25/2.75))*h+0.9375)+f}else{return j*(7.5625*(h-=(2.625/2.75))*h+0.984375)+f}}}},easeInOutBounce:function(g,h,f,j,i){if(h<i/2){return d.easing.easeInBounce(g,h*2,0,j,i)*0.5+f}return d.easing.easeOutBounce(g,h*2-i,0,j,i)*0.5+j*0.5+f}})})(jQuery);;/*
 * jQuery UI Effects Blind 1.7
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Blind
 *
 * Depends:
 *	effects.core.js
 */(function(a){a.effects.blind=function(b){return this.queue(function(){var d=a(this),c=["position","top","left"];var h=a.effects.setMode(d,b.options.mode||"hide");var g=b.options.direction||"vertical";a.effects.save(d,c);d.show();var j=a.effects.createWrapper(d).css({overflow:"hidden"});var e=(g=="vertical")?"height":"width";var i=(g=="vertical")?j.height():j.width();if(h=="show"){j.css(e,0)}var f={};f[e]=h=="show"?i:0;j.animate(f,b.duration,b.options.easing,function(){if(h=="hide"){d.hide()}a.effects.restore(d,c);a.effects.removeWrapper(d);if(b.callback){b.callback.apply(d[0],arguments)}d.dequeue()})})}})(jQuery);;/*
 * jQuery UI Effects Fold 1.7
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Fold
 *
 * Depends:
 *	effects.core.js
 */(function(a){a.effects.fold=function(b){return this.queue(function(){var e=a(this),k=["position","top","left"];var h=a.effects.setMode(e,b.options.mode||"hide");var o=b.options.size||15;var n=!(!b.options.horizFirst);var g=b.duration?b.duration/2:a.fx.speeds._default/2;a.effects.save(e,k);e.show();var d=a.effects.createWrapper(e).css({overflow:"hidden"});var i=((h=="show")!=n);var f=i?["width","height"]:["height","width"];var c=i?[d.width(),d.height()]:[d.height(),d.width()];var j=/([0-9]+)%/.exec(o);if(j){o=parseInt(j[1],10)/100*c[h=="hide"?0:1]}if(h=="show"){d.css(n?{height:0,width:o}:{height:o,width:0})}var m={},l={};m[f[0]]=h=="show"?c[0]:o;l[f[1]]=h=="show"?c[1]:0;d.animate(m,g,b.options.easing).animate(l,g,b.options.easing,function(){if(h=="hide"){e.hide()}a.effects.restore(e,k);a.effects.removeWrapper(e);if(b.callback){b.callback.apply(e[0],arguments)}e.dequeue()})})}})(jQuery);;/*
 * jQuery UI Effects Highlight 1.7
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Highlight
 *
 * Depends:
 *	effects.core.js
 */(function(a){a.effects.highlight=function(b){return this.queue(function(){var e=a(this),d=["backgroundImage","backgroundColor","opacity"];var h=a.effects.setMode(e,b.options.mode||"show");var c=b.options.color||"#ffff99";var g=e.css("backgroundColor");a.effects.save(e,d);e.show();e.css({backgroundImage:"none",backgroundColor:c});var f={backgroundColor:g};if(h=="hide"){f.opacity=0}e.animate(f,{queue:false,duration:b.duration,easing:b.options.easing,complete:function(){if(h=="hide"){e.hide()}a.effects.restore(e,d);if(h=="show"&&a.browser.msie){this.style.removeAttribute("filter")}if(b.callback){b.callback.apply(this,arguments)}e.dequeue()}})})}})(jQuery);;/*
 * jQuery UI Effects Slide 1.7
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Slide
 *
 * Depends:
 *	effects.core.js
 */(function(a){a.effects.slide=function(b){return this.queue(function(){var e=a(this),d=["position","top","left"];var i=a.effects.setMode(e,b.options.mode||"show");var h=b.options.direction||"left";a.effects.save(e,d);e.show();a.effects.createWrapper(e).css({overflow:"hidden"});var f=(h=="up"||h=="down")?"top":"left";var c=(h=="up"||h=="left")?"pos":"neg";var j=b.options.distance||(f=="top"?e.outerHeight({margin:true}):e.outerWidth({margin:true}));if(i=="show"){e.css(f,c=="pos"?-j:j)}var g={};g[f]=(i=="show"?(c=="pos"?"+=":"-="):(c=="pos"?"-=":"+="))+j;e.animate(g,{queue:false,duration:b.duration,easing:b.options.easing,complete:function(){if(i=="hide"){e.hide()}a.effects.restore(e,d);a.effects.removeWrapper(e);if(b.callback){b.callback.apply(this,arguments)}e.dequeue()}})})}})(jQuery);;
// -----------------------------------------------------------------------
// eros@recoding.it
// jqprint 0.3
//
// - 19/06/2009 - some new implementations, added Opera support
// - 11/05/2009 - first sketch
//
// Printing plug-in for jQuery, evolution of jPrintArea: http://plugins.jquery.com/project/jPrintArea
// requires jQuery 1.3.x
//------------------------------------------------------------------------

(function($) {
    var opt;

    $.fn.jqprint = function (options) {
        opt = $.extend({}, $.fn.jqprint.defaults, options);

        var $element = (this instanceof jQuery) ? this : $(this);

        if (opt.operaSupport && $.browser.opera)
        {
            var tab = window.open("","jqPrint-preview");
            tab.document.open();

            var doc = tab.document;
        }
        else
        {
            var $iframe = $("<iframe  />");

            if (!opt.debug) { $iframe.css({ position: "absolute", width: "0px", height: "0px", left: "-600px", top: "-600px" }); }

            $iframe.appendTo("body");
            var doc = $iframe[0].contentWindow.document;
        }

        if (opt.importCSS)
        {
            if ($("link[media=print]").length > 0)
            {
                $("link[media=print]").each( function() {
                    doc.write("<link type='text/css' rel='stylesheet' href='" + $(this).attr("href") + "' media='print' />");
                });
            }
            else
            {
                $("link").each( function() {
                    doc.write("<link type='text/css' rel='stylesheet' href='" + $(this).attr("href") + "' />");
                });
            }
        }

        if (opt.printContainer) { doc.write($element.outer()); }
        else { $element.each( function() { doc.write($(this).html()); }); }

        doc.close();

        (opt.operaSupport && $.browser.opera ? tab : $iframe[0].contentWindow).focus();
        setTimeout( function() { (opt.operaSupport && $.browser.opera ? tab : $iframe[0].contentWindow).print(); if (tab) { tab.close(); } }, 1000);
    }

    $.fn.jqprint.defaults = {
		debug: false,
		importCSS: true,
		printContainer: true,
		operaSupport: true
	};

    // Thanks to 9__, found at http://users.livejournal.com/9__/380664.html
    jQuery.fn.outer = function() {
      return $($('<div></div>').html(this.clone())).html();
    }
})(jQuery);
/*! Copyright (c) 2008 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version 2.1.2-pre
 */

(function($){

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

})(jQuery);
/**
 * jCarousel - Riding carousels with jQuery
 *   http://sorgalla.com/jcarousel/
 *
 * Copyright (c) 2006 Jan Sorgalla (http://sorgalla.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Built on top of the jQuery library
 *   http://jquery.com
 *
 * Inspired by the "Carousel Component" by Bill Scott
 *   http://billwscott.com/carousel/
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(9($){$.1v.C=9(o){z 4.1b(9(){3p r(4,o)})};8 q={Z:F,25:1,21:1,u:7,1c:3,15:7,1K:\'2X\',2c:\'2Q\',1q:0,B:7,1j:7,1G:7,2F:7,2B:7,2z:7,2x:7,2v:7,2s:7,2p:7,1S:\'<P></P>\',1Q:\'<P></P>\',2m:\'2l\',2k:\'2l\',1O:7,1L:7};$.C=9(e,o){4.5=$.16({},q,o||{});4.Q=F;4.D=7;4.H=7;4.t=7;4.U=7;4.R=7;4.N=!4.5.Z?\'1H\':\'26\';4.E=!4.5.Z?\'24\':\'23\';8 a=\'\',1e=e.K.1e(\' \');1r(8 i=0;i<1e.I;i++){6(1e[i].2y(\'C-2w\')!=-1){$(e).1E(1e[i]);8 a=1e[i];1p}}6(e.2t==\'3o\'||e.2t==\'3n\'){4.t=$(e);4.D=4.t.19();6(4.D.1o(\'C-H\')){6(!4.D.19().1o(\'C-D\'))4.D=4.D.B(\'<P></P>\');4.D=4.D.19()}10 6(!4.D.1o(\'C-D\'))4.D=4.t.B(\'<P></P>\').19()}10{4.D=$(e);4.t=$(e).3h(\'>2o,>2n,P>2o,P>2n\')}6(a!=\'\'&&4.D.19()[0].K.2y(\'C-2w\')==-1)4.D.B(\'<P 3g=" \'+a+\'"></P>\');4.H=4.t.19();6(!4.H.I||!4.H.1o(\'C-H\'))4.H=4.t.B(\'<P></P>\').19();4.R=$(\'.C-11\',4.D);6(4.R.u()==0&&4.5.1Q!=7)4.R=4.H.1z(4.5.1Q).11();4.R.V(4.K(\'C-11\'));4.U=$(\'.C-17\',4.D);6(4.U.u()==0&&4.5.1S!=7)4.U=4.H.1z(4.5.1S).11();4.U.V(4.K(\'C-17\'));4.H.V(4.K(\'C-H\'));4.t.V(4.K(\'C-t\'));4.D.V(4.K(\'C-D\'));8 b=4.5.15!=7?1k.1P(4.1m()/4.5.15):7;8 c=4.t.32(\'1F\');8 d=4;6(c.u()>0){8 f=0,i=4.5.21;c.1b(9(){d.1I(4,i++);f+=d.S(4,b)});4.t.y(4.N,f+\'T\');6(!o||o.u===J)4.5.u=c.u()}4.D.y(\'1y\',\'1A\');4.U.y(\'1y\',\'1A\');4.R.y(\'1y\',\'1A\');4.2G=9(){d.17()};4.2b=9(){d.11()};4.1U=9(){d.2q()};6(4.5.1j!=7)4.5.1j(4,\'2a\');6($.2A.28){4.1f(F,F);$(27).1u(\'2I\',9(){d.1t()})}10 4.1t()};8 r=$.C;r.1v=r.2H={C:\'0.2.3\'};r.1v.16=r.16=$.16;r.1v.16({1t:9(){4.A=7;4.G=7;4.X=7;4.13=7;4.14=F;4.1d=7;4.O=7;4.W=F;6(4.Q)z;4.t.y(4.E,4.1s(4.5.21)+\'T\');8 p=4.1s(4.5.25);4.X=4.13=7;4.1i(p,F);$(27).22(\'2E\',4.1U).1u(\'2E\',4.1U)},2D:9(){4.t.2C();4.t.y(4.E,\'3u\');4.t.y(4.N,\'3t\');6(4.5.1j!=7)4.5.1j(4,\'2D\');4.1t()},2q:9(){6(4.O!=7&&4.W)4.t.y(4.E,r.M(4.t.y(4.E))+4.O);4.O=7;4.W=F;6(4.5.1G!=7)4.5.1G(4);6(4.5.15!=7){8 a=4;8 b=1k.1P(4.1m()/4.5.15),N=0,E=0;$(\'1F\',4.t).1b(9(i){N+=a.S(4,b);6(i+1<a.A)E=N});4.t.y(4.N,N+\'T\');4.t.y(4.E,-E+\'T\')}4.1c(4.A,F)},3s:9(){4.Q=1h;4.1f()},3r:9(){4.Q=F;4.1f()},u:9(s){6(s!=J){4.5.u=s;6(!4.Q)4.1f()}z 4.5.u},3q:9(i,a){6(a==J||!a)a=i;6(4.5.u!==7&&a>4.5.u)a=4.5.u;1r(8 j=i;j<=a;j++){8 e=4.L(j);6(!e.I||e.1o(\'C-1a-1D\'))z F}z 1h},L:9(i){z $(\'.C-1a-\'+i,4.t)},2u:9(i,s){8 e=4.L(i),20=0,2u=0;6(e.I==0){8 c,e=4.1B(i),j=r.M(i);1n(c=4.L(--j)){6(j<=0||c.I){j<=0?4.t.2r(e):c.1X(e);1p}}}10 20=4.S(e);e.1E(4.K(\'C-1a-1D\'));1R s==\'3l\'?e.3k(s):e.2C().3j(s);8 a=4.5.15!=7?1k.1P(4.1m()/4.5.15):7;8 b=4.S(e,a)-20;6(i>0&&i<4.A)4.t.y(4.E,r.M(4.t.y(4.E))-b+\'T\');4.t.y(4.N,r.M(4.t.y(4.N))+b+\'T\');z e},1V:9(i){8 e=4.L(i);6(!e.I||(i>=4.A&&i<=4.G))z;8 d=4.S(e);6(i<4.A)4.t.y(4.E,r.M(4.t.y(4.E))+d+\'T\');e.1V();4.t.y(4.N,r.M(4.t.y(4.N))-d+\'T\')},17:9(){4.1C();6(4.O!=7&&!4.W)4.1T(F);10 4.1c(((4.5.B==\'1Z\'||4.5.B==\'G\')&&4.5.u!=7&&4.G==4.5.u)?1:4.A+4.5.1c)},11:9(){4.1C();6(4.O!=7&&4.W)4.1T(1h);10 4.1c(((4.5.B==\'1Z\'||4.5.B==\'A\')&&4.5.u!=7&&4.A==1)?4.5.u:4.A-4.5.1c)},1T:9(b){6(4.Q||4.14||!4.O)z;8 a=r.M(4.t.y(4.E));!b?a-=4.O:a+=4.O;4.W=!b;4.X=4.A;4.13=4.G;4.1i(a)},1c:9(i,a){6(4.Q||4.14)z;4.1i(4.1s(i),a)},1s:9(i){6(4.Q||4.14)z;6(4.5.B!=\'18\')i=i<1?1:(4.5.u&&i>4.5.u?4.5.u:i);8 a=4.A>i;8 b=r.M(4.t.y(4.E));8 f=4.5.B!=\'18\'&&4.A<=1?1:4.A;8 c=a?4.L(f):4.L(4.G);8 j=a?f:f-1;8 e=7,l=0,p=F,d=0;1n(a?--j>=i:++j<i){e=4.L(j);p=!e.I;6(e.I==0){e=4.1B(j).V(4.K(\'C-1a-1D\'));c[a?\'1z\':\'1X\'](e)}c=e;d=4.S(e);6(p)l+=d;6(4.A!=7&&(4.5.B==\'18\'||(j>=1&&(4.5.u==7||j<=4.5.u))))b=a?b+d:b-d}8 g=4.1m();8 h=[];8 k=0,j=i,v=0;8 c=4.L(i-1);1n(++k){e=4.L(j);p=!e.I;6(e.I==0){e=4.1B(j).V(4.K(\'C-1a-1D\'));c.I==0?4.t.2r(e):c[a?\'1z\':\'1X\'](e)}c=e;8 d=4.S(e);6(d==0){3f(\'3e: 3d 1H/26 3c 1r 3b. 3a 39 38 37 36 35. 34...\');z 0}6(4.5.B!=\'18\'&&4.5.u!==7&&j>4.5.u)h.33(e);10 6(p)l+=d;v+=d;6(v>=g)1p;j++}1r(8 x=0;x<h.I;x++)h[x].1V();6(l>0){4.t.y(4.N,4.S(4.t)+l+\'T\');6(a){b-=l;4.t.y(4.E,r.M(4.t.y(4.E))-l+\'T\')}}8 n=i+k-1;6(4.5.B!=\'18\'&&4.5.u&&n>4.5.u)n=4.5.u;6(j>n){k=0,j=n,v=0;1n(++k){8 e=4.L(j--);6(!e.I)1p;v+=4.S(e);6(v>=g)1p}}8 o=n-k+1;6(4.5.B!=\'18\'&&o<1)o=1;6(4.W&&a){b+=4.O;4.W=F}4.O=7;6(4.5.B!=\'18\'&&n==4.5.u&&(n-k+1)>=1){8 m=r.Y(4.L(n),!4.5.Z?\'1l\':\'1N\');6((v-m)>g)4.O=v-g-m}1n(i-->o)b+=4.S(4.L(i));4.X=4.A;4.13=4.G;4.A=o;4.G=n;z b},1i:9(p,a){6(4.Q||4.14)z;4.14=1h;8 b=4;8 c=9(){b.14=F;6(p==0)b.t.y(b.E,0);6(b.5.B==\'1Z\'||b.5.B==\'G\'||b.5.u==7||b.G<b.5.u)b.2j();b.1f();b.1M(\'2i\')};4.1M(\'31\');6(!4.5.1K||a==F){4.t.y(4.E,p+\'T\');c()}10{8 o=!4.5.Z?{\'24\':p}:{\'23\':p};4.t.1i(o,4.5.1K,4.5.2c,c)}},2j:9(s){6(s!=J)4.5.1q=s;6(4.5.1q==0)z 4.1C();6(4.1d!=7)z;8 a=4;4.1d=30(9(){a.17()},4.5.1q*2Z)},1C:9(){6(4.1d==7)z;2Y(4.1d);4.1d=7},1f:9(n,p){6(n==J||n==7){8 n=!4.Q&&4.5.u!==0&&((4.5.B&&4.5.B!=\'A\')||4.5.u==7||4.G<4.5.u);6(!4.Q&&(!4.5.B||4.5.B==\'A\')&&4.5.u!=7&&4.G>=4.5.u)n=4.O!=7&&!4.W}6(p==J||p==7){8 p=!4.Q&&4.5.u!==0&&((4.5.B&&4.5.B!=\'G\')||4.A>1);6(!4.Q&&(!4.5.B||4.5.B==\'G\')&&4.5.u!=7&&4.A==1)p=4.O!=7&&4.W}8 a=4;4.U[n?\'1u\':\'22\'](4.5.2m,4.2G)[n?\'1E\':\'V\'](4.K(\'C-17-1w\')).1J(\'1w\',n?F:1h);4.R[p?\'1u\':\'22\'](4.5.2k,4.2b)[p?\'1E\':\'V\'](4.K(\'C-11-1w\')).1J(\'1w\',p?F:1h);6(4.U.I>0&&(4.U[0].1g==J||4.U[0].1g!=n)&&4.5.1O!=7){4.U.1b(9(){a.5.1O(a,4,n)});4.U[0].1g=n}6(4.R.I>0&&(4.R[0].1g==J||4.R[0].1g!=p)&&4.5.1L!=7){4.R.1b(9(){a.5.1L(a,4,p)});4.R[0].1g=p}},1M:9(a){8 b=4.X==7?\'2a\':(4.X<4.A?\'17\':\'11\');4.12(\'2F\',a,b);6(4.X!==4.A){4.12(\'2B\',a,b,4.A);4.12(\'2z\',a,b,4.X)}6(4.13!==4.G){4.12(\'2x\',a,b,4.G);4.12(\'2v\',a,b,4.13)}4.12(\'2s\',a,b,4.A,4.G,4.X,4.13);4.12(\'2p\',a,b,4.X,4.13,4.A,4.G)},12:9(a,b,c,d,e,f,g){6(4.5[a]==J||(1R 4.5[a]!=\'2h\'&&b!=\'2i\'))z;8 h=1R 4.5[a]==\'2h\'?4.5[a][b]:4.5[a];6(!$.2W(h))z;8 j=4;6(d===J)h(j,c,b);10 6(e===J)4.L(d).1b(9(){h(j,4,d,c,b)});10{1r(8 i=d;i<=e;i++)6(i!==7&&!(i>=f&&i<=g))4.L(i).1b(9(){h(j,4,i,c,b)})}},1B:9(i){z 4.1I(\'<1F></1F>\',i)},1I:9(e,i){8 a=$(e).V(4.K(\'C-1a\')).V(4.K(\'C-1a-\'+i));a.1J(\'2V\',i);z a},K:9(c){z c+\' \'+c+(!4.5.Z?\'-2U\':\'-Z\')},S:9(e,d){8 a=e.2g!=J?e[0]:e;8 b=!4.5.Z?a.1x+r.Y(a,\'2f\')+r.Y(a,\'1l\'):a.2e+r.Y(a,\'2d\')+r.Y(a,\'1N\');6(d==J||b==d)z b;8 w=!4.5.Z?d-r.Y(a,\'2f\')-r.Y(a,\'1l\'):d-r.Y(a,\'2d\')-r.Y(a,\'1N\');$(a).y(4.N,w+\'T\');z 4.S(a)},1m:9(){z!4.5.Z?4.H[0].1x-r.M(4.H.y(\'2T\'))-r.M(4.H.y(\'2S\')):4.H[0].2e-r.M(4.H.y(\'2R\'))-r.M(4.H.y(\'3i\'))},2P:9(i,s){6(s==J)s=4.5.u;z 1k.2O((((i-1)/s)-1k.2N((i-1)/s))*s)+1}});r.16({3m:9(d){z $.16(q,d||{})},Y:9(e,p){6(!e)z 0;8 a=e.2g!=J?e[0]:e;6(p==\'1l\'&&$.2A.28){8 b={\'1y\':\'1A\',\'2M\':\'2L\',\'1H\':\'1q\'},1Y,1W;$.29(a,b,9(){1Y=a.1x});b[\'1l\']=0;$.29(a,b,9(){1W=a.1x});z 1W-1Y}z r.M($.y(a,p))},M:9(v){v=2K(v);z 2J(v)?0:v}})})(3v);',62,218,'||||this|options|if|null|var|function||||||||||||||||||||list|size||||css|return|first|wrap|jcarousel|container|lt|false|last|clip|length|undefined|className|get|intval|wh|tail|div|locked|buttonPrev|dimension|px|buttonNext|addClass|inTail|prevFirst|margin|vertical|else|prev|callback|prevLast|animating|visible|extend|next|circular|parent|item|each|scroll|timer|split|buttons|jcarouselstate|true|animate|initCallback|Math|marginRight|clipping|while|hasClass|break|auto|for|pos|setup|bind|fn|disabled|offsetWidth|display|before|block|create|stopAuto|placeholder|removeClass|li|reloadCallback|width|format|attr|animation|buttonPrevCallback|notify|marginBottom|buttonNextCallback|ceil|buttonPrevHTML|typeof|buttonNextHTML|scrollTail|funcResize|remove|oWidth2|after|oWidth|both|old|offset|unbind|top|left|start|height|window|safari|swap|init|funcPrev|easing|marginTop|offsetHeight|marginLeft|jquery|object|onAfterAnimation|startAuto|buttonPrevEvent|click|buttonNextEvent|ol|ul|itemVisibleOutCallback|reload|prepend|itemVisibleInCallback|nodeName|add|itemLastOutCallback|skin|itemLastInCallback|indexOf|itemFirstOutCallback|browser|itemFirstInCallback|empty|reset|resize|itemLoadCallback|funcNext|prototype|load|isNaN|parseInt|none|float|floor|round|index|swing|borderTopWidth|borderRightWidth|borderLeftWidth|horizontal|jcarouselindex|isFunction|normal|clearTimeout|1000|setTimeout|onBeforeAnimation|children|push|Aborting|loop|infinite|an|cause|will|This|items|set|No|jCarousel|alert|class|find|borderBottomWidth|append|html|string|defaults|OL|UL|new|has|unlock|lock|10px|0px|jQuery'.split('|'),0,{}))
jQuery.url=function(){var segments={};var parsed={};var options={url:window.location,strictMode:false,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}};var parseUri=function(){str=decodeURI(options.url);var m=options.parser[options.strictMode?"strict":"loose"].exec(str);var uri={};var i=14;while(i--){uri[options.key[i]]=m[i]||""}uri[options.q.name]={};uri[options.key[12]].replace(options.q.parser,function($0,$1,$2){if($1){uri[options.q.name][$1]=$2}});return uri};var key=function(key){if(!parsed.length){setUp()}if(key=="base"){if(parsed.port!==null&&parsed.port!==""){return parsed.protocol+"://"+parsed.host+":"+parsed.port+"/"}else{return parsed.protocol+"://"+parsed.host+"/"}}return(parsed[key]==="")?null:parsed[key]};var param=function(item){if(!parsed.length){setUp()}return(parsed.queryKey[item]===null)?null:parsed.queryKey[item]};var setUp=function(){parsed=parseUri();getSegments()};var getSegments=function(){var p=parsed.path;segments=[];segments=parsed.path.length==1?{}:(p.charAt(p.length-1)=="/"?p.substring(1,p.length-1):path=p.substring(1)).split("/")};return{setMode:function(mode){strictMode=mode=="strict"?true:false;return this},setUrl:function(newUri){options.url=newUri===undefined?window.location:newUri;setUp();return this},segment:function(pos){if(!parsed.length){setUp()}if(pos===undefined){return segments.length}return(segments[pos]===""||segments[pos]===undefined)?null:segments[pos]},attr:key,param:param}}();
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
/**
 * jQuery Templates
 *
 * 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 <stanlemon@mac.com>
 *
 * Based off of the Ext.Template library, available at:
 * http://www.extjs.com
 *
 * This library provides basic templating functionality, allowing for macro-based
 * templates within jQuery.
 *
 * Basic Usage:
 *
 * var t = $.template('<div id="foo">Hello ${name}, how are you ${question}?  I am ${me:substr(0,10)}</div>');
 *
 * $(selector).append( t , {
 *     name: 'Stan',
 *     question: 'feeling',
 *     me: 'doing quite well myself, thank you very much!'
 * });
 *
 * Requires: jQuery 1.2+
 *
 *
 * @todo    Add callbacks to the DOM manipulation methods, so that events can be bound
 *          to template nodes after creation.
 */
(function($){

	/**
	 * Create a New Template
	 */
	$.template = function(html, options) {
		return new $.template.instance(html, options);
	};

	/**
	 * Template constructor - Creates a new template instance.
	 *
	 * @param 	html 	The string of HTML to be used for the template.
	 * @param 	options An object of configurable options.  Currently
	 * 			you can toggle compile as a boolean value and set a custom
	 *          template regular expression on the property regx by
	 *          specifying the key of the regx to use from the regx object.
	 */
	$.template.instance = function(html, options) {
        // If a custom regular expression has been set, grab it from the regx object
        if ( options && options['regx'] ) options.regx = this.regx[ options.regx ];

		this.options = $.extend({
			compile: 		false,
			regx:           this.regx.standard
		}, options || {});

		this.html = html;

		if (this.options.compile) {
			this.compile();
		}
		this.isTemplate = true;
	};

	/**
	 * Regular Expression for Finding Variables
	 *
	 * The default pattern looks for variables in JSP style, the form of: ${variable}
	 * There are also regular expressions available for ext-style variables and
	 * jTemplate style variables.
	 *
	 * You can add your own regular expressions for variable ussage by doing.
	 * $.extend({ $.template.re , {
	 *     myvartype: /...../g
	 * }
	 *
	 * Then when creating a template do:
	 * var t = $.template("<div>...</div>", { regx: 'myvartype' });
	 */
	$.template.regx = $.template.instance.prototype.regx = {
	    jsp:        /\$\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
        ext:        /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
        jtemplates: /\{\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}\}/g
	};

	/**
	 * Set the standard regular expression to be used.
	 */
	$.template.regx.standard = $.template.regx.jsp;

	/**
	 * Variable Helper Methods
	 *
	 * This is a collection of methods which can be used within the variable syntax, ie:
	 * ${variable:substr(0,30)} Which would only print a substring, 30 characters in length
	 * begining at the first character for the variable named "variable".
	 *
	 * A basic substring helper is provided as an example of how you can define helpers.
	 * To add more helpers simply do:
	 * $.extend( $.template.helpers , {
	 *	 sampleHelper: function() { ... }
	 * });
	 */
	$.template.helpers = $.template.instance.prototype.helpers = {
		substr : function(value, start, length){
			return String(value).substr(start, length);
		}
	};


	/**
	 * Template Instance Methods
	 */
	$.extend( $.template.instance.prototype, {

		/**
		 * Apply Values to a Template
		 *
		 * This is the macro-work horse of the library, it receives an object
		 * and the properties of that objects are assigned to the template, where
		 * the variables in the template represent keys within the object itself.
		 *
		 * @param 	values 	An object of properties mapped to template variables
		 */
		apply: function(values) {
			if (this.options.compile) {
				return this.compiled(values);
			} else {
				var tpl = this;
				var fm = this.helpers;

				var fn = function(m, name, format, args) {
					if (format) {
						if (format.substr(0, 5) == "this."){
							return tpl.call(format.substr(5), values[name], values);
						} else {
							if (args) {
								// quoted values are required for strings in compiled templates,
								// but for non compiled we need to strip them
								// quoted reversed for jsmin
								var re = /^\s*['"](.*)["']\s*$/;
								args = args.split(',');

								for(var i = 0, len = args.length; i < len; i++) {
									args[i] = args[i].replace(re, "$1");
								}
								args = [values[name]].concat(args);
							} else {
								args = [values[name]];
							}

							return fm[format].apply(fm, args);
						}
					} else {
						return values[name] !== undefined ? values[name] : "";
					}
				};

				return this.html.replace(this.options.regx, fn);
			}
		},

		/**
		 * Compile a template for speedier usage
		 */
		compile: function() {
			var sep = $.browser.mozilla ? "+" : ",";
			var fm = this.helpers;

			var fn = function(m, name, format, args){
				if (format) {
					args = args ? ',' + args : "";

					if (format.substr(0, 5) != "this.") {
						format = "fm." + format + '(';
					} else {
						format = 'this.call("'+ format.substr(5) + '", ';
						args = ", values";
					}
				} else {
					args= ''; format = "(values['" + name + "'] == undefined ? '' : ";
				}
				return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'";
			};

			var body;

			if ($.browser.mozilla) {
				body = "this.compiled = function(values){ return '" +
					   this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.options.regx, fn) +
						"';};";
			} else {
				body = ["this.compiled = function(values){ return ['"];
				body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.options.regx, fn));
				body.push("'].join('');};");
				body = body.join('');
			}
			eval(body);
			return this;
		}
	});


	/**
	 * Save a reference in this local scope to the original methods which we're
	 * going to overload.
	 **/
	var $_old = {
	    domManip: $.fn.domManip,
	    text: $.fn.text,
	    html: $.fn.html
	};

	/**
	 * Overwrite the domManip method so that we can use things like append() by passing a
	 * template object and macro parameters.
	 */
	$.fn.domManip = function( args, table, reverse, callback ) {
		if (args[0].isTemplate) {
			// Apply the template and it's arguments...
			args[0] = args[0].apply( args[1] );
			// Get rid of the arguements, we don't want to pass them on
			delete args[1];
		}

		// Call the original method
		var r = $_old.domManip.apply(this, arguments);

		return r;
	};

    /**
     * Overwrite the html() method
     */
	$.fn.html = function( value , o ) {
	    if (value && value.isTemplate) var value = value.apply( o );

		var r = $_old.html.apply(this, [value]);

		return r;
	};

	/**
	 * Overwrite the text() method
	 */
	$.fn.text = function( value , o ) {
	    if (value && value.isTemplate) var value = value.apply( o );

		var r = $_old.text.apply(this, [value]);

		return r;
	};

})(jQuery);

(function($){function toIntegersAtLease(n)
{return n<10?'0'+n:n;}
Date.prototype.toJSON=function(date)
{return this.getUTCFullYear()+'-'+
toIntegersAtLease(this.getUTCMonth())+'-'+
toIntegersAtLease(this.getUTCDate());};var escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};$.quoteString=function(string)
{if(escapeable.test(string))
{return'"'+string.replace(escapeable,function(a)
{var c=meta[a];if(typeof c==='string'){return c;}
c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
return'"'+string+'"';};$.toJSON=function(o,compact)
{var type=typeof(o);if(type=="undefined")
return"undefined";else if(type=="number"||type=="boolean")
return o+"";else if(o===null)
return"null";if(type=="string")
{return $.quoteString(o);}
if(type=="object"&&typeof o.toJSON=="function")
return o.toJSON(compact);if(type!="function"&&typeof(o.length)=="number")
{var ret=[];for(var i=0;i<o.length;i++){ret.push($.toJSON(o[i],compact));}
if(compact)
return"["+ret.join(",")+"]";else
return"["+ret.join(", ")+"]";}
if(type=="function"){throw new TypeError("Unable to convert object of type 'function' to json.");}
var ret=[];for(var k in o){var name;type=typeof(k);if(type=="number")
name='"'+k+'"';else if(type=="string")
name=$.quoteString(k);else
continue;var val=$.toJSON(o[k],compact);if(typeof(val)!="string"){continue;}
if(compact)
ret.push(name+":"+val);else
ret.push(name+": "+val);}
return"{"+ret.join(", ")+"}";};$.compactJSON=function(o)
{return $.toJSON(o,true);};$.evalJSON=function(src)
{return eval("("+src+")");};$.secureEvalJSON=function(src)
{var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
return eval("("+src+")");else
throw new SyntaxError("Error parsing JSON, source is not valid.");};})(jQuery);
(function($) {

$.ajaxSync = function(o) {
  var fn = $.ajaxSync.fn, data = $.ajaxSync.data, pos = fn.length;

  fn[ pos ] = {
    error: o.error,
    success: o.success,
    complete: o.complete,
    done: false
  };

  data[ pos ] = {};
  o.error = function() {
    data[ pos ].error = [{responseText: arguments[0].responseText, status: arguments[0].status}];
  };
  o.success = function() {
    data[ pos ].success = arguments;
  };
  o.complete = function() {
    data[ pos ].complete = arguments;
    fn[ pos ].done = true;
    if (pos == 0 || !fn[ pos - 1 ])
      for (var i = pos; i < fn.length && fn[i].done; i++) {
        if (fn[i].error && data[i].error) fn[i].error.apply(jQuery, data[i].error);
        if (fn[i].success && data[i].success) fn[i].success.apply(jQuery, data[i].success);
        if (fn[i].complete && data[i].complete) fn[i].complete.apply(jQuery, data[i].complete);

        fn[i] = null;
        data[i] = null;
      }
  };
  $.ajax(o);
};

$.discardPriorRequests = function() {
  var fn = $.ajaxSync.fn, pos = fn.length;
  for (var i = 0; i < pos; i++) {
    if (fn[i] && !fn[i].done) {
      fn[i] = {};

    }
  }
  $.ajaxSync.fn = [];
  $.ajaxSync.data = [];
}

$.ajaxSync.fn = [];
$.ajaxSync.data = [];

})(jQuery);
/**
 * DUI: The Digg User Interface Library
 *
 * Copyright (c) 2008-2009, Digg, Inc.
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice, 
 *   this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation 
 *   and/or other materials provided with the distribution.
 * - Neither the name of the Digg, Inc. nor the names of its contributors 
 *   may be used to endorse or promote products derived from this software 
 *   without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * @module DUI
 * @author Micah Snyder <micah@digg.com>
 * @description The Digg User Interface Library
 * @version 0.0.4
 * @link http://code.google.com/p/digg
 *
 */

/* Add Array.prototype.indexOf -- Guess which major browser doesn't support it natively yet? */
[].indexOf || (Array.prototype.indexOf = function(v, n){
    n = (n == null) ? 0 : n; var m = this.length;
    
    for(var i = n; i < m; i++) {
        if(this[i] == v) return i;
    }
    
    return -1;
});

(function($) {

/* Create our top-level namespace */
DUI = {
    version: "0.0.4"
};

/**
 * @class Class Class creation and management for use with jQuery. Class is a singleton that handles static and dynamic classes, as well as namespaces
 */
Class = {
    /**
     * @var {Array} _dontEnum Internal array of keys to omit when looking through a class' properties. Once the real DontEnum bit is writable we won't have to deal with this.
     */
    _dontEnum: ['_ident', '_dontEnum', 'create', 'namespace', 'ns', 'supers', 'sup', 'init', 'each'],
    
    /**
     * @function create Make a class! Do work son, do work
     * @param {optional Object} methods Any number of objects can be passed in as arguments to be added to the class upon creation
     * @param {optional Boolean} static If the last argument is Boolean, it will be treated as the static flag. Defaults to false (dynamic)
     */
    create: function() {
        //Set _this to DUI.Class
        var _this = this;
        
        //Figure out if we're creating a static or dynamic class
        var s = (arguments.length > 0 && //if we have arguments...
                arguments[arguments.length - 1].constructor == Boolean) ? //...and the last one is Boolean...
                    arguments[arguments.length - 1] : //...then it's the static flag...
                    false; //...otherwise default to a dynamic class
        
        //Static: Object, dynamic: Function
        var c = s ? {} : function() {
            this.init.apply(this, arguments);
        }
        
        //All of our classes have these in common
        var methods = {
            _ident: {
                library: "DUI.Class",
                version: "0.0.4",
                dynamic: true
            },
            
            //_dontEnum should exist in our classes as well
            _dontEnum: this._dontEnum,
            
            //A basic namespace container to pass objects through
            ns: [],
            
            //A container to hold one level of overwritten methods
            supers: {},
            
            //A constructor
            init: function() {},
            
            //Our namespace function
            namespace:function(ns) {
                //Don't add nothing
                if (!ns) return null;
                
                //Set _this to the current class, not the DUI.Class lib itself
                var _this = this;
                
                //Handle ['ns1', 'ns2'... 'nsN'] format
                if(ns.constructor == Array) {
                    //Call namespace normally for each array item...
                    $.each(ns, function() {
                        _this.namespace.apply(_this, [this]);
                    });
                    
                    //...then get out of this call to namespace
                    return;
                
                //Handle {'ns': contents} format
                } else if(ns.constructor == Object) {
                    //Loop through the object passed to namespace
                    for(var key in ns) {
                        //Only operate on Objects and Functions
                        if([Object, Function].indexOf(ns[key].constructor) > -1) {
                            //In case this.ns has been deleted
                            if(!this.ns) this.ns = [];
                            
                            //Copy the namespace into an array holder
                            this.ns[key] = ns[key];
                            
                            //Apply namespace, this will be caught by the ['ns1', 'ns2'... 'nsN'] format above
                            this.namespace.apply(this, [key]);
                        }
                    }
                    
                    //We're done with namespace for now
                    return;
                }
                
                //Note: [{'ns': contents}, {'ns2': contents2}... {'nsN': contentsN}] is inherently handled by the above two cases
                
                var levels = ns.split(".");
                
                /* Dynamic classes are Functions, so we'll extend their prototype.
                   Static classes are Objects, so we'll extend them directly */
                var nsobj = this.prototype ? this.prototype : this;
                
                $.each(levels, function() {
                    /* When adding a namespace check to see, in order:
                     * 1) Does the ns exist in our ns passthrough object?
                     * 2) Does the ns already exist in our class
                     * 3) Does the ns exist as a global var?
                     *    NOTE: Support for this was added so that you can namespace classes
                     *    into other classes, i.e. MyContainer.namespace('MyUtilClass'). this
                     *    behaviour is dangerously greedy though, so it may be removed.
                     * 4) If none of the above, make a new static class
                     */
                    nsobj[this] = _this.ns[this] || nsobj[this] || window[this] || DUI.Class.create(true);
                    
                    /* If our parent and child are both dynamic classes, copy the child out of Parent.prototype and into Parent.
                     * It seems weird at first, but this allows you to instantiate a dynamic sub-class without instantiating
                     * its parent, e.g. var baz = new Foo.Bar();
                     */
                    if(_this.prototype && DUI.isClass(nsobj[this]) && nsobj[this].prototype) {
                        _this[this] = nsobj[this];
                    }
                    
                    //Remove our temp passthrough if it exists
                    delete _this.ns[this];
                    
                    //Move one level deeper for the next iteration
                     nsobj = nsobj[this];
                });
                
                //TODO: Do we really need to return this? It's not that useful anymore
                return nsobj;
            },
            
            /* Create exists inside classes too. neat huh?
             * Usage differs slightly: MyClass.create('MySubClass', { myMethod: function() }); */
            create: function() {
                //Turn arguments into a regular Array
                var args = Array.prototype.slice.call(arguments);
                
                //Pull the name of the new class out
                var name = args.shift();
                
                //Create a new class with the rest of the arguments
                var temp = DUI.Class.create.apply(DUI.Class, args);
                
                //Load our new class into the {name: class} format to pass it into namespace()
                var ns = {};
                ns[name] = temp;
                
                //Put the new class into the current one
                this.namespace(ns);
            },
            
            //Iterate over a class' members, omitting built-ins
            each: function(cb) {
                if(!$.isFunction(cb)) {
                    throw new Error('DUI.Class.each must be called with a function as its first argument.');
                }
                
                //Set _this to the current class, not the DUI.Class lib itself
                var _this = this;
                
                $.each(this, function(key) {
                    if(_this._dontEnum.indexOf(key) != -1) return;
                    
                    cb.apply(this, [key, this]);
                });
            },
            
            //Call the super of a method
            sup: function() {
                try {
                    var caller = this.sup.caller.name;
                    this.supers[caller].apply(this, arguments);
                } catch(noSuper) {
                    return false;
                }
            }
        }
        
        //Static classes don't need a constructor
        s ? delete methods.init : null;
        
        //...nor should they be identified as dynamic classes
        s ? methods._ident.dynamic = false : null;
        
        /* Put default methods into the class before anything else,
         *   so that they'll be overwritten by the user-specified ones */
        $.extend(c, methods);
        
        /* Second copy of methods for dynamic classes: They get our 
         * common utils in their class definition AND their prototype */
        if(!s) $.extend(c.prototype, methods);
        
        //Static: extend the Object, Dynamic: extend the prototype
        var extendee = s ? c : c.prototype;
        
        //Loop through arguments. If they're the right type, tack them on
        $.each(arguments, function() {
            //Either we're passing in an object full of methods, or the prototype of an existing class
            if(this.constructor == Object || typeof this.init != undefined) {
                /* Here we're going per-property instead of doing $.extend(extendee, this) so that
                 * we overwrite each property instead of the whole namespace. Also: we omit the 'namespace'
                 * helper method that DUI.Class tacks on, as there's no point in storing it as a super */
                for(i in this) {
                    /* If a property is a function (other than our built-in helpers) and it already exists
                     * in the class, save it as a super. note that this only saves the last occurrence */
                    if($.isFunction(extendee[i]) && _this._dontEnum.indexOf(i) == -1) {
                        //since Function.name is almost never set for us, do it manually
                        this[i].name = extendee[i].name = i;
                        
                        //throw the existing function into this.supers before it's overwritten
                        extendee.supers[i] = extendee[i];
                    }
                    
                    //Special case! If 'dontEnum' is passed in as an array, add its contents to DUI.Class._dontEnum
                    if(i == 'dontEnum' && this[i].constructor == Array) {
                        extendee._dontEnum = $.merge(extendee._dontEnum, this[i]);
                    }
                    
                    //extend the current property into our class
                    extendee[i] = this[i];
                }
            }
        });
        
        //Shiny new class, ready to go
        return c;
    }
};

})(jQuery);

//Simple check so see if the object passed in is a DUI Class
isClass = function(check, type)
{
    type = type || false;
    
    try {
        if(check._ident.library == 'DUI.Class') {
            if((type == 'dynamic' && !check._ident.dynamic)
               || (type == 'static' && check._ident.dynamic)) {
                return false;
            }
            
            return true;
        }
    } catch(noIdentUhOh) {
        return false;
    }
    
    return false;
}

// Observer intializer

function attachRUJSObservers() {
  ButtonObserver.attachAllObservers();
  LinkObserver.attachAllObservers();
  FormObserver.attachAllObservers();
}
// Observer intializer

function attachAllObservers() {
  DialogObserver.attachAllObservers();
  ButtonObserver.attachAllObservers();
  LinkObserver.attachAllObservers();
  FormObserver.attachAllObservers();
  SchedulerObserver.attachAllObservers();
  UIObserver.attachAllObservers();
  CarouselObserver.attachAllObservers();
  SchedulerValidationObserver.attachAllObservers();
  ElementObserver.attachAllObservers();
  OmnitureObserver.attachAllObservers();
  LoginObserver.attachAllObservers();
  LeadObserver.attachAllObservers();
  SearsVerticalObserver.attachAllObservers();
  ProtectionAgreementInvoiceObserver.attachAllObservers();
  ReCaptchaObserver.attachAllObservers();
  OrderConfirmationObserver.attachAllObservers();
  CarryInObserver.attachAllObservers();
}

$(document).ready(function() {
  attachAllObservers();
});
// Easily specify all IEs
function isIE() {
  var ie = false;
  if($.browser.msie) {
    ie = true;
  }
  return ie;
}

// Easily specify IE6
function isIE6() {
  var ie6 = false;
  if($.browser.msie) {
    if($.browser.version == '6.0') {
      ie6 = true;
    }
  }
  return ie6;
}


// Easily specify IE7
function isIE7() {
  var ie7 = false;
  if($.browser.msie) {
    if($.browser.version == '7.0') {
      ie7 = true;
    }
  }
  return ie7;
}

// ArrayIndexOf
// Not really a function, but it creates a method on Array. It's close enough
// (Required for Class.js)
if(isIE()) {
  if(!Array.indexOf) {
    Array.prototype.indexOf = function(obj){
      for(var i=0; i<this.length; i++){
        if(this[i]==obj){
          return i;
        }
      }
      return -1;
    }
  }
}

// Create classes from input types for IE6
if(isIE6()) {
  function addInputTypeAsClass() {
    $('input').each(function(){
      $(this).addClass($(this).attr('type'));
    });
  }

  $(document).ready(function() {
    addInputTypeAsClass();
  });
}

// function to unify a debugging display

function trace(msg){
  if (typeof Debug!='undefined') {
    new Debug().error(msg);
  }
}

//show object internals
function showStuff(obj) {
  var guts=new Array();
  for(var property in obj){
    guts.push(property + ':' + obj[property]);
  }
  return guts;
}


function getNumericValue(strValue){
  return parseInt(strValue.replace('px',''));
}
function bindAjaxActionCall(buttonId, urlBuilder, inputId, resultsId,callBack) {
  var button = $(buttonId);

  button.bind('click', invokeAction(urlBuilder, inputId, resultsId, buttonId, callBack));
  button.parents('form').bind('submit', function() {
    invokeAction(urlBuilder, inputId, resultsId);
    return false;
  });

}

function invokeAction(urlBuilder, inputId, resultsId, buttonId, callBack) {

  return function() {
    var term = $(inputId).attr('value');
    var title = $(inputId).attr('title');
    if(term != title) {
      $(inputId).addClass('ajax_loading');

      if(!($(buttonId).hasClass('go_disabled'))){
        $.ajax({
          type: "GET",
          url: urlBuilder.build(term),
          success: function(response) {
            $(resultsId).html(response);
            $(buttonId).removeClass('go_disabled');
            $(inputId).removeClass('ajax_loading');
            if(typeof callBack != 'undefined') {
              var resultsCount = $(resultsId).find('ul').length;
              callBack(resultsCount);

            }
          }
        });
      }
      $(buttonId).addClass('go_disabled');

    } else {
      $(inputId).focus();
    }
    return false;
  }

}
var OmniturePageName;
var OmnitureCall = {

  //Omniture Events Reporting - start
  reportSchedulerOpen: function() {
    var zip = 'BLANK';
    var category = 'BLANK';
    var productname = 'BLANK';
    s.linkTrackVars = 'prop3,prop4,prop6,prop7,prop8,prop12,events,channel';
    s.linkTrackEvents = 'scOpen';
    s.events = 'scOpen';
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.prop4 = 'Step 1';
    s.prop6 = zip;
    s.prop7 = [category,productname].join(': ');
    s.prop8 = [zip, category, productname].join(': ');
    s.prop12 = 'Scheduler';
    s.channel = OmnitureReport.pageInformation.channel;
    s.tl(true, 'o', 'Scheduler Open');
    OmnitureReport.clearEventsAndEvars();
  },

  reportChannelOnSchedulerOpen: function() {
    s.channel = OmnitureReport.pageInformation.channel;
  },

  reportSchedulerComplete: function(productid, orderid) {
    s.linkTrackVars = 'products,prop3,prop4,events';
    s.linkTrackEvents = 'event2';
    if (orderid == '') {
      s.events = 'event2';
    } else {
      s.events = 'event2' + ":" + orderid;
    }

    s.products = ';' + productid;
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.prop4 = 'Scheduler Confirmation',
    s.tl(true, 'o', 'Scheduler Complete');
    OmnitureReport.clearEventsAndEvars();
  },

  reportCIRSchedulerComplete: function(productid, orderid) {
    s.linkTrackVars = 'products,prop3,events';
    s.linkTrackEvents = 'event2' + ":" + orderid;
    s.events = 'event2';
    s.products = ';' + productid;
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.tl(true, 'o', 'Carry In Repair: Scheduler Complete');
    OmnitureReport.clearEventsAndEvars();
  },

  reportNullSearchServices: function() {
    new OmnitureReport({
      events:'event3'
    });
  },

  reportNullSearchAnswers: function() {
    new OmnitureReport({
      events:'event4'
    });
  },

  reportClickToChatUsage: function() {
    s.linkTrackVars = 'prop3,eVar14,events';
    s.linkTrackEvents = 'event6';
    s.events = 'event6';
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.eVar14 = "chat: " + OmnitureReport.pageInformation.pageName;
    s.tl(true, 'o', 'Click To Chat');
    OmnitureReport.clearEventsAndEvars();
  },

  reportRegisterSuccess:function() {
    s.linkTrackVars = 'prop3,events';
    s.linkTrackEvents = 'event9';
    s.events = 'event9';
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.tl(true, 'o', 'Registration Success');
    OmnitureReport.clearEventsAndEvars();
  },

  reportLoginSuccess:function() {
    s.linkTrackVars = 'prop3,events';
    s.linkTrackEvents = 'event11';
    s.events = 'event11';
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.tl(true, 'o', 'Login Success');
    OmnitureReport.clearEventsAndEvars();
  },

  reportProfileUpdate:function(omnitureParameters) {
    new OmnitureReport({
      events:'event12',
      prop20: omnitureParameters['prop20'],
      prop21: omnitureParameters['prop21']
    });
  },

  reportPaThankYouPageLoad:function() {
    new OmnitureReport({
      events:'event13'
    });
  },

  reportPaPurchaseFormLoad:function() {
    new OmnitureReport({
      events:'event14'
    });
  },

  reportSuccessfulOrderLookup: function() {
    s.linkTrackVars = 'prop3,events';
    s.linkTrackEvents = 'event15';
    s.events = 'event15';
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.tl(true, 'o', 'Order Lookup Successful');
    OmnitureReport.clearEventsAndEvars();
  },

  reportRescheduleAttempt: function() {
    s.linkTrackVars = 'prop3,events';
    s.linkTrackEvents = 'event16';
    s.events = 'event16';
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.tl(true, 'o', 'Reschedule Attempt');
    OmnitureReport.clearEventsAndEvars();
  },

  reportCancelEvent: function(event, cancellation_message) {
    s.linkTrackVars = 'events,prop3,prop28';
    s.linkTrackEvents = 'event27,event28';
    s.events = event;
    s.prop28 = cancellation_message;
    s.prop3 = OmnitureReport.pageInformation.pageName;
    var link_description = (event == 'event27') ? 'CancelY' : 'CancelN';
    s.tl(true, 'o', link_description);
    OmnitureReport.clearEventsAndEvars();
  },

  reportCancelSubmitReasonEvent: function(reason) {
    s.linkTrackVars = 'prop3,prop29';
    s.prop29 = reason;
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.tl(true, 'o', "cancellation reason");
    OmnitureReport.clearEventsAndEvars();
  },
  //Omniture Events Reporting - end

  //Omniture Page Reporting - start

  reportHomePage: function(pageName) {
    new OmnitureReport({
      pageName:pageName,
      channel:pageName,
      prop1: pageName,
      prop2:pageName
    });
    OmnitureReport.pageInformation = new OmniturePageInformation(pageName, pageName, pageName, 'Home');
  },

  reportProfilePage: function(pageName) {
    new OmnitureReport({
      pageName:pageName,
      channel:pageName,
      prop1: pageName,
      prop2:pageName
    });
    OmnitureReport.pageInformation = new OmniturePageInformation(pageName, pageName, pageName, 'User Profile');
  },

  reportServiceLandingPage: function(category) {
    new OmnitureReport({
      pageName: category,
      channel: category,
      prop1:category,
      prop2:'Department'
    });
    OmnitureReport.pageInformation = new OmniturePageInformation(category, category, category, 'Category');
  },

  getHIProductPageParameters : function(category, productName) {
    return{
      pageName: productName,
      channel: category,
      prop1: productName,
      prop2: 'Product Detail'
    }
  },

  getHIProductDetailPageParameters : function(category, productName, tabName) {
    var self = this;
    return jQuery.extend(self.getHIProductPageParameters(category, productName),{
      prop37: tabName,
      eVar28: productName + ": " + tabName
    });
  },

  reportHIProductDetailPage: function(category, productName, tabName) {
    var self = this;
    new OmnitureReport(self.getHIProductDetailPageParameters(category, productName, tabName));
  },

  reportProductDetailPage: function(category, productname) {
    new OmnitureReport({
      pageName: category + ' :' + productname + ' :PDP',
      channel: category,
      prop1: productname,
      prop2:'Product Detail'
    });
    OmnitureReport.pageInformation = new OmniturePageInformation(category + ' :' + productname + ':PDP', category, productname, 'Product Detail');
  },

  reportOrderSearchPage: function(serviceName, orderLookupType) {
    new OmnitureReport({
      pageName:serviceName + ' order search',
      channel:serviceName + ' order search',
      prop1:serviceName + ' order search',
      prop2:'Category',
      eVar7: orderLookupType
    });
    OmnitureReport.pageInformation = new OmniturePageInformation(serviceName + ' order search', serviceName + ' order search',
            serviceName + ' order search', 'Category');
  },

  reportAnswersPage: function(searchTerm) {
    new OmnitureReport({
      pageName:'Search Results > Expert answers',
      channel:'Answers search results',
      prop1:'Search Results > Expert answers',
      prop2:'Category',
      prop9:searchTerm
    });
    OmnitureReport.pageInformation = new OmniturePageInformation('Search Results > Expert answers', 'Answers search results',
            'Search Results > Expert answers', 'Category');
  },

  reportMarketingPage: function(promoHeading) {
    new OmnitureReport({
      pageName: promoHeading + ' Marketing Landing Page',
      channel: promoHeading + ' Marketing Landing Page',
      prop1: promoHeading + ' Marketing Landing Page',
      prop2:'Category'
    });
    OmnitureReport.pageInformation = new OmniturePageInformation(promoHeading + ' Marketing Landing Page', promoHeading + ' Marketing Landing Page',
            promoHeading + ' Marketing Landing Page', 'Category');
  },

  reportOrderCancelConfirmationPage: function(serviceName) {
    new OmnitureReport({
      pageName:serviceName + ' order cancellation',
      channel:serviceName + ' order cancellation',
      prop1:serviceName + ' order cancellation',
      prop2:'Category',
      events: 'event30',
      eVar16: serviceName
    });
    OmnitureReport.pageInformation = new OmniturePageInformation(serviceName + ' order cancellation', serviceName + ' order cancellation',
            serviceName + ' order cancellation', 'Category');
  },

  reportOrderCancelErrorPage: function(serviceName) {
    new OmnitureReport({
      pageName:serviceName + ' order cancellation',
      channel:serviceName + ' order cancellation',
      prop1:serviceName + ' order cancellation',
      prop2:'Category'
    });
    OmnitureReport.pageInformation = new OmniturePageInformation(serviceName + ' order cancellation', serviceName + ' order cancellation',
            serviceName + ' order cancellation', 'Category');
  },

  reportOrderRescheduleConfirmationPage: function(serviceName) {
    new OmnitureReport({
      pageName:serviceName + ' order reschedule',
      channel:serviceName + ' order reschedule',
      prop1:serviceName + ' order reschedule',
      prop2:'Category',
      events: "event31"
    });
    OmnitureReport.pageInformation = new OmniturePageInformation(serviceName + ' order reschedule', serviceName + ' order reschedule',
            serviceName + ' order reschedule', 'Category');
  },

  reportOrderStatusPage: function(serviceName) {
    new OmnitureReport({
      pageName:serviceName + ' order status',
      channel:serviceName + ' order status',
      prop1:serviceName + ' order status',
      prop2:'Category'
    });
    OmnitureReport.pageInformation = new OmniturePageInformation(serviceName + ' order status', serviceName + ' order status', 'Category');
  },

  reportShipOrderConfirmationPage: function(serviceName) {
    new OmnitureReport({
      pageName:serviceName + ' order confirmation',
      channel:serviceName + ' order confirmation',
      prop1:serviceName + ' order confirmation',
      prop2: 'Category'
    });
    OmnitureReport.pageInformation = new OmniturePageInformation(serviceName + ' order confirmation', serviceName + ' order confirmation',
            serviceName + ' order confirmation', 'Category');
  },

  reportSearchPage: function(searchTerm) {
    new OmnitureReport({
      pageName:'Search Results > Search Results',
      channel:'Search',
      prop9:searchTerm
    });
    OmnitureReport.pageInformation = new OmniturePageInformation(OmnitureReport.pageInformation.getPageNameForSearch(), "Search",
            OmnitureReport.pageInformation.getCategoryForSearchPages(), OmnitureReport.pageInformation.pageType);
  },

  reportPageNotFound: function(url) {
    new OmnitureReport({
      pageName: '404:' + url,
      channel: '404:' + url,
      prop1:'errorpage',
      prop2:'Error Page'
    });
    OmnitureReport.pageInformation = new OmniturePageInformation('404:' + url, '404:' + url, 'errorpage', 'Error Page');
  },

  reportLoginPage: function() {
    new OmnitureReport({
      pageName: 'Login',
      channel: 'Login',
      prop1:'SHS: Login',
      prop2:'Login Page'
    });
    OmnitureReport.pageInformation = new OmniturePageInformation('Login', 'Login', 'SHS: Login', 'Login Page');
  },

  reportRegistrationPage: function() {
    new OmnitureReport({
      pageName: 'Registration',
      channel: 'Registration',
      prop1:'SHS: Registration',
      prop2:'Registration Page'
    });
    OmnitureReport.pageInformation = new OmniturePageInformation('Registration', 'Registration', 'SHS: Registration', 'Registration Page');
  },

  //Omniture Page Reporting - end

  reportSchedulerMacroView: function(step, zip, category, productname, first_available_date, selected_date) {
    zip = zip || 'BLANK';
    category = category || 'BLANK';
    productname = productname || 'BLANK';
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.prop6 = zip;
    s.prop7 = [category,productname].join(': ');
    s.prop8 = [zip, category, productname].join(': ');

    if (step == 'Step 1') {
      this.reportStepOne(category, productname);
    } else if (step == 'Step 2') {
      if (SchedulerObserver.scheduler.order.isCarryInProduct()) {
        this.reportStepTwoForCarryIn();
      } else {
        this.reportStepTwo(first_available_date, selected_date);
      }
    }
  },

  reportStepOne: function(category, productname) {
    var productid = $.cookie("cancel_retarget_merchandise_code");
    var price = $('#priceForOmnitureTracking').val();
    var range = (price > 0) ? ((Math.floor(price / 100) * 100) + 1) + "-" + (Math.floor(price / 100) + 1) * 100 : "0";

    productid = productid || $('#product').val();
    s.linkTrackVars = 'prop3,prop4,prop6,prop7,prop8,prop23,prop24,events,products,eVar11,eVar18';

    var carryInOmnitureCodes = this.collectCarryInNOPCodes();

    if (carryInOmnitureCodes != null) {
      s.eVar18 = carryInOmnitureCodes;
    }
    s.linkTrackEvents = 'event17';
    s.products = ';' + productid;
    s.events = 'event17';
    s.prop23 = category;
    s.prop4 = 'Step 2';
    s.eVar11 = range;

    s.prop24 = productname;
    s.tl(true, 'o', 'Step 2');
    OmnitureReport.clearEventsAndEvars();
  },

  collectCarryInNOPCodes: function() {
    var fieldset = $('#problem_description').children('.select_flyout_option');
    if (fieldset == null || fieldset == 'undefined') {
      return null;
    }
    var problems = new Array();
    var i = 0;
    $(fieldset).each(function() {
      var checkBox = $(this).children('input');
      if (checkBox.attr('checked') == true) {
        problems[i++] = checkBox.val().split('|')[1];
      }
    });
    return problems.join('|');
  },

  reportStepTwo: function(first_date, selected_date) {
    var selectedDate = $.datepicker.parseDate('D, MM d, yy', selected_date);
    var firstAvaiableDate = $.datepicker.parseDate('yy-mm-dd', first_date);
    var currentDate = $.datepicker.parseDate('yy-mm-dd', $.datepicker.formatDate('yy-mm-dd', new Date()));
    var daysOut = (firstAvaiableDate.valueOf() - currentDate.valueOf()) / (1000 * 60 * 60 * 24);
    s.linkTrackVars = 'prop3,prop4,prop5,prop6,prop7,prop8,prop25,prop26,prop27,events';
    s.linkTrackEvents = 'event18';
    s.events = 'event18';
    if ($('#time_slots').attr('title') != $('#time_slots').val()) s.prop5 = "time";
    s.prop25 = $.datepicker.formatDate('M d yy', firstAvaiableDate);
    s.prop26 = $.datepicker.formatDate('M d yy', selectedDate);
    s.prop27 = daysOut;
    s.prop4 = 'Step 3';
    s.tl(true, 'o', 'Step 3');
    OmnitureReport.clearEventsAndEvars();
  },

  reportStepTwoForCarryIn: function() {
    s.linkTrackVars = 'eVar19,events';
    s.linkTrackEvents = 'event17';
    s.events = 'event17';
    var storeId = $("#schedulerInformation_storeNumber").val();
    if (storeId != null && storeId != 'undefined') {
      s.eVar19 = storeId;
    }
    s.tl(true, 'o', 'Carry In Repair: Step 2');
    OmnitureReport.clearEventsAndEvars();
  },

  reportServiceDown: function() {
    var category = $("#service").val() || '';
    var productname = SchedulerService.productNameForService($("#service :selected").val()) || '';
    var zip = $("#zip_code").val() || '';
    s.linkTrackVars = 'prop3,prop18';
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.prop18 = [zip, category, productname].join(': ');
    s.tl(true, 'o', 'No Service');
    OmnitureReport.clearEventsAndEvars();
  },

  reportSchedulerMicroView: function(field, zip, category, productname, state) {
    zip = zip || 'BLANK';
    category = category || 'BLANK';
    productname = productname || 'BLANK';
    s.linkTrackVars = 'prop3,prop5,prop6,prop7,prop8,channel,state';
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.prop5 = field;
    s.prop6 = zip;
    s.prop7 = [category,productname].join(': ');
    s.prop8 = [zip, category, productname].join(': ');
    if (field == 'state') {
      s.state = state;
    }
    s.tl(true, 'o', 'Scheduler Micro View');
    OmnitureReport.clearEventsAndEvars();
  },

  reportPartsDirect:function(obj) {
    s.linkTrackVars = 'prop3,prop17';
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.prop17 = 'Need a Part';
    var lt = (obj.href != null) ? s.lt(obj.href) : '';
    if (lt == '') {
      s.tl(obj, 'e', 'Parts Direct');
      OmnitureReport.clearEventsAndEvars();
    }
  },

  reportSchedulerStart:function() {
    s.linkTrackVars = 'prop3,events';
    s.linkTrackEvents = 'event1';
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.events = "event1";
    s.tl(true, 'o', 'Scheduler Start');
    OmnitureReport.clearEventsAndEvars();
  },

  reportManageMyHome:function(obj) {
    s.linkTrackVars = 'prop3,prop17';
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.prop17 = 'Find a Manual';
    var lt = (obj.href != null) ? s.lt(obj.href) : '';
    if (lt == '') {
      s.tl(obj, 'e', 'Manage My Home');
      OmnitureReport.clearEventsAndEvars();
    }
  },

  reportAjaxToolUsage:function(tool) {
    s.linkTrackVars = 'prop3,prop12';
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.prop12 = tool;
    s.tl(true, 'o', 'Tool Usage');
    OmnitureReport.clearEventsAndEvars();
  },

  reportToolUsage:function(tool) {
    var properties = {prop12: tool};
    if (tool == 'click to call') {
      properties = {prop12: tool, events: 'event29', eVar15: "ctc: " + OmnitureReport.pageInformation.pageName};
    }
    new OmnitureReport(properties);
  },

  reportServiceFinding:function(findingMethod) {
    new OmnitureReport({
      eVar1:findingMethod
    });
  },

  reportAnswerShowMore:function(question) {
    s.linkTrackVars = 'prop3,prop12,prop15';
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.prop15 = question;
    s.prop12 = 'Read Answer';
    s.tl(true, 'o', 'Show More / Read Answer');
    OmnitureReport.clearEventsAndEvars();
  },

  reportVisitorProfile: function(state, zip) {
    new OmnitureReport({
      state: state,
      zip: zip
    });
  },

  reportServicesSearch: function(count) {
    var prop10Value = (count == 0) ? 'Zero' : count;
    new OmnitureReport({
      prop10:prop10Value
    });
  },

  reportAnswersSearch: function(count) {
    var prop11Value = (count == 0) ? 'Zero' : count;
    new OmnitureReport({
      prop11:prop11Value
    });
  },

  reportBlueCrewAnswersSearch: function(blueCrewSearchTerm) {
    s.linkTrackVars = 'prop3,prop13';
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.prop13 = blueCrewSearchTerm;
    s.tl(true, 'o', 'Blue Crew Search Term on Go Button');
    OmnitureReport.clearEventsAndEvars();
  },

  reportBlueCrewViewAllAnswers:function(expertAnswersSearchTerm) {
    s.linkTrackVars = 'prop3,prop16';
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.prop16 = expertAnswersSearchTerm;
    s.tl(true, 'o', 'Blue Crew Search Term on View All+');
    OmnitureReport.clearEventsAndEvars();
  },

  reportBlueCrewNumberOfSearchResults: function (count) {
    var prop14Value = (count == 0) ? 'Zero' : count;
    s.linkTrackVars = 'prop3,prop14';
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.prop14 = prop14Value;
    s.tl(true, 'o', 'Blue Crew Search Results Count');
    OmnitureReport.clearEventsAndEvars();
  },

  reportHITabsDisplay: function(tabName) {
    s.linkTrackVars = 'prop29,eVar17';
    s.prop29 = tabName;
    s.eVar17 = tabName;
    s.tl(true, 'o', 'tabs');
    OmnitureReport.clearEventsAndEvars();
  },

  getHIPageParameters : function(pageName) {
    return{
      pageName: pageName,
      channel: pageName,
      prop1: pageName,
      prop2: pageName
    }
  },

  getHILandingPageParameters : function(pageName) {
    var self = this;
    return jQuery.extend(self.getHIPageParameters(pageName),
    {eVar27:"improvements"})
  },

  getHISearchLandingPageParameters : function(pageName) {
    var self = this;
    return jQuery.extend(self.getHILandingPageParameters(pageName),
    {campaign:"search"})
  },

  reportLandingPage:function(pageName) {
    var self = this;
    new OmnitureReport(self.getHIPageParameters(pageName))
  },

  reportHILandingPage: function(pageName) {
    var self = this;
    new OmnitureReport(self.getHILandingPageParameters(pageName))
  },

  reportHISearchLandingPage: function(pageName) {
    var self = this;
    new OmnitureReport(self.getHISearchLandingPageParameters(pageName))
  },

  reportCIRConfirmationPage: function(pageName) {
    new OmnitureReport({
      pageName: pageName,
      channel: pageName,
      prop1: 'SHS: CIR Confirmation Page',
      prop2: 'Confirmation Page'
    });
    OmnitureReport.pageInformation = new OmniturePageInformation(pageName, pageName, 'SHS: CIR Confirmation Page', 'Confirmation Page');
  }
  ,

  reportLeadStep: function(pageName) {
    s.linkTrackVars = 'pageName';
    s.linkTrackEvents = '';
    s.events = '';
    s.products = '';
    s.pageName = pageName;
    s.t(this, 'o', 'leadForms');
    OmnitureReport.clearEventsAndEvars();
  }
  ,

  reportCIRViewMoreLocations: function() {
    s.linkTrackVars = 'prop3,events';
    s.linkTrackEvents = 'event19';
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.events = "event19";
    s.tl(true, 'o', 'Carry In Repair: View More Locations');
    OmnitureReport.clearEventsAndEvars();
  }
  ,

  reportCIRSaveLocation: function(storeID) {

    s.linkTrackVars = 'prop3,events,eVar19';
    s.linkTrackEvents = 'event20';
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.events = "event20";
    s.eVar19 = storeID;
    s.tl(true, 'o', 'Carry In Repair: Save Location');
    OmnitureReport.clearEventsAndEvars();
  }
  ,

  reportCIRPrintForm: function() {
    s.linkTrackVars = 'prop3,events';
    s.linkTrackEvents = 'event23';
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.events = "event23";
    s.tl(true, 'o', 'Carry In Repair: Print Form');
    OmnitureReport.clearEventsAndEvars();
  }
  ,

  reportCIRCouponPrintForm: function() {
    s.linkTrackVars = 'prop3,events';
    s.linkTrackEvents = 'event22';
    s.prop3 = OmnitureReport.pageInformation.pageName;
    s.events = "event22";
    s.tl(true, 'o', 'Carry In Repair: Coupon Print Form');
    OmnitureReport.clearEventsAndEvars();
  }
}

var OmniturePageName;
var OmnitureCallSearsVertical = {
  delay : 1000,
  reportProductDetailPage: function(category, productname,productGroupName) {
    var productId =category.toUpperCase() + " " + productGroupName;
    OmnitureReportSears.pageInformation = new OmniturePageInformation(category + " :" + productname, productname, 'Product Detail');
    var productPageName = category + " :" + productname + " :PDP";
    new OmnitureReportSears({
      pageName:productPageName,
      channel:"Home Services",
      prop1:category,
      prop2:productname,
      events:"prodView,event10",
      products:";" + productId + ";;;;evar41=Home Services|evar42=SHS:" + category
    });

 setTimeout( function() {
	 new OmnitureReport({
	        pageName: productPageName,
	        channel: category,
	        prop1:productname,
	        prop2:"Product Detail",
	        events:"prodView,event10",
	        products:";"+productId
	      });
    }, this.delay    );

  },


  reportCategoryPage:  function(category) {
	  OmnitureCall.reportServiceLandingPage(category);
	  var that = this;
	  setTimeout(function() {
	    	that._reportCategoryPage(category);
	    	},this.delay )  ;
  },

  _reportCategoryPage: function(category) {
    OmnitureReportSears.pageInformation = new OmniturePageInformation(category,category,"Category Page");
    new OmnitureReportSears({
      pageName:category,
      prop1:category,
      prop2:category,
      channel:"Home Services"
    });
  },

  reportHomePage: function(category) {
    OmnitureCall.reportHomePage("SHS: " + category);
    var that = this;
    setTimeout(function() {
    	that._reportCategoryPage(category);
    	},this.delay )  ;
  },

  reportAddToCart:function(products) {
	  var s=s_gi(sears_account);
	  s.linkTrackVars='products,events';
	  s.linkTrackEvents='scAdd';
	  s.events='scAdd';
	  s.products=products;
	  s.tl(this,'o','Add to Cart');
	  ;;
  }
};
var OmnitureCancelRetarget = {
  setRetargetLandingPageUrlCookiesIfRetargetLandingPage :function () {

    var sid = s.getQueryParam('productid');
    if (sid != null) {
        $.cookie("cancel_retarget_merchandise_code", sid, {path:"/"});
        $.cookie("cancel_retarget_navigation_flag", "true", {path:"/"});
    }
  },

  reportNavigationFromRetargetLandingPage: function() {
    var navigationFlagCookie = $.cookie('cancel_retarget_navigation_flag');
    if (navigationFlagCookie == 'true') {
      $.cookie('cancel_retarget_navigation_flag', null, {path:'/'});
    }
  }
}
var MP = {
  // mp_trans_disable_start
  Version: '1.0.15',
  Domains: {'es':'espanol.searshomeservices.com'},			
	SrcLang: 'en',
	
  // mp_trans_disable_end 
	UrlLang: 'mp_js_current_lang',
	SrcUrl: unescape('mp_js_orgin_url'),
	
  // mp_trans_disable_start
	init: function() {
    if (MP.SrcUrl.indexOf('p_js_') == 1) {
      MP.SrcUrl = location.href;
      MP.UrlLang = MP.SrcLang;
    }
	},
	
  switchLanguage: function(lang) {
	  if (lang != MP.SrcLang) {
      var script = document.createElement('SCRIPT');
      script.src = location.protocol+'//' + MP.Domains[lang] + '/en' + lang + '/?1023749632;' + escape(MP.SrcUrl);
      document.body.appendChild(script);
    } else if (lang == MP.SrcLang) {
  	  MP.switchToLang(MP.SrcUrl);		
	  }
	  
	  return false;
  },
  
	switchToLang: function(url) {
    var mplink = document.createElement('A');
		if (mplink.click) { 
		  // using location.href will cause IE6 to not report referrer
  		mplink.href = url;
      document.body.appendChild(mplink);
      mplink.click();
		} else {
		  location.href = url; 
		}
	}
  // mp_trans_disable_end
};
/* 
 * flowplayer.js 3.1.3. The Flowplayer API
 * 
 * Copyright 2009 Flowplayer Oy
 * 
 * This file is part of Flowplayer.
 * 
 * Flowplayer is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Flowplayer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Flowplayer.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Date: 2009-02-25 16:24:29 -0500 (Wed, 25 Feb 2009)
 * Revision: 166 
 */
(function(){function g(o){console.log("$f.fireEvent",[].slice.call(o))}function k(q){if(!q||typeof q!="object"){return q}var o=new q.constructor();for(var p in q){if(q.hasOwnProperty(p)){o[p]=k(q[p])}}return o}function m(t,q){if(!t){return}var o,p=0,r=t.length;if(r===undefined){for(o in t){if(q.call(t[o],o,t[o])===false){break}}}else{for(var s=t[0];p<r&&q.call(s,p,s)!==false;s=t[++p]){}}return t}function c(o){return document.getElementById(o)}function i(q,p,o){if(typeof p!="object"){return q}if(q&&p){m(p,function(r,s){if(!o||typeof s!="function"){q[r]=s}})}return q}function n(s){var q=s.indexOf(".");if(q!=-1){var p=s.substring(0,q)||"*";var o=s.substring(q+1,s.length);var r=[];m(document.getElementsByTagName(p),function(){if(this.className&&this.className.indexOf(o)!=-1){r.push(this)}});return r}}function f(o){o=o||window.event;if(o.preventDefault){o.stopPropagation();o.preventDefault()}else{o.returnValue=false;o.cancelBubble=true}return false}function j(q,o,p){q[o]=q[o]||[];q[o].push(p)}function e(){return"_"+(""+Math.random()).substring(2,10)}var h=function(t,r,s){var q=this;var p={};var u={};q.index=r;if(typeof t=="string"){t={url:t}}i(this,t,true);m(("Begin*,Start,Pause*,Resume*,Seek*,Stop*,Finish*,LastSecond,Update,BufferFull,BufferEmpty,BufferStop").split(","),function(){var v="on"+this;if(v.indexOf("*")!=-1){v=v.substring(0,v.length-1);var w="onBefore"+v.substring(2);q[w]=function(x){j(u,w,x);return q}}q[v]=function(x){j(u,v,x);return q};if(r==-1){if(q[w]){s[w]=q[w]}if(q[v]){s[v]=q[v]}}});i(this,{onCuepoint:function(x,w){if(arguments.length==1){p.embedded=[null,x];return q}if(typeof x=="number"){x=[x]}var v=e();p[v]=[x,w];if(s.isLoaded()){s._api().fp_addCuepoints(x,r,v)}return q},update:function(w){i(q,w);if(s.isLoaded()){s._api().fp_updateClip(w,r)}var v=s.getConfig();var x=(r==-1)?v.clip:v.playlist[r];i(x,w,true)},_fireEvent:function(v,y,w,A){if(v=="onLoad"){m(p,function(B,C){if(C[0]){s._api().fp_addCuepoints(C[0],r,B)}});return false}A=A||q;if(v=="onCuepoint"){var z=p[y];if(z){return z[1].call(s,A,w)}}if(y&&"onBeforeBegin,onMetaData,onStart,onUpdate,onResume".indexOf(v)!=-1){i(A,y);if(y.metaData){if(!A.duration){A.duration=y.metaData.duration}else{A.fullDuration=y.metaData.duration}}}var x=true;m(u[v],function(){x=this.call(s,A,y,w)});return x}});if(t.onCuepoint){var o=t.onCuepoint;q.onCuepoint.apply(q,typeof o=="function"?[o]:o);delete t.onCuepoint}m(t,function(v,w){if(typeof w=="function"){j(u,v,w);delete t[v]}});if(r==-1){s.onCuepoint=this.onCuepoint}};var l=function(p,r,q,t){var s={};var o=this;var u=false;if(t){i(s,t)}m(r,function(v,w){if(typeof w=="function"){s[v]=w;delete r[v]}});i(this,{animate:function(y,z,x){if(!y){return o}if(typeof z=="function"){x=z;z=500}if(typeof y=="string"){var w=y;y={};y[w]=z;z=500}if(x){var v=e();s[v]=x}if(z===undefined){z=500}r=q._api().fp_animate(p,y,z,v);return o},css:function(w,x){if(x!==undefined){var v={};v[w]=x;w=v}r=q._api().fp_css(p,w);i(o,r);return o},show:function(){this.display="block";q._api().fp_showPlugin(p);return o},hide:function(){this.display="none";q._api().fp_hidePlugin(p);return o},toggle:function(){this.display=q._api().fp_togglePlugin(p);return o},fadeTo:function(y,x,w){if(typeof x=="function"){w=x;x=500}if(w){var v=e();s[v]=w}this.display=q._api().fp_fadeTo(p,y,x,v);this.opacity=y;return o},fadeIn:function(w,v){return o.fadeTo(1,w,v)},fadeOut:function(w,v){return o.fadeTo(0,w,v)},getName:function(){return p},getPlayer:function(){return q},_fireEvent:function(w,v,x){if(w=="onUpdate"){var y=q._api().fp_getPlugin(p);if(!y){return}i(o,y);delete o.methods;if(!u){m(y.methods,function(){var A=""+this;o[A]=function(){var B=[].slice.call(arguments);var C=q._api().fp_invoke(p,A,B);return C==="undefined"||C===undefined?o:C}});u=true}}var z=s[w];if(z){z.apply(o,v);if(w.substring(0,1)=="_"){delete s[w]}}}})};function b(o,t,z){var E=this,y=null,x,u,p=[],s={},B={},r,v,w,D,A,q;i(E,{id:function(){return r},isLoaded:function(){return(y!==null)},getParent:function(){return o},hide:function(F){if(F){o.style.height="0px"}if(y){y.style.height="0px"}return E},show:function(){o.style.height=q+"px";if(y){y.style.height=A+"px"}return E},isHidden:function(){return y&&parseInt(y.style.height,10)===0},load:function(F){if(!y&&E._fireEvent("onBeforeLoad")!==false){m(a,function(){this.unload()});x=o.innerHTML;if(x&&!flashembed.isSupported(t.version)){o.innerHTML=""}flashembed(o,t,{config:z});if(F){F.cached=true;j(B,"onLoad",F)}}return E},unload:function(){if(x.replace(/\s/g,"")!==""){if(E._fireEvent("onBeforeUnload")===false){return E}try{if(y){y.fp_close()}}catch(F){}y=null;o.innerHTML=x;E._fireEvent("onUnload")}return E},getClip:function(F){if(F===undefined){F=D}return p[F]},getCommonClip:function(){return u},getPlaylist:function(){return p},getPlugin:function(F){var H=s[F];if(!H&&E.isLoaded()){var G=E._api().fp_getPlugin(F);if(G){H=new l(F,G,E);s[F]=H}}return H},getScreen:function(){return E.getPlugin("screen")},getControls:function(){return E.getPlugin("controls")},getConfig:function(F){return F?k(z):z},getFlashParams:function(){return t},loadPlugin:function(I,H,K,J){if(typeof K=="function"){J=K;K={}}var G=J?e():"_";E._api().fp_loadPlugin(I,H,K,G);var F={};F[G]=J;var L=new l(I,null,E,F);s[I]=L;return L},getState:function(){return y?y.fp_getState():-1},play:function(G,F){function H(){if(G!==undefined){E._api().fp_play(G,F)}else{E._api().fp_play()}}if(y){H()}else{E.load(function(){H()})}return E},getVersion:function(){var G="flowplayer.js 3.1.3";if(y){var F=y.fp_getVersion();F.push(G);return F}return G},_api:function(){if(!y){throw"Flowplayer "+E.id()+" not loaded when calling an API method"}return y},setClip:function(F){E.setPlaylist([F]);return E},getIndex:function(){return w}});m(("Click*,Load*,Unload*,Keypress*,Volume*,Mute*,Unmute*,PlaylistReplace,ClipAdd,Fullscreen*,FullscreenExit,Error,MouseOver,MouseOut").split(","),function(){var F="on"+this;if(F.indexOf("*")!=-1){F=F.substring(0,F.length-1);var G="onBefore"+F.substring(2);E[G]=function(H){j(B,G,H);return E}}E[F]=function(H){j(B,F,H);return E}});m(("pause,resume,mute,unmute,stop,toggle,seek,getStatus,getVolume,setVolume,getTime,isPaused,isPlaying,startBuffering,stopBuffering,isFullscreen,toggleFullscreen,reset,close,setPlaylist,addClip,playFeed").split(","),function(){var F=this;E[F]=function(H,G){if(!y){return E}var I=null;if(H!==undefined&&G!==undefined){I=y["fp_"+F](H,G)}else{I=(H===undefined)?y["fp_"+F]():y["fp_"+F](H)}return I==="undefined"||I===undefined?E:I}});E._fireEvent=function(O){if(typeof O=="string"){O=[O]}var P=O[0],M=O[1],K=O[2],J=O[3],I=0;if(z.debug){g(O)}if(!y&&P=="onLoad"&&M=="player"){y=y||c(v);A=y.clientHeight;m(p,function(){this._fireEvent("onLoad")});m(s,function(Q,R){R._fireEvent("onUpdate")});u._fireEvent("onLoad")}if(P=="onLoad"&&M!="player"){return}if(P=="onError"){if(typeof M=="string"||(typeof M=="number"&&typeof K=="number")){M=K;K=J}}if(P=="onContextMenu"){m(z.contextMenu[M],function(Q,R){R.call(E)});return}if(P=="onPluginEvent"){var F=M.name||M;var G=s[F];if(G){G._fireEvent("onUpdate",M);G._fireEvent(K,O.slice(3))}return}if(P=="onPlaylistReplace"){p=[];var L=0;m(M,function(){p.push(new h(this,L++,E))})}if(P=="onClipAdd"){if(M.isInStream){return}M=new h(M,K,E);p.splice(K,0,M);for(I=K+1;I<p.length;I++){p[I].index++}}var N=true;if(typeof M=="number"&&M<p.length){D=M;var H=p[M];if(H){N=H._fireEvent(P,K,J)}if(!H||N!==false){N=u._fireEvent(P,K,J,H)}}m(B[P],function(){N=this.call(E,M,K);if(this.cached){B[P].splice(I,1)}if(N===false){return false}I++});return N};function C(){if($f(o)){$f(o).getParent().innerHTML="";w=$f(o).getIndex();a[w]=E}else{a.push(E);w=a.length-1}q=parseInt(o.style.height,10)||o.clientHeight;if(typeof t=="string"){t={src:t}}r=o.id||"fp"+e();v=t.id||r+"_api";t.id=v;z.playerId=r;if(typeof z=="string"){z={clip:{url:z}}}if(typeof z.clip=="string"){z.clip={url:z.clip}}z.clip=z.clip||{};if(o.getAttribute("href",2)&&!z.clip.url){z.clip.url=o.getAttribute("href",2)}u=new h(z.clip,-1,E);z.playlist=z.playlist||[z.clip];var F=0;m(z.playlist,function(){var H=this;if(typeof H=="object"&&H.length){H={url:""+H}}m(z.clip,function(I,J){if(J!==undefined&&H[I]===undefined&&typeof J!="function"){H[I]=J}});z.playlist[F]=H;H=new h(H,F,E);p.push(H);F++});m(z,function(H,I){if(typeof I=="function"){if(u[H]){u[H](I)}else{j(B,H,I)}delete z[H]}});m(z.plugins,function(H,I){if(I){s[H]=new l(H,I,E)}});if(!z.plugins||z.plugins.controls===undefined){s.controls=new l("controls",null,E)}s.canvas=new l("canvas",null,E);t.bgcolor=t.bgcolor||"#000000";t.version=t.version||[9,0];t.expressInstall="http://www.flowplayer.org/swf/expressinstall.swf";function G(H){if(!E.isLoaded()&&E._fireEvent("onBeforeClick")!==false){E.load()}return f(H)}x=o.innerHTML;if(x.replace(/\s/g,"")!==""){if(o.addEventListener){o.addEventListener("click",G,false)}else{if(o.attachEvent){o.attachEvent("onclick",G)}}}else{if(o.addEventListener){o.addEventListener("click",f,false)}E.load()}}if(typeof o=="string"){flashembed.domReady(function(){var F=c(o);if(!F){throw"Flowplayer cannot access element: "+o}else{o=F;C()}})}else{C()}}var a=[];function d(o){this.length=o.length;this.each=function(p){m(o,p)};this.size=function(){return o.length}}window.flowplayer=window.$f=function(){var p=null;var o=arguments[0];if(!arguments.length){m(a,function(){if(this.isLoaded()){p=this;return false}});return p||a[0]}if(arguments.length==1){if(typeof o=="number"){return a[o]}else{if(o=="*"){return new d(a)}m(a,function(){if(this.id()==o.id||this.id()==o||this.getParent()==o){p=this;return false}});return p}}if(arguments.length>1){var r=arguments[1];var q=(arguments.length==3)?arguments[2]:{};if(typeof o=="string"){if(o.indexOf(".")!=-1){var t=[];m(n(o),function(){t.push(new b(this,k(r),k(q)))});return new d(t)}else{var s=c(o);return new b(s!==null?s:o,r,q)}}else{if(o){return new b(o,r,q)}}}return null};i(window.$f,{fireEvent:function(){var o=[].slice.call(arguments);var q=$f(o[0]);return q?q._fireEvent(o.slice(1)):null},addPlugin:function(o,p){b.prototype[o]=p;return $f},each:m,extend:i});if(typeof jQuery=="function"){jQuery.prototype.flowplayer=function(q,p){if(!arguments.length||typeof arguments[0]=="number"){var o=[];this.each(function(){var r=$f(this);if(r){o.push(r)}});return arguments.length?o[arguments[0]]:new d(o)}return this.each(function(){$f(this,k(q),p?k(p):{})})}}})();(function(){var e=typeof jQuery=="function";var i={width:"100%",height:"100%",allowfullscreen:true,allowscriptaccess:"always",quality:"high",version:null,onFail:null,expressInstall:null,w3c:false,cachebusting:false};if(e){jQuery.tools=jQuery.tools||{};jQuery.tools.flashembed={version:"1.0.4",conf:i}}function j(){if(c.done){return false}var l=document;if(l&&l.getElementsByTagName&&l.getElementById&&l.body){clearInterval(c.timer);c.timer=null;for(var k=0;k<c.ready.length;k++){c.ready[k].call()}c.ready=null;c.done=true}}var c=e?jQuery:function(k){if(c.done){return k()}if(c.timer){c.ready.push(k)}else{c.ready=[k];c.timer=setInterval(j,13)}};function f(l,k){if(k){for(key in k){if(k.hasOwnProperty(key)){l[key]=k[key]}}}return l}function g(k){switch(h(k)){case"string":k=k.replace(new RegExp('(["\\\\])',"g"),"\\$1");k=k.replace(/^\s?(\d+)%/,"$1pct");return'"'+k+'"';case"array":return"["+b(k,function(n){return g(n)}).join(",")+"]";case"function":return'"function()"';case"object":var l=[];for(var m in k){if(k.hasOwnProperty(m)){l.push('"'+m+'":'+g(k[m]))}}return"{"+l.join(",")+"}"}return String(k).replace(/\s/g," ").replace(/\'/g,'"')}function h(l){if(l===null||l===undefined){return false}var k=typeof l;return(k=="object"&&l.push)?"array":k}if(window.attachEvent){window.attachEvent("onbeforeunload",function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){}})}function b(k,n){var m=[];for(var l in k){if(k.hasOwnProperty(l)){m[l]=n(k[l])}}return m}function a(r,t){var q=f({},r);var s=document.all;var n='<object width="'+q.width+'" height="'+q.height+'"';if(s&&!q.id){q.id="_"+(""+Math.random()).substring(9)}if(q.id){n+=' id="'+q.id+'"'}if(q.cachebusting){q.src+=((q.src.indexOf("?")!=-1?"&":"?")+Math.random())}if(q.w3c||!s){n+=' data="'+q.src+'" type="application/x-shockwave-flash"'}else{n+=' classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'}n+=">";if(q.w3c||s){n+='<param name="movie" value="'+q.src+'" />'}q.width=q.height=q.id=q.w3c=q.src=null;for(var l in q){if(q[l]!==null){n+='<param name="'+l+'" value="'+q[l]+'" />'}}var o="";if(t){for(var m in t){if(t[m]!==null){o+=m+"="+(typeof t[m]=="object"?g(t[m]):t[m])+"&"}}o=o.substring(0,o.length-1);n+='<param name="flashvars" value=\''+o+"' />"}n+="</object>";return n}function d(m,p,l){var k=flashembed.getVersion();f(this,{getContainer:function(){return m},getConf:function(){return p},getVersion:function(){return k},getFlashvars:function(){return l},getApi:function(){return m.firstChild},getHTML:function(){return a(p,l)}});var q=p.version;var r=p.expressInstall;var o=!q||flashembed.isSupported(q);if(o){p.onFail=p.version=p.expressInstall=null;m.innerHTML=a(p,l)}else{if(q&&r&&flashembed.isSupported([6,65])){f(p,{src:r});l={MMredirectURL:location.href,MMplayerType:"PlugIn",MMdoctitle:document.title};m.innerHTML=a(p,l)}else{if(m.innerHTML.replace(/\s/g,"")!==""){}else{m.innerHTML="<h2>Flash version "+q+" or greater is required</h2><h3>"+(k[0]>0?"Your version is "+k:"You have no flash plugin installed")+"</h3>"+(m.tagName=="A"?"<p>Click here to download latest version</p>":"<p>Download latest version from <a href='http://www.adobe.com/go/getflashplayer'>here</a></p>");if(m.tagName=="A"){m.onclick=function(){location.href="http://www.adobe.com/go/getflashplayer"}}}}}if(!o&&p.onFail){var n=p.onFail.call(this);if(typeof n=="string"){m.innerHTML=n}}if(document.all){window[p.id]=document.getElementById(p.id)}}window.flashembed=function(l,m,k){if(typeof l=="string"){var n=document.getElementById(l);if(n){l=n}else{c(function(){flashembed(l,m,k)});return}}if(!l){return}if(typeof m=="string"){m={src:m}}var o=f({},i);f(o,m);return new d(l,o,k)};f(window.flashembed,{getVersion:function(){var m=[0,0];if(navigator.plugins&&typeof navigator.plugins["Shockwave Flash"]=="object"){var l=navigator.plugins["Shockwave Flash"].description;if(typeof l!="undefined"){l=l.replace(/^.*\s+(\S+\s+\S+$)/,"$1");var n=parseInt(l.replace(/^(.*)\..*$/,"$1"),10);var r=/r/.test(l)?parseInt(l.replace(/^.*r(.*)$/,"$1"),10):0;m=[n,r]}}else{if(window.ActiveXObject){try{var p=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7")}catch(q){try{p=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");m=[6,0];p.AllowScriptAccess="always"}catch(k){if(m[0]==6){return m}}try{p=new ActiveXObject("ShockwaveFlash.ShockwaveFlash")}catch(o){}}if(typeof p=="object"){l=p.GetVariable("$version");if(typeof l!="undefined"){l=l.replace(/^\S+\s+(.*)$/,"$1").split(",");m=[parseInt(l[0],10),parseInt(l[2],10)]}}}}return m},isSupported:function(k){var m=flashembed.getVersion();var l=(m[0]>k[0])||(m[0]==k[0]&&m[1]>=k[1]);return l},domReady:c,asString:g,getHTML:a});if(e){jQuery.fn.flashembed=function(l,k){var m=null;this.each(function(){m=flashembed(this,l,k)});return l.api===false?this:m}}})();
// Date last modified =  090108
// Modified by =  JGP

var lpMTagConfig = {
        "lpServer" : "sales.liveperson.net",
        "lpNumber" : "37457093",
        "lpProtocol" : (document.location.toString().indexOf("https:")==0) ? "https" : "http",
		"lpTagLoaded" : false,
		"pageStartTime" : (new Date()).getTime() //pageStartTime is set with a timestamp as soon as the page starts loading
	}

function lpAddMonitorTag(src)
{
	if (!lpMTagConfig.lpTagLoaded)
	{
		if(typeof(src)=="undefined"||typeof(src)=="object"){src=lpMTagConfig.lpMTagSrc?lpMTagConfig.lpMTagSrc:"/hcp/html/mTag.js";}if(src.indexOf("http")!=0){src=lpMTagConfig.lpProtocol+"://"+lpMTagConfig.lpServer+src+"?site="+lpMTagConfig.lpNumber;}else{if(src.indexOf("site=")<0){if(src.indexOf("?")<0)src=src+"?";else src=src+"&";src=src+"site="+lpMTagConfig.lpNumber;}};var s=document.createElement("script");s.setAttribute("type","text/javascript");s.setAttribute("charset","iso-8859-1");s.setAttribute("src",src);document.getElementsByTagName("head").item(0).appendChild(s);	
	}
}
/*
The code below send a PAGEVAR to LP with the time [in seconds] it took the page to load. Code is executed in the onload event
*/
lpMTagConfig.calculateSentPageTime = function () {
	var t = (new Date()).getTime() - lpMTagConfig.pageStartTime;
	lpAddVars('page','pageLoadTime', Math.round(t/1000)+" sec");
};

if (window.attachEvent)window.attachEvent("onload",lpMTagConfig.calculateSentPageTime);
else window.addEventListener("load",lpMTagConfig.calculateSentPageTime,false);

//Load mtag.js inline if this is a Confermation Page else load it on page load event
if (window.attachEvent)window.attachEvent("onload",lpAddMonitorTag);
else window.addEventListener("load",lpAddMonitorTag,false);

//Variables Arrays - By Scope
if (typeof(lpMTagConfig.pageVar)=="undefined") lpMTagConfig.pageVar = new Array();
if (typeof(lpMTagConfig.sessionVar)=="undefined") lpMTagConfig.sessionVar = new Array();
if (typeof(lpMTagConfig.visitorVar)=="undefined") lpMTagConfig.visitorVar = new Array();
//Extra actions to be taken once the code executes
if (typeof(lpMTagConfig.onLoadCode)=="undefined") lpMTagConfig.onLoadCode = new Array();
//Dynamic Buttons Array
if(typeof(lpMTagConfig.dynButton)=="undefined") lpMTagConfig.dynButton=new Array();

// Function that sends variables to LP - By Scope
function lpAddVars(scope,name,value) {
	if (name.indexOf('OrderTotal')!=-1 || name.indexOf('OrderNumber')!=-1){
		if  (value=='' || value==0) return; // pass 0 value to all but OrderTotal
		else lpMTagConfig.sendCookies = false
	}
	
	value=lpTrimSpaces(value.toString());
	switch (scope){
		case "page": lpMTagConfig.pageVar[lpMTagConfig.pageVar.length] = escape(name)+"="+escape(value); break;
		case "session": lpMTagConfig.sessionVar[lpMTagConfig.sessionVar.length] = escape(name)+"="+escape(value); break;
		case "visitor": lpMTagConfig.visitorVar[lpMTagConfig.visitorVar.length] = escape(name)+"="+escape(value); break;
	}	
}
// Preventing long cookie transfer for IE based browsers.
function onloadEMT() { 
	var LPcookieLengthTest=document.cookie;
	if (lpMTag.lpBrowser == "IE" && LPcookieLengthTest.length>1000){
		lpMTagConfig.sendCookies=false;
	}
}

//The Trim function returns a text value with the leading and trailing spaces removed
function lpTrimSpaces(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
// Immediate Data submission function
function lpSendData(varscope,varname,varvalue){
if(typeof(lpMTag)!="undefined" && typeof(lpMTag.lpSendData)!="undefined")
  lpMTag.lpSendData(varscope.toUpperCase() +"VAR!"+ varname + "=" + varvalue, true);
}

// This need to be add to afterStartPage will work
lpMTagConfig.ifVisitorCode = [];

// The unit variable purpose is to route the chat or call to the designated skill. <LOB> should be replaced with the skill name, i.e. : sales
try{
	if (typeof(lpUnit)=="undefined")	var lpUnit='shs';
	if(typeof(lpAddVars)!="undefined")	lpAddVars("page","unit",lpUnit);
	if (typeof(lpLanguage)=="undefined")	var lpLanguage='english';
	if(typeof(lpAddVars)!="undefined")	lpAddVars("session","language",lpLanguage);
	lpMTagConfig.defaultInvite ='voice'+'-' + lpUnit;
	}catch(e){}

lpMTagConfig.onLoadCode[lpMTagConfig.onLoadCode.length] = onloadEMT;
var SelectDate = Class.create({
  init: function(dateSelectionCallback, container_id) {
    this.dateSelectionCallback = dateSelectionCallback;
    this.bindEvents();

    if(container_id){
      this.scheduler_calender_container = "#" + container_id;
    }
  },

  bindEvents: function() {
    var self = this;
    
	//UNBIND CLICKS FOR PREVENTING DOUBLE ASSIGNATION
    $("#previousDate").unbind('click');
	
    $("#previousDate").click(function() {
      self.selectPreviousDate();
    });

	//UNBIND CLICKS FOR PREVENTING DOUBLE ASSIGNATION
    $("#nextDate").unbind('click');
		
	$("#nextDate").click(function() {
      self.selectNextDate();
    });
  },
  
  setTimePreference: function(time) {
    this.timePreference = time;
  },

  isAvailable: function(date) {
    var formattedDate = $.datepicker.formatDate('yy-mm-dd', date); //yy means 4-digit year
    var found = false;
    jQuery.each(this.dates, function() {
      if (this == formattedDate)
        found = true;
    });

    return found;
  },

  fillDates: function(dates) {
    //data is array of date strings in yyyy-mm-dd format.
    this.populateDates(dates);
    this.initCalendar();
  },

  isPopulated:function() {
    return this.dates.length != 0;
  },

  populateDates: function(data) {
    this.dates = [];
    var self = this;
    jQuery.each(data, function(i, value) {
      self.dates[i] = value.date;
    });
    return this.dates;
  },

  setSelectedDate: function(dateText) {
    var formattedDate = $.datepicker.formatDate('D, MM d, yy', new Date(dateText));
    this.userSelectedDate = dateText;
    $("#selectedDate").html(formattedDate);
    this.dateSelectionCallback && this.dateSelectionCallback(this.getSelectedDate(dateText));
  },

  getSelectedDate: function() {
    if (this.userSelectedDate != null) {
      return $.datepicker.formatDate('yy-mm-dd', new Date(this.userSelectedDate));//yy means 4-digit year
    }
    return null;
  },

  getTimePreference: function() {
    return this.timePreference;
  },

  getPreviousAvailableDate: function(date) {
    var index = this.indexOf(date);
    var previousDateIndex = index - 1;
    if ((index != -1) && (previousDateIndex >= 0)) {
      var previousDate = $.datepicker.parseDate('yy-mm-dd', this.dates[previousDateIndex]);
      return previousDate;
    }
    return date;
  },

  getNextAvailableDate: function(date) {
    var index = this.indexOf(date);
    var nextDateIndex = index + 1;
    if ((index != -1) && (nextDateIndex != this.dates.length)) {
      var nextDate = $.datepicker.parseDate('yy-mm-dd', this.dates[nextDateIndex]);
      return nextDate;
    }
    return date;
  },

  initCalendar: function() {
    var self = this;
    $(this.scheduler_calender_container).datepicker('destroy');
    $(this.scheduler_calender_container).datepicker({
      minDate: $.datepicker.parseDate('yy-mm-dd', self.getFirstAvailableDate()),
      maxDate: $.datepicker.parseDate('yy-mm-dd', self.getLastAvailableDate()),
      beforeShowDay: function(date) {
        return [self.isAvailable(date),'  '];
      },
      onSelect: function(date) {
        self.setSelectedDate(date);
        var product_name = SchedulerService.productNameForService($("#service :selected").val());
        OmnitureCall.reportSchedulerMicroView("date", $("#zip_code").val(), $("#service").val(), product_name);
      }
    });
    $(this.scheduler_calender_container).datepicker('option', 'defaultDate', null);
    this.selectFirstDateAvailable();
  },

  indexOf: function(date) {
    var formattedDate = $.datepicker.formatDate('yy-mm-dd', date);//yy means 4-digit year
    var returnValue = -1;
    jQuery.each(this.dates, function(i, value) {
      if (value == formattedDate) {
        returnValue = i;
      }
    });
    return returnValue;
  },

  selectPreviousDate: function () {
    var date = $(this.scheduler_calender_container).datepicker('getDate');
    var previousDate = this.getPreviousAvailableDate(date);
    $(this.scheduler_calender_container).datepicker('setDate', previousDate);
    date = $(this.scheduler_calender_container).datepicker('getDate');
    this.setSelectedDate(date);
  },

  selectNextDate: function () {
    var date = $(this.scheduler_calender_container).datepicker('getDate');
    var nextDate = this.getNextAvailableDate(date);
    $(this.scheduler_calender_container).datepicker('setDate', nextDate);
    date = $(this.scheduler_calender_container).datepicker('getDate');
    this.setSelectedDate(date);
  },
  
  selectFirstDateAvailable: function () {
    var date=$.datepicker.parseDate('yy-mm-dd', this.getFirstAvailableDate());
    $(this.scheduler_calender_container).datepicker('setDate', date);
    date = $(this.scheduler_calender_container).datepicker('getDate');
    this.setSelectedDate(date);
  },

  getFirstAvailableDate:function() {
    $('#firstAvailableDate').val(this.dates[0]);
    return this.dates[0];
  },

  getLastAvailableDate:function() {
    return this.dates[this.dates.length - 1];
  },

  userSelectedDate: null,
  scheduler_calender_container: "#scheduler_calendar",
  dates: []

});
var DomainHandler = {};

DomainHandler.isUserInteractingWithSearsDotCom = function() {
    return $("#searsVertical").val();
}
var CleanType = Class.create({
  init: function(zipcode) {
    //TODO:use classes to hide/show
    SchedulerObserver.scheduler.resetHeight($('#step_one'));

    this.zipcode = zipcode;
    this.products = new Array();
    this.packages = new Array();
    //additional services hash
    this.additionalServices={};
    this.isRequestSubmitted = false;
  },

  setup: function(){
    this.products.push(new CleanSelectProduct("cleaning",
        this.zipcode,
        0,
        "#product",
        "#package",
        "#quantity",
        "#subtotal",
        this));
    this.productCounter = 1;
    this.hideClickToCallInStepTwo();
    this.showCleanQuestionInStepTwo();
    this.observe();
	  this.dynamicDescription = "What do you need cleaned?";
    $("#dynamicDescription").html(this.dynamicDescription);
    var self = this;
    this.selectDate = new SelectDate(function(dateText) {
      $('#go_to_step_three').addClass('disabled');
      $('#go_to_step_three').addClass('blocked');
      $('#schedule_service').removeClass('blocked');
      self.showTimeSlots();
    });
  },
  getNextUniqueId: function() {
    this.productCounter = this.productCounter + 1;
    return this.productCounter;
  },

  hideClickToCallInStepTwo: function() {
    $('#service_date_desc').hide();
  },

  showClickToCallInStepTwo: function() {
    $('#service_date_desc').show();
  },

  hideCleanQuestionInStepTwo: function() {
    $('#service_clean_question').hide();
  },

  showCleanQuestionInStepTwo: function() {
    $('#service_clean_question').show();
  },

  observe: function() {
    // this.observeTimePreference();
    this.observeScheduleService();
    this.observeAddAnotherService();
  },

  growSchedulerHeight: function() {
    SchedulerObserver.scheduler.growHeight(
        SchedulerObserver.scheduler.standardNewCleaningHeight,
        $('#step_one')
        );
  },

  observeRemoveServiceLink:function(removeServiceId) {
    var self = this;
    $("#" + removeServiceId).click(function(element) {
      self.removeService(this,self);
    });
  },

  removeService:function(element,self){
    var removedProductSectionId = self.getSectionId($(element));
    self.reduceHeight($(element));
    self.products = self.removeProductFromArray(self.products, removedProductSectionId);
    self.removeAdditionalSectionValidation($(element).attr('id'));
    self.showTotalCost();
    $("#add_service").show();
  },

  removeAllServices:function(){
    var innerElements = $('#step_one').find('a.remove_service');
    var self=this;
    innerElements.each(function(index,element){
      self.removeService(element,self);
    });
  },

  observeAddAnotherService: function() {
    var self = this;
    $("#add_service").click(function(event) {
      var productSectionUniqueId = self.getNextUniqueId();
      var sectionIdBuilder = new AdditionalSectionIdBuilder(productSectionUniqueId);

      self.growSchedulerHeight();
      self.insertAddtionalServiceSection($(this), sectionIdBuilder);

      var product = new CleanSelectProduct("cleaning", self.zipcode,
          productSectionUniqueId,
          "#" + sectionIdBuilder.productElementId(),
          "#" + sectionIdBuilder.packageElementId(),
          "#" + sectionIdBuilder.quantityElementId(),
          "#" + sectionIdBuilder.subTotalElementId(),
          self);
      product.update();
      self.products.push(product);

      self.observeRemoveServiceLink(sectionIdBuilder.removeServiceId());
      self.observeAdditionalSectionValidation(sectionIdBuilder.removeServiceId());

      event.stopImmediatePropagation();
      new SchedulerUtilities('#scheduler');
    });
  },

  removeAdditionalSectionValidation:function(sectionId){
    this.additionalServices[sectionId].fieldset.reset();
    delete this.additionalServices[sectionId];
    $('#go_to_step_two').removeClass('disabled');
    $('#go_to_step_two').removeClass('blocked');
    $.each(this.additionalServices,function(index,element){
      if(typeof element.fieldset!='undefined'){
        element.fieldset.validate(true);
      }
    })
  },

  observeAdditionalSectionValidation:function(sectionId){
    this.additionalServices[sectionId]=new SchedulerValidationObserver.attachValidateAdditionalService();
  },

  insertAddtionalServiceSection:function(addServiceElement, sectionIdBuilder) {
    var t = this.cleanServicesTemplate();
    //German:  an append here was replaced for a before in another container
    addServiceElement.before(t, {
    //addServiceElement.append(t, {
      product: sectionIdBuilder.productElementId(),
      package: sectionIdBuilder.packageElementId(),
      quantity: sectionIdBuilder.quantityElementId(),
      subtotal: sectionIdBuilder.subTotalElementId(),
      removeServiceId: sectionIdBuilder.removeServiceId()
    });

  },

  reduceHeight:function(section) {
    var parent = section.parents('.container');
    section.parents('.section_add_service').remove();
    SchedulerObserver.scheduler.growHeight(SchedulerObserver.scheduler.standardNewCleaningHeight * -1, parent);
  },

  getSectionId:function(section) {
    return section.attr("id").substring("remove".length);
  },

  removeProductFromArray:function(products, removedProductSectionId) {
    var removeMatchingElement = true;
    return jQuery.grep(products, function(product) {
      return product.getProductSectionUniqueId() == removedProductSectionId;
    }, removeMatchingElement);
  },

  observeScheduleService: function() {
    var self = this;
    $("#schedule_service").unbind("click.clean").bind("click.clean", function() {
      var validation = new FormValidation($('#contact_info'), schedulerStep3ErrorHolder);
      if (!validation.hasErrors && !self.isRequestSubmitted) {
        self.isRequestSubmitted = true;
        self.createOrder();
      }
      return false;
    });
  },

  showTimeSlots: function(timeSlots) {
    var self = this;
    var name = 'cleanTimePreference';

    new TimeSlot().resetTimeSlots();

    jQuery.each(['AM','PM'], function(index, timeslot) {
      var timeSlot = new TimeSlot(name, index, timeslot, function(input_value) {
        self.dateContainer.setTimePreference(input_value);
      });

      $(timeSlot.option).appendTo($('#time_slots'));
    });
  },

  showTotalCost: function() {
    var totalCost = 0;
    jQuery.each(this.products, function(i, product) {
      var selectedPackage = product.getPackageHolder();
      var subtotal = 0;
      if(selectedPackage != null && isNaN(selectedPackage.subTotal()) == false) {
        subtotal = selectedPackage.subTotal();
      } else if(isNaN(subtotal)) {  
        subtotal = 0;
      }
      
      totalCost = totalCost + subtotal;
    });
    $("#totalPrice").show();
    $("#totalPrice").html("Total cost <p class='price'><em>$</em>" + this.truncate(totalCost) + "</p>");
    $('#priceForOmnitureTracking').val(totalCost.toFixed(2));
  },

  truncate: function(price){
    var stringPrice = new String(price);
    if(stringPrice.indexOf(".") > 0) stringPrice = price.toFixed(2);
    return stringPrice;
  },


  cleanServicesTemplate: function() {
    return $.template('<div class="section_add_service" id="section_add_service">' +
                      //comment this fieldset again
                      '  <fieldset class="js_validate_additional_service">' +
                      '    <div class="section"> ' +
                      '      <div class="product fieldset_wrap"> ' +
                      '          <label for="${product}">Product</label> ' +
                      '          <select id="${product}" class="js_required" title="Product"> ' +
                      '            <option>Product</option> ' +
                      '          </select> ' +
                      '      </div> ' +
                      '      <a id="${removeServiceId}" class="remove_service">&#45; Remove this service</a> ' +
                      '    </div> ' +
                      '    <div class="section"> ' +
                      '      <div class="package fieldset_wrap"> ' +
                      '        <label for="${package}">Select a package</label> ' +
                      '          <select id="${package}" class="js_required" title="Select a package">' +
                      '            <option>Select a package</option> ' +
                      '          </select>' +
                      '      </div> ' +
                      '      <div class="quantity fieldset_wrap"> ' +
                      '        <label for="${quantity}">Quantity</label> ' +
                      '        <select id="${quantity}" title="Quantity">' +
                      '          <option selected="true" value="1">Quantity 1</option> <option value="2">Quantity 2</option> <option value="3">Quantity 3</option> <option value="4">Quantity 4</option> <option value="5">Quantity 5</option> <option value="6">Quantity 6</option> <option value="7">Quantity 7</option> <option value="8">Quantity 8</option> <option value="9">Quantity 9</option>' +
                      '        </select>' +
                      '      </div> ' +
                      '      <div class="subtotal fieldset_wrap"> ' +
                      '        Subtotal <span id="${subtotal}">$0</span> ' +
                      '      </div> ' +
                      '    </div> ' +
                      '  </fieldset> ' +
                      '</div>');
  },

  getProduct : function() {
    return this.products;
  },

  setDateContainer: function (dateContainer) {
    this.dateContainer = dateContainer;
  },

  register: function() {
    var self = this;
    this.products[0].update();
  },

  createOrder: function() {
    var self = this;
    var orderParams = this.createOrderParams();
    var successFunction = function(data) {
      self.successfullOrder(data);
    };

    var errorFunction = function(cleanError) {
      new SchedulerServiceError($.evalJSON(cleanError)).display();
    };

    new SchedulerRequest().httpPost(this.createCleanOrderUrl, orderParams, successFunction, errorFunction, $('#schedule_service'));

    return false;
  },

  successfullOrder: function(data) {
    $("#successfullOrderForm").attr("action", this.orderSuccessfullyCreated);
    $("#successfullOrderForm").submit();
  },

  createOrderParams: function() {
    var parameters = {'zipCode': this.zipcode.val(),
      'serviceCode': $("#product").val(),
      'serviceId': $("#package").val(),
      'quantity': $("#quantity").val(),
      'chosenDate': this.dateContainer.getSelectedDate(),
      'timePreference':this.dateContainer.getTimePreference(),
      'firstName': $("#first_name").val(),
      'lastName': $("#last_name").val(),
      'phone': $("#phone").val(),
      'email': $("#email").val(),
      'optForEmail': $("#optForEmail").attr("checked") ? $("#optForEmail").val() : "N",
      'address': $("#address").val(),
      'city': $("#city").val(),
      'state': $("#state").val(),
      'notes' : ($("#notes").val() != $("#notes").attr('title'))? $("#notes").val():"",
      'serviceCount': this.products.length
    };

    var postParameters = jQuery.extend(parameters, this.prepareServiceParameters());
    return postParameters;
  },

  prepareServiceParameters: function() {
    var serviceParameters = new Array();
    jQuery.each(this.products, function(i, product) {
      var serviceParameterBuilder = new CleanServiceParameterBuilder(i, product);
      var parameters = serviceParameterBuilder.build();
      serviceParameters = jQuery.extend(serviceParameters, parameters);
    });
    return serviceParameters;
  },

  reset: function() {
    this.removeAllServices();
    $('#add_service').hide();
    $("#totalPrice").hide();
    $("#clean_services").hide();
    $("#schedule_service").unbind("click.clean");
    this.showClickToCallInStepTwo();
    this.hideCleanQuestionInStepTwo();
    this.products[0].resetProductList();
    this.products[0].resetPackageList();
    new SchedulerRequest().cancelPriorRequest();
    this.destroyExistingCalendar();
    $("#email").addClass("js_required"); //toggle for CIR
  },

  destroyExistingCalendar: function() {
    $("#scheduler_calendar").datepicker('destroy');
  },

  hasDates:function() {
    if (!this.dateContainer)
      return false;
    return this.dateContainer.isPopulated();
  },

  populateDates:function() {
    if (this.products[0].isValid() && !this.hasDates()) {
      this.getDates();
    }
  },

  getDates: function() {
    var self = this;
    var successFunction = function(dates) {
      self.setDateContainer(self.selectDate);
      self.selectDate.fillDates(dates);
    };

    var errorFunction = function(cleanError) {
      SchedulerObserver.scheduler.next("#error_message");
      new SchedulerServiceError($.evalJSON(cleanError)).display();
    };

    new SchedulerRequest().httpGet(this.getDatesUrl(), this.selectParams(), successFunction, errorFunction, $(this.selectDate.scheduler_calender_container));
  },

  getDatesUrl:function() {
    return this.datesForCleanURL;
  },

  selectParams: function() {
    return {'zipCode': this.zipcode.val(), 'serviceCode': $(this.productElementId).val()};
  },

  createCleanOrderUrl: "/shs/createCleanAppointmentJSON",
  datesForCleanURL: '/shs/cleanDateAvailabilityJSON',
  orderSuccessfullyCreated: '/shs/order/clean/confirmation'


});

var AdditionalSectionIdBuilder = Class.create({
  init: function(sectionUniqueId) {
    this.sectionUniqueId = sectionUniqueId;
  },

  getSectionUniqueId:function() {
    return this.sectionUniqueId;
  },

  productElementId: function() {
    return "product" + this.sectionUniqueId;
  },

  packageElementId: function() {
    return "package" + this.sectionUniqueId;
  },

  quantityElementId: function() {
    return "quantity" + this.sectionUniqueId;
  },

  subTotalElementId: function() {
    return "subtotal" + this.sectionUniqueId;
  },

  removeServiceId:function() {
    return "remove" + this.sectionUniqueId;
  }

});
var CleanServiceParameterBuilder = Class.create({
  init: function(index, product) {
    this.index = index;
    this.product = product;
    this.selectedPackage = product.getSelectedPackage();
  },

  build:function(product) {
    var parameters = new Array();
    parameters[this.productElementId()] = this.product.getSelectedProduct();
    parameters[this.quantityElementId()] = this.product.getSelectedQuantity();
    parameters[this.packageElementId()] = this.selectedPackage.id;
    return parameters;
  },

  productElementId:function() {
    return "product" + this.index;
  },
  packageElementId:function(){
    return "package" + this.index;
  },

  quantityElementId:function(){
    return "quantity" + this.index;
  }
});
var CleanSelectProduct = Class.create({
  init: function(selected_service, zipcode, productSectionUniqueId, productElementId, packageElementId, quantityElementId, subtotalElementId, cleanType) {
    this.selected_service = selected_service;
    this.zipcode = zipcode;
    this.productSectionUniqueId = productSectionUniqueId;
    this.productElementId = productElementId;
    this.packageElementId = packageElementId;
    this.quantityElementId = quantityElementId;
    this.subtotalElementId = subtotalElementId;
    this.cleanType = cleanType
    $(this.productElementId).parent("div.product").show();
    this.observeProductChange();
    this.schedulerPrepopulator = new SchedulerPrepopulator();
  },

  getProductSectionUniqueId:function() {
    return this.productSectionUniqueId;
  },

  observeProductChange: function() {
    var self = this;
    $(this.productElementId).unbind("change.clean").bind("change.clean", function() {
      //new SchedulerRequest().cancelPriorRequest();
      //Unmesh:Commenting cancelling previous requests. Causing too much problem when all the requests get cancelled and multiple services are added.
      new Select($(self.packageElementId)).removeAllElements("", "Select a package")
      self.processProductChange($(this));
      self.cleanType.populateDates(); //Moved here from clean_type.js so that cancelling unfinished prior requests should fire a new request for getting dates.
    });
  },


  processProductChange: function(product) {
    if ($(product).val() != $(product).attr('title')) {
      this.showCleanPackageSection();
      this.selectedProduct = product.val();
      this.packageHolder = new CleanSelectPackage("cleaning", this.zipcode, this.productElementId, this.productSectionUniqueId, this.packageElementId, this.quantityElementId, this.subtotalElementId, this.cleanType);
      this.packageHolder.update();
    }
  },

  getSelectedProduct: function() {
    return this.selectedProduct;
  },

  getSelectedPackage:function() {
    return this.packageHolder.getSelectedPackage();
  },

  getSelectedQuantity: function() {
    return this.packageHolder.getSelectedQuantity();
  },

  getPackageHolder: function() {
    return this.packageHolder;
  },

  hideInitialHelp: function() {
    $("#initialHelp").hide();
  },

  processResponse: function(select_element, products) {
    new Select(select_element).populateWith(products, "id", "description", "Product", "Product").forceChangeEventForSingleOption();
  },

  populateProductList: function(select_element, products) {
    this.processResponse(select_element, products);
  },

  showCleanServiceDescription: function(description) {
    $("#dynamicDescription").show();
    $("#dynamicDescription").html(description);
  },

  showCleanPackageSection: function() {
    if (this.selected_service == this.cleanName) {
      $("#clean_services").show()
    } else {
      $("#clean_services").hide()
    }
  },

  resetProductList: function() {
    this.processResponse($(this.productElementId), []);
    $(this.productElementId).unbind("change.clean");
    $('#clean_services').hide();
  },

  resetPackageList: function() {
    if (this.packageHolder) {
      this.packageHolder.resetPackageList();
    }
  },

  populateProducts: function(product_dropdown, data) {
    if (data.length != 0) {
      //this.hideInitialHelp();
     // this.showCleanServiceDescription(data.serviceDescription);
      this.populateProductList(product_dropdown, data.products);
      this.schedulerPrepopulator.selectElementAndTriggerChangeForService(product_dropdown, $("#schedulerInformation_product"));

    } else {
      this.resetProductList();
    }
  },

  createPackageParams: function() {
    return {'zipCode': this.zipcode.val(), 'selectedServiceCode': "ALL"};
  },

  selectParams: function() {
    return this.createPackageParams();
  },

  handleData: function(data) {
    this.populateProducts($(this.productElementId), data);
  },

  isValid: function() {
    return ((this.zipcode.val() != null) && (this.zipcode.val().length == 5));
  },

  update: function() {

    var errorFunction = function(cleanError) {
         SchedulerObserver.scheduler.next("#error_message");
         new SchedulerServiceError($.evalJSON(cleanError)).display();
       };

    var self = this;
    if (this.isValid()) {
      new SchedulerRequest().httpGet(this.selectUrl(), this.selectParams(), function(data) {
        self.populateProducts($(self.productElementId), data);
      }, errorFunction, $(self.productElementId));
    } else {
      this.handleData([]);
    }
  },

  selectUrl: function() {
    return this.servicesForCleanURL;
  },

  servicesForCleanURL: '/shs/cleanServicesAvailabilityJSON',
  cleanName : "cleaning"
});

var Appointment = Class.create({
  init: function(service, params) {
    this.minTriggerResize = 4;
    this.timeSlotHeight = 28;
    this.service = service;
    this.params = params;
    this.handleEmergencyService();
    $('#contact_by_phone').hide();
    $('#contact_me_by_phone').change(function() {
      $('input[name=shipTimePreference]').parents('.radio_group').removeClass('selected');
    });

		$('#priority_service').unbind('click');
		$('#contact_me_by_phone').unbind('click');

		$('#contact_me_by_phone').click(function(){
			if( !$('#contact_me_by_phone').is(':checked')) {
        $('#time_slots').show();
				$('#time_slots').val($('option:first', this).val());
				$('#go_to_step_three').addClass('disabled');
				$('#go_to_step_three').addClass('blocked');
			}
			else if ( $('#contact_me_by_phone').is(':checked')) {
        if($('#priority_service').is(':checked')){
              $('#priority_service').attr('checked', false);
            }
        $('#time_slots').hide(); 
				$('#go_to_step_three').removeClass('disabled');
				$('#go_to_step_three').removeClass('blocked');
			}
		});		

     $('#priority_service').click(function(){

        if ($('#priority_service').is(':checked') && !$('#contact_me_by_phone').is(':checked')){
          $('#time_slots').show();
          if($('#time_slots').val() == $('#time_slots').attr('title')) {
				      $('#go_to_step_three').addClass('disabled');
				      $('#go_to_step_three').addClass('blocked');
            }
        } else if($('#priority_service').is(':checked') && $('#contact_me_by_phone').is(':checked')){

          $('#contact_me_by_phone').attr('checked', false);
            $('#time_slots').show();  
            if($('#time_slots').val() == $('#time_slots').attr('title')) {
				      $('#go_to_step_three').addClass('disabled');
				      $('#go_to_step_three').addClass('blocked');
            }       
        } 
      });

    var self = this;
    this.selectDate = new SelectDate(function(selectedDate) {
      self.updateTimeSlots(selectedDate);
    });
  },

  handleEmergencyService: function() {
    if ($('#product').val() == this.HEATING_AND_COOLING) {
      $('#emergency_service').show();
    } else {
      $('#emergency_service').hide();
      $('#priority_service').attr('checked', false);
    }
  },

  availabilityCalendar: function() {
    this.getDates();
  },

  updateTimeSlots: function(selectedDate) {
    var self = this;
    $('#contact_by_phone').show();
    $('#selectedDate').show();
    $('#previousDate').show();
    $('#nextDate').show();
    $("#currentDate").val(selectedDate);
    var timeSlots;
    jQuery.each(this.datesData["shipDateTimeSlots"], function() {
      if (this.date == selectedDate) {
        timeSlots = jQuery.map(this["timeSlots"], function(datum) {
          return datum;
        });
        self.showTimeSlots(timeSlots);
        if($('#contact_me_by_phone').is(':checked')) {
          $('#time_slots').hide();
        }
        if(!$('#time_slots').is(':visible')) {
          $('#go_to_step_three').removeClass('disabled');
				  $('#go_to_step_three').removeClass('blocked');
        }
      }
    });
  },

  showTimeSlots: function(timeSlots) {
    var self = this;
    var name = 'shipTimePreference';

    jQuery.each(timeSlots, function(index, timeslot) {
      var timeSlot = new TimeSlot(name, index, timeslot.time, function(input_value) {
        self.selectedTime = input_value;
        $("#currentDate").val(self.selectedDate);
      });

      $(timeSlot.option).appendTo($('#time_slots'));
      $(timeSlot.option).attr("salesRepId", timeslot.salesRepId)
      $(timeSlot.option).attr("overnightAreaId", timeslot.overnightAreaId)
    });
  },

  getDates: function() {
    var self = this;
    var successFunction = function(datesData) {
      if (datesData["message"]) {
        new SchedulerServiceError(datesData).display();
      } else {
//        hiddenParamsForFinalSubmit(datesData);
        self.datesData = datesData;
        self.selectDate.fillDates(datesData["shipDateTimeSlots"]);
      }
    };

    var errorFunction = function(shipError) {
      SchedulerObserver.scheduler.next("#error_message");
      new SchedulerServiceError($.evalJSON(shipError)).display();
    };

//    var hiddenParamsForFinalSubmit = function(datesData) {
//      //for submitting the create request we would need lots of other params , since we are not using scope interceptor anymore
//      // we would pass this in the final request for create. these include things like latitude, longitude etc.
//      $("#driveTime").val(datesData.driveTime);
//      $("#latitude").val(datesData.latitude);
//      $("#longitude").val(datesData.longitude);
//      $("#officeId").val(datesData.officeId);
//    };

    new SchedulerRequest().httpGet(this.availableDatesUrl, this.params, successFunction, errorFunction, $(this.selectDate.scheduler_calender_container));
  },

  createParams: function() {
     var appointmentParams = {};
     var selectedTimeslot = $("#time_slots option:selected");
//     appointmentParams.driveTime = $("#driveTime").val();
//     appointmentParams.latitude = $("#latitude").val();
//     appointmentParams.longitude = $("#longitude").val();
//     appointmentParams.officeId = $("#officeId").val();
     appointmentParams.selectedDate = $("#currentDate").val();
     appointmentParams.overnightAreaId = selectedTimeslot.attr("overnightAreaId");
     appointmentParams.salesRepId = selectedTimeslot.attr("salesRepId");
     appointmentParams.selectedTime = this.selectedTime;
     appointmentParams.contactMeByPhone =  $('#contact_me_by_phone').attr('checked');
     appointmentParams.priority = $('#priority_service').attr('checked');
     return appointmentParams;
   },


  HEATING_AND_COOLING: '8',
  availableDatesUrl: '/shs/shipDateAvailabilityJSON'
});
var Customer = Class.create({
  init: function() {

  },

  createParams: function() {
    var customerParams = {};
    customerParams.firstName = $("#first_name").val();
    customerParams.lastName = $("#last_name").val();
    customerParams.phone = $("#phone").val();
    customerParams.secondaryPhone = ($("#secondary_phone").val() != $("#secondary_phone").attr('title'))? $("#secondary_phone").val():"";
    customerParams.email = $("#email").val();
    customerParams.address = $("#address").val();
    customerParams.city = $("#city").val();
    customerParams.state = $("#state").val();
    customerParams.notes = ($("#notes").val() != $("#notes").attr('title'))? $("#notes").val():"";
    customerParams.optForEmail = $("#optForEmail").val();
   return customerParams;
  }
});
var ServiceLocation = Class.create({
  init: function(){

  },

  getServiceURL: function(serviceType){
    return this.serviceUrl[serviceType];
  },

  serviceUrl: {
    "home_improvement": "/shs/createShipAppointmentJSON"
  }

});
var Select = Class.create({
  init: function(element) {
    this.element = element;
  },

  populateWith: function(data, key, description, headerKey, headerDescription) {
    key = key || "id";
    description = description || "description";
    headerKey = headerKey || "";
    headerDescription = headerDescription || "Select";

    var html = this.defaultOption(data, headerKey)
    html += this.populate(data, key, description);
    this.element.html(html);
    return this;
  },

  forceChangeEventForSingleOption: function(forceEmptyValidValue) {
    var selectLength=this.element.children('option').size();
    if (selectLength == 1) {
      if(forceEmptyValidValue && $(this.element).hasClass('js_required')) {
	      $(this.element).removeClass('js_required');
      } else  {
	      $(this.element).addClass('js_required');
      }
      this.element.trigger('change');
    }
    return selectLength;
  },

  defaultOption: function(data, headerKey) {
    if (data.length != 1) {
      return this.buildOption(headerKey);
    }
    return "";
  },

  populate: function(data, key, description) {
    var self = this;
    var options = "";
    jQuery.each(data, function() {
      options += self.buildOption(this[key], this[description]);
    });
    return this.addOtherFieldForCIRProblems(options);
  },

  addOtherFieldForCIRProblems: function (options) {
    if($(this.element).attr('id') == 'problem_description') {
      options += '<div class="select_flyout_option clearfix"><input type="checkbox" id="otherProblemsCheckBox" value="Other problems|OTHR" ' +
                 '/><label for="otherProblemsCheckBox">Other :</label><input class="js_select_other_nop js_prompt_text" id="otherProblems" title="please describe" value="please describe"></div>';
      return options;
    }

    return options;
  },

  buildOption: function(value, description) {
    if($(this.element).attr('id') == 'problem_description') { 
      if (typeof description == 'undefined') {
        return '';
      } else {
        var id = description.replace(/\s+/g, '_').toLowerCase();

        return '<div class="select_flyout_option"><input id="' + id + '"  type="checkbox" value="' + value + '"/>' + '<label for="' + id + '">' + description + '</label></div>'
      }
    } else {
      if (typeof description == 'undefined') {
        return '<option>' + value + '</option>';
      } else {
        return '<option value="' + value + '" title="' + description + '">' + description + '</option>';
      }
    }
  },

  // Truncation was removed, but saving it down here... 
  //
  // buildOption: function(value, description) {
  //   if (typeof description == 'undefined') {
  //     return '<option>' + value + '</option>';
  //   }
  // 
  //   var actualDescription = description;
  //   if (isIE() && description.length > 20) {
  //     description = description.substr(0, 20) + "...";
  //   }
  //   return '<option value="' + value + '" title="' + actualDescription + '">' + description + '</option>'
  // },

  removeAllElements: function(id, description) {
    this.element.html("");
    this.element.html(this.buildOption(id, description));
  }
});
var Order = Class.create({
  init: function(service, zipcode) {
    this.service = service;
    this.zipcode = zipcode;
    this.availability = null;
    this.appointment = null;
    this.customer = null;

    // Part for merging logic
    this.serviceType = null;
  },

  observeService: function() {
    var self = this;
    this.service.change(function() {
      if ((self.zipcode.val() != "") && (self.zipcode.val().length == 5)) {
          self.addServiceClassNameToScheduler($(this).val());
          self.serviceDetails($(this).val());
      }
    });
  },

observeZipCode: function() {
      var self = this;
      this.zipcode.change(function() {
        self.zipcode = $(this);
        if ((self.service.val() != "") && (self.zipcode.val().length == 5)) {
          self.addServiceClassNameToScheduler(self.service.val());

          self.serviceDetails(self.service.val());

      }
    });
  },


observe: function() {
      this.observeService();
      this.observeZipCode();
      this.populate();
  },

  serviceDetails: function(serviceType) {
    if (this.serviceType && this.serviceType.reset) {
        new Button($("#schedule_service"), "Schedule service");
        this.serviceType.reset();
        this.serviceType = null;
        $("#add_to_cart_message").addClass("hide");
        new Select($("#product")).removeAllElements("", "Product")
    }
    if (serviceType == "cleaning") {
        this.serviceType = new CleanType(this.zipcode);
        this.serviceType.setup();
    } else if (serviceType == "repair") {
        this.serviceType = new RepairType(this.zipcode);
    } else if (serviceType == "installation") {
        this.serviceType = new InstallationType(this.zipcode, $("#install_product_category"), $(".js_install_back"));
    } else if (serviceType == "home_improvement") {
        this.serviceType = new SHIPType(this.zipcode)
    }
    if (this.serviceType != null) {
        this.serviceType.register();
    }

    if (Order.canBeAddedToCart(serviceType)) {
      if (this.serviceType) { this.serviceType.addToCart = "true"; };
      $("#add_to_cart_message").removeClass("hide");
      $("#schedule_service span").text('Add to cart');
    }

  },

  isCarryInProduct:function() {
    if(this.serviceType && this.serviceType.isCarryInProduct) {
      return this.serviceType.isCarryInProduct()
    }
    return false;
  },

  addServiceClassNameToScheduler:function(className) {
    var scheduler = $('#scheduler');
    $(scheduler).attr('class', '');
    $(scheduler).addClass(className);
  },

  populateCustomerInformation: function(customerInformation) {
    if (!customerInformation.zipcode)
      return;
    this.zipcode.val(customerInformation.zipcode);
    $("#address").val(customerInformation.concatenatedAddress);
    $("#address_line_1").val(customerInformation.concatenatedAddress==''?'Address':customerInformation.concatenatedAddress);
    $("#city").val(customerInformation.city);
    $("#ship_city").val(customerInformation.city);
    $("#state").val(customerInformation.state);
    $("#ship_state").val(customerInformation.state);
    $("#first_name").val(customerInformation.firstName);
    $("#last_name").val(customerInformation.lastName);
    $("#phone").val(customerInformation.phone);
    $("#email").val(customerInformation.email);
    $("#county").val(customerInformation.county);
    $("#secondary_phone").val(customerInformation.alternatePhone)
    new PromptText().isPrePopulated('#zip_code');
  },

  populateContactUsInformation: function(customerInformation) {
    if (!customerInformation.zipcode)
      return;
    $("#contact_first_name").val(customerInformation.firstName);
    $("#contact_last_name").val(customerInformation.lastName);
    $("#contact_phone").val(customerInformation.phone);
    $("#contact_email").val(customerInformation.email);
  },

  populate: function() {
    var self = this;
    $.get(this.customerInformationUrl, {}, function(customerInformation) {
      self.populateCustomerInformation(customerInformation);
      self.populateContactUsInformation(customerInformation);
    }, "json");
  },
  customerInformationUrl: '/shs/customerInformationJSON'
});



Order.canBeAddedToCart = function(serviceType) {
  return  DomainHandler.isUserInteractingWithSearsDotCom() &&
          serviceType != "home_improvement" &&
          serviceType != "cleaning";
}
var ShipAvailability = Class.create( {
  init : function(zipcode, products, address) {
    this.zipcode = zipcode;
    this.products = products;
    this.address = address;
    this.schedulerPrepopulator = new SchedulerPrepopulator();
  },

  populateProducts : function() {
    var self = this;
    var successFunction = function(data) {
      if (data["message"]) {
        new SchedulerServiceError(data).display();
      } else {
        self.jsonForProducts(data);
        self.schedulerPrepopulator.selectElementAndTriggerChangeForService(self.products, $("#schedulerInformation_product"));
      }
    };
    var errorFunction = function(error) {
      SchedulerObserver.scheduler.next("#error_message");
      new SchedulerServiceError($.evalJSON(error)).display();
    };
    new SchedulerRequest().httpGet(this.serviceLocation,
                                 this.createShipParams(), 
                                 successFunction, 
                                 errorFunction, $('#product'));
    this.showAddress();
  },

  jsonForProducts : function(data) {
    new Select(this.products).populateWith(data, "id", "description", "Product", "Product");
  },

  createShipParams : function() {
    return {
      'zipCode' : this.zipcode.val()
    };
  },

  showAddress : function() {
    this.address.show();
    this.triggerBlurForAddressFields(); //Hack for putting titles back on field if value set earlier is empty string
  },

  triggerBlurForAddressFields: function() {
    var inputs = $(this.address).find(':input');
    $(inputs).each(function() {
      $(this).trigger('blur');
    });
  },

  createParams : function() {
    var params = {};
    params.zipCode = $("#zip_code").val();
    params.product = $("#product").val();
    params.service = "Home Improvement";
    params.serviceType = "home_improvement";
    params.city = $("#ship_city").val();
    params.state = $("#ship_state").val();
    params.address = $("#address_line_1").val();
    return params;
  },

  serviceLocation : '/shs/shipServicesAvailabilityJSON'
});
var CleanSelectPackage = Class.create({
  init: function(selected_service, zipcode, selected_product_id, productSectionUniqueId, packageElementId, quantityElementId, subtotalElementId, cleanType) {
    this.selected_service = selected_service;
    this.zipcode = zipcode;
    this.productElementId = selected_product_id
    this.productSectionUniqueId = productSectionUniqueId;
    this.packageElementId = packageElementId;
    this.quantityElementId = quantityElementId;
    this.subtotalElementId = subtotalElementId;
    this.cleanType = cleanType;
    this.selectedQuantity = 1;
  },

  packages:[],

  resetPackageList: function() {
    $(this.packageElementId).html(this.buildOptions([]));
    $(this.packageElementId).unbind("change.clean");
  },

  processResponse: function(data) {
    this.description = data.serviceDescription;
    $("#dynamicDescription").html(data.serviceDescription);
    var options = this.buildOptions(data.entries);
    return options;
  },

  buildOptions: function(entries) {
    var self = this;
    var options = this.buildOption("Select a package", "Select a package");
    jQuery.each(entries, function(i, value) {
      options += self.buildOption(this.id, this.description);
      self.packages[this.id] = this;
    });
    return options;
  },

  buildOption: function(id, description) {
    return "<option value=\"" + id + "\">" + description + "</option>\n";
  },

  populateProducts: function(select_element, data) {
    if(data){
      //SchedulerObserver.scheduler.next(select_element);
      $(select_element).html(this.processResponse(data));
      this.observePackageChange();
    }
  },

  observePackageChange: function() {
      var self = this;
      $(this.packageElementId).unbind("change.clean").bind("change.clean", function() {
        self.showSubTotal();

        self.selectedPackageValue = $(self.packageElementId).val();
//        $("#add-another-service").show();
      });

      $(this.quantityElementId).unbind("change.clean").bind("change.clean", function() {
        self.showSubTotal()
        self.selectedQuantity = $(self.quantityElementId).val()
      });
  },

  getSelectedQuantity:function() {
    return this.selectedQuantity;
  },

  getSelectedPackage:function() {
    return this.packages[this.selectedPackageValue];
  },

  subTotal: function() {
    var subTotal = 0;
    var selectedPackage = this.packages[$(this.packageElementId).val()]
    if (selectedPackage != null) {
     var price = selectedPackage.salePrice;
     subTotal = parseFloat(price) * parseFloat($(this.quantityElementId).val());
    }
    return subTotal;
  },

  showSubTotal: function() {
    var subTotal = this.subTotal();
    this.cleanType.showTotalCost();
    $(this.subtotalElementId).html("$" + this.formattedSubTotal(subTotal));
  },

  formattedSubTotal: function(subTotal){
    var subTotalValue = new String(subTotal);
    if(subTotalValue.indexOf(".") > 0) subTotalValue = subTotal.toFixed(2);
    return subTotalValue;
  },

  createPackageParams: function() {
    return {'zipCode': this.zipcode.val(), 'serviceCode': $(this.productElementId).val()};
  },

  handleData: function(data) {
    this.populateProducts($(this.packageElementId), data);
  },

  isValid: function() {
    return (this.selected_service == this.cleanName && (this.zipcode != null) && (this.productElementId != null));
  },

  update: function() {
    var self = this;
    if (this.isValid()) {
      if (this.selected_service == this.cleanName) {
        new SchedulerRequest().httpGet(this.servicesForCleanURL, this.createPackageParams(), function(data) {
          self.populateProducts($(self.packageElementId), data);
        }, new SchedulerRequest().defaultErrorHandler, $(this.packageElementId));
      }
    } else {
      this.handleData([]);
    }
  },

  servicesForCleanURL: '/shs/cleanPackagesJSON',
  cleanName : "cleaning"
});
var RepairType = Class.create({
  init: function(zipcode) {
    //TODO:use classes to hide/show
    this.productWrapper = $('.product.fieldset_wrap').parents('fieldset');
    this.productWrapper.hide();
    this.productWrapper.addClass('faux_hide');

    $("#scheduler .click_to_chat_optional").show();
    $('.product_group.fieldset_wrap').parents('fieldset').show();
    $("#repair_contact_info").show();

    SchedulerObserver.scheduler.resetHeight($('#step_one'));

    this.zipcode = zipcode;
    this.selectRepairProduct = new RepairSelectProduct("repair", this.zipcode);
    this.isRequestSubmitted = false;

    var self = this;
    $("#schedule_service").unbind("click.repair").bind("click.repair", function() {
      validation = new FormValidation($('#contact_info'), schedulerStep3ErrorHolder);
      if (!validation.hasErrors && !self.isRequestSubmitted) {
        self.isRequestSubmitted = true;
        self.createOrder();
      }
      return false;
    });
    this.dynamicDescription = "Tell us what needs fixing.";
    this.showRepairQuestionInStepTwo();
    $("#dynamicDescription").html(this.dynamicDescription);
  },

  isCarryInProduct:function() {
    return this.selectRepairProduct.selectedPackage.carryIn;
  },

  hideRepairQuestionInStepTwo: function() {
    $('#service_repair_question').hide();
  },

  showRepairQuestionInStepTwo: function() {
    $('#service_repair_question').show();
  },

  register: function() {
    this.selectRepairProduct.updateProductGroups();
  },

  getProduct: function() {
    return this.selectRepairProduct;
  },

  createOrder: function() {
    //if a product is eligible for both 'addToCart' & 'carryIn' - carryIn takes precedence. 
    if(this.selectRepairProduct.selectedPackage.carryIn) {
      new CarryInRepairOrder(this.selectRepairProduct,this.zipcode).create();
      return;
    }
    if (this.addToCart) {
      new AddToCartRepairOrder(this.selectRepairProduct,this.zipcode).create()
      return;
    }

    new RepairOrder(this.selectRepairProduct,this.zipcode).create();
  },


  reset: function() {
    $("#step_2_calendar_wrapper").show();
    $("#step_2_store_information_wrapper").hide();
    $("#step_2_store_information_wrapper").html("");
    $("#schedulerInformation_storeNumber").val('');
    $("#schedulerInformation_storeID").val(''); 
    $("#store_locator").hide();
    $("#scheduler .click_to_chat_optional").hide();
    $("#go_to_step_two").show();
    $("#repair_site_services").hide();
    $("#date_time_content").removeClass("hide");
    $("#repair_by_phone").hide();
    //$("#dynamicDescription").hide();
    $("#repairTimePreference").hide();
    $("#repair_contact_info").hide();
    $("#schedule_service").unbind("click.repair");
    $("#product").unbind("change.repair");
    this.productWrapper.removeClass('faux_hide');
    this.hideRepairQuestionInStepTwo();
    new SchedulerRequest().cancelPriorRequest();
    this.destroyExistingCalendar();
    $("#email").addClass("js_required");   //toggle for CIR
  },

  destroyExistingCalendar: function() {
    $("#scheduler_calendar").datepicker('destroy');
  }

});
var SHIPType = Class.create({
  init: function(zipcode) {
    //TODO:use classes to hide/show
    $("#product").parent("div.product").show();
    SchedulerObserver.scheduler.resetHeight($('#step_one'));
    new TimeSlot().resetTimeSlots();


    this.params = {};
    this.zipcode = zipcode;
    this.isRequestSubmitted = false;
    this.product = $("#product");
    this.shipAvailability = new ShipAvailability(this.zipcode, this.product, $("#ship_service_address"));
    this.showShipQuestionInStepTwo();
    this.dynamicDescription="What would you like to do?";
    this.dynamicProductDescription="Our consultants will meet you for an in-home design consultation.";
    $("#dynamicDescription").html(this.dynamicDescription);
  },

  hideShipQuestionInStepTwo: function() {                                                 
    $('#service_ship_question').hide();
  },

  showShipQuestionInStepTwo: function() {
    $('#service_ship_question').show();
  },

  register: function() {
    this.shipAvailability.populateProducts();
    this.observeServiceNext();
    this.observeProductChange();
    this.observeAppointmentNext();
    this.observeScheduleService();
  },

  observeProductChange: function() {
    var self = this;
    this.product.unbind("change.ship").bind("change.ship", function() {
      $("#dynamicDescription").html(self.dynamicProductDescription);
    });
  },

  observeServiceNext: function() {
    var self = this;
    $("#go_to_step_two").bind("click.ship",function() {
      if(self.isStepDataValid(this)){
        var availabilityParams = self.shipAvailability.createParams();
        self.mergeArray(availabilityParams, self.params);
        self.resetCalendar();
        self.appointment = new Appointment(self.service, self.params);
        self.appointment.availabilityCalendar();
      }
    });
  },

  isStepDataValid:function(element){
    return !($(element).parents('.container').hasClass('selected_container'));
  },

  observeAppointmentNext: function() {
    var self = this;
    $("#go_to_step_three").bind("click.ship",function() {
      var appointmentParams = self.appointment.createParams();
      self.mergeArray(appointmentParams, self.params);
      self.customer = new Customer();
    });
  },
  observeScheduleService: function() {
    var self = this;
    $("#schedule_service").unbind("click.ship").bind("click.ship", function() {
      validation = new FormValidation($('#contact_info'), schedulerStep3ErrorHolder);
      if (!validation.hasErrors && !self.isRequestSubmitted) {
        var customerParams = self.customer.createParams();
        self.mergeArray(customerParams, self.params);
        self.isRequestSubmitted = true;
        self.commitOrder(self);
      }
      return false;
    });
  },


  mergeArray: function(src, dest) {
    for (key in src) {
      dest[key] = src[key];
    }
  },
    commitOrder: function(instance) {
    var self = this;
    var successFunction = function(msg) {
      instance.reset();
      SchedulerObserver.scheduler.resetToStart();
      self.successfullOrder(msg);
    };

    var errorFunction = function(shipError) {
      new SchedulerServiceError($.evalJSON(shipError)).display();
    };

    var schedulerRequest = new SchedulerRequest();
    new SchedulerRequest().httpPost(new ServiceLocation().getServiceURL(instance.params.serviceType), instance.params, successFunction, errorFunction, $('#schedule_service'));

  },

  successfullOrder: function(data) {
    $("#successfullOrderForm").attr("action", this.orderSuccessfullyCreated);
    $("#successfullOrderForm").submit();
  },

  reset: function() {
    $("#shipTimePreference").hide();
    $("#ship_service_address").hide();
    this.hideShipQuestionInStepTwo();
    
    new TimeSlot().resetTimeSlots();

    new SchedulerRequest().cancelPriorRequest();
    $("#schedule_service").unbind("click.ship");
    $("#go_to_step_two").unbind("click.ship");
    $("#go_to_step_three").unbind("click.ship");
    this.product.unbind("change.ship");
    this.destroyExistingCalendar();
    $("#email").addClass("js_required"); //toggle for CIR
  },

  destroyExistingCalendar: function() {
    $("#scheduler_calendar").datepicker('destroy');
  },

  resetCalendar: function() {
      this.destroyExistingCalendar();
      $('#selectedDate').hide();
      $('#previousDate').hide();
      $('#nextDate').hide();
      new TimeSlot().resetTimeSlots();

  },

  orderSuccessfullyCreated: '/shs/order/ship/confirmation'

});
var RepairSelectProduct = Class.create({
  init: function(selected_service, zipcode) {
    this.productWrapper = $('.product.fieldset_wrap').parents('fieldset');
    this.selected_service = selected_service;
    this.zipcode = zipcode;
    this.product = $("#product");
    this.productGroup = $("#productGroup");
    this.dynamicProductDescription = "What seems to be the problem?";
    this.carryInDynamicProductDescription = "Where would you like to drop off your item for repair? Please pick a drop off location.";
    var self = this;

    this.product.unbind("change.repair").bind("change.repair", function() {
      if ($(this).val() != $(this).attr('title')) {
        new SchedulerRequest().cancelPriorRequest();
        self.processProductChange($(this));
      }
    });

    this.productGroup.unbind("change.repair").bind("change.repair", function() {
      self.processProductGroupChange();
    });
    this.schedulerPrepopulator = new SchedulerPrepopulator();
  },

  processProductGroupChange: function() {
    $('#product').parents('fieldset').show();
    $("#product").parent("div.product").show();
    $("#dynamicDescription").html(this.getDescriptionForProductGroup(this.productGroup.val()))
    this.updateProducts();
  },

  processProductChange: function(product) {
    $("#dynamicDescription").html(this.getDynamicProductDescription(product));
    this.displayProductTypeInformation(product);
  },

  getDynamicProductDescription: function(product) {
    if(this.getProductData(product).carryIn){
      return this.carryInDynamicProductDescription;
    }
    return this.dynamicProductDescription;
  },

  displayProductTypeInformation: function(product) {
    this.selectedPackage = new RepairSelectPackage(this.zipcode, product, this.getProductData(product).carryIn);
    this.selectedPackage.update();
    this.showSiteInformation();
  },

  showSiteInformation: function() {
    $("#repair_site_services").show();
  },

  hideStoreLocatorInfo: function() {
    $("#store_locator_description").hide();
    $("#store_locator").addClass("hide");
  },

  getProductData: function(product) {
    var productData;
    jQuery.each(this.data.products, function() {
      if (this.id == product.val()) {
        productData = this;
      }
    });
    return productData;
  },

  getOrderParams:function() {
    return  this.selectedPackage.getOrderParams();
  },

  populateProducts: function(context, select_element, data) {

    context.hideStoreLocatorInfo();
    context.data = data;

    var selectProductDropdown = new Select(select_element);
    selectProductDropdown.populateWith(data.products, "id", "description", "Product", "Product");

    if (selectProductDropdown.forceChangeEventForSingleOption() > 1) {
      context.productWrapper.removeClass('faux_hide');
    } else {
      context.productWrapper.addClass('faux_hide');
    }
  },

  populateProductGroups: function(context, select_element, data) {
    context.data = data;

    context.productGroups = data;
    new Select(select_element).populateWith(data, "name", "name", "Product group", "Product group").forceChangeEventForSingleOption();

    if (isIE6()) {
      setTimeout(function() {
        context.schedulerPrepopulator.selectElementAndTriggerChangeForService(select_element, $("#schedulerInformation_productGroup"));
      }, 100);
    } else {
      context.schedulerPrepopulator.selectElementAndTriggerChangeForService(select_element, $("#schedulerInformation_productGroup"));
    }
  },

  createPackageParams: function() {
    return {'zipCode': this.zipcode.val(),'productGroup':this.productGroup.val()};
  },


  selectUrl: function() {
    return this.productGroupsForRepairURL;
  },

  selectParams: function() {
    return this.createPackageParams();
  },

  isValid: function() {
    return (this.zipcode.val() != null);
  },


  updateProductGroups: function() {
    this.update(this.productGroup, this.productGroupsForRepairURL, null, this.populateProductGroups);
  },

  updateProducts: function() {
    if ($(this.productGroup).val() != $(this.productGroup).attr('title')) {
      this.update(this.product, this.productForRepairURL, this.selectParams(), this.populateProducts);
    }
  },

  update: function(elementToPopulate, selectUrl, selectparams, populate) {

    var self = this;
    if (this.isValid()) {
      var successFunction = function(data) {
        setTimeout(function() {
          populate(self, elementToPopulate, data);
        }, 1000);
      };
      var errorFunction = function(errorMessage) {
        new RepairSchedulerServiceError($.evalJSON(errorMessage)).display();
      }
      new SchedulerRequest().httpGet(selectUrl, selectparams, successFunction, errorFunction, $('#product'));
    } else {
      populate(self, elementToPopulate, []);
    }
  },

  getDescriptionForProductGroup: function(selectedGroup) {
    var removeMatchingElement = false;
    var productGroup = jQuery.grep(this.productGroups, function(productGroup) {
      return productGroup.name == selectedGroup;
    }, removeMatchingElement);
    return productGroup.length == 0 ? '' : productGroup[0].description;
  },

  productGroupsForRepairURL: '/shs/repairProductGroupJSON',
  productForRepairURL: '/shs/repairServicesAvailabilityJSON'
});

var RepairSelectPackage = Class.create({
  init: function(zipcode, selected_product, carryIn) {
    this.zipcode = zipcode;
    this.product = selected_product;
    this.carryIn = carryIn;
    var self = this;
    //$("#warranty").attr('disabled','disabled');
    this.selectDate = new SelectDate(function(selectedDate) {
      self.updateTimeSlots(selectedDate);
    });
  },

  populateProducts: function(select_element, brandData) {
    new Select(select_element).populateWith(brandData, "id", "description", "Brand", "Brand");
  },

  populateProblemDescription: function(problemDescriptionData) {
    if(this.carryIn) {
      new Select($("#problem_description")).populateWith(problemDescriptionData, "id", "description", "Nature of the problem", "Nature of the problem");
    } else {
      new Select($("#in_home_problem_description")).populateWith(problemDescriptionData, "id", "description", "Nature of the problem", "Nature of the problem");
    }
    //new SchedulerObserver.attachSelectFlyoutLister();
  },

  createPackageParams: function() {
    return {'zipCode': this.zipcode.val(), 'productId': this.product.val()};
  },

  isValid: function() {
    return (this.zipcode != null) && (this.product != null);
  },

  displayPhoneInformation: function() {
    $("#date_time_content").css('visibility', 'hidden');
    $("#repair_by_phone").show();
    if (DomainHandler.isUserInteractingWithSearsDotCom()) {
      $("#skip_phone_schedule").hide();
    }
    $("#skip_phone_schedule").unbind("click.repair").bind("click.repair", function() {
      $("#date_time_content").css('visibility', 'visible');
      $("#repair_by_phone").fadeOut();
      return false;
    });
  },

  hidePhoneInformation: function() {
    $("#date_time_content").css('visibility', 'visible');
    $("#repair_by_phone").hide();
  },

  handleSchedulerStepTwo: function() {
    this.resetCarryInStoreInformation();
    if(this.carryIn) {
       this.getCarryInStoreInformation();
      } else {
        this.handlePhoneInformationDisplay();
    }
  },

  resetCarryInStoreInformation: function(){
    $("#step_2_store_information_wrapper").html("");
    $("#step_2_store_information_wrapper").hide();
  },

  getCarryInStoreInformation: function(){
    $("#step_2_calendar_wrapper").hide();
    $("#step_2_store_information_wrapper").html("");
    var self = this;
    var successFunction = function(html) {
      $("#step_2_store_information_wrapper").html(html);
      $("#step_2_store_information_wrapper").show();
      self.updateCarryInStep3Message();
      var carryInDescription = new RepairProductDataType(self.productDataType).getDynamicDescription(self.minimumService, self.dataDescription);
      $("#carry_in_description").html(carryInDescription);
      $("#step_2_wrapper").ready(function() {
        attachAllObservers();
      });
    }
    var errorFunction = function(errorMessage) {
      new RepairSchedulerServiceError($.evalJSON(errorMessage)).display();
    }
    new SchedulerRequest().httpGetHtml(this.carryInStoresUrl,
        this.createCarryInParams(),
        successFunction,
        errorFunction,
        $("#step_2_store_information_wrapper"));
  },

  createCarryInParams: function() {
    return{
      'zipCode': $('#zip_code').val()
    };
  },

  handlePhoneInformationDisplay: function() {
    if ($("#warranty").find(':selected').attr("phonesupport") == "true") {
      this.displayPhoneInformation();
    } else {
      this.hidePhoneInformation();
    }
  },

  observe: function() {
    var self = this;

    $("#warranty").unbind("change.repair").bind("change.repair", function() {
      self.updateDescriptionWithData();
      //self.handlePhoneInformationDisplay();
      self.handleSchedulerStepTwo();
    });
  },

  update: function() {
    this.updateProductData();
    this.observe();
    if (!this.carryIn) {
      $('#step3_description').hide();
      $('#contact_info .right').show();
      $('#scheduler').removeClass('carry_in');
      $('.problem_description').hide();
      $("#step_2_calendar_wrapper").show();
      this.getDates();
      if($('#schedule_service span').text() != 'Add to cart') {
        $("#schedule_service span").text("Schedule service");
      }
    } else {
      $('#contact_info .right').hide();
      $('#step3_description').show();
      $('#scheduler').addClass('carry_in');
      $('.problem_description').show();
      $("#schedule_service span").text("Confirm & print");
      $("#email").removeClass("js_required");    //toggle for CIR
    }
  },

  resetWarrantyDropdown: function() {
    $("#warranty").val('Warranty');
    $("#warranty").removeAttr('disabled');
  },

  updateProductData: function() {
    var self = this;
    var successFunction = function(data) {
      self.populateProblemDescription(data["productProblems"]);
      //self.resetWarrantyDropdown();
      self.populateProducts($("#brand"), data["brands"]);
      self.dataDescription = data["description"];
      self.updateCTCTemplateId(data["ctcTemplateId"]);
      self.updateCallUsNumber(data["callUsNumber"]);
      self.productDataType = data["productPrice"].applicableToProductType;
      self.handleDynamicData(data);
      //self.handlePhoneInformationDisplay();
      self.handleSchedulerStepTwo();
    };
    var errorMessageHandler = function(repairError) {
      new RepairSchedulerServiceError($.evalJSON(repairError)).display();
    };

    var problemDescriptionElement = $('#in_home_problem_description');
    if (this.carryIn) {
      problemDescriptionElement = $('#problem_description');
    }
    new SchedulerRequest().httpGet(this.productDetailsUrl,
        this.createPackageParams(),
        successFunction,
        errorMessageHandler,
        problemDescriptionElement);
  },

  // this is a second attachment of the same method
  /* 
   attachRepairInfoValidation: function() {
   $('#repair_info').addClass('js_validate_repair_info');
   if (typeof $('#repair_info')[0].js_attached == 'undefined') {
   $('#repair_info')[0].js_attached = {};
   }
   $('#repair_info')[0].js_attached.js_validate_repair_info = false;
   new SchedulerValidationObserver.attachValidateRepairInfo();
   },*/

  updateCTCTemplateId: function(ctcTemplateId) {
    $("#ctc_template, #talk_to_us_icon_scheduler").attr('href', ctcTemplateId);
    RepairSelectPackage.ctcTemplateId = ctcTemplateId;
    new UIObserver.attachClickToCall().attachBehavior($("#ctc_template"));
  },

  updateCallUsNumber: function(callUsNumber) {
    RepairSelectPackage.callUsNumber = callUsNumber;
    $("#call_us_number").html(callUsNumber);
  },

  updateTimeSlots: function(selectedDate, option) {
    new TimeSlot().resetTimeSlots();

    var self = this;
    jQuery.each(this.datesData["serviceDates"], function() {
      if (this.date == selectedDate) {
        self.showTimeSlots(this.timeSlots);
      }
    });
  },

  getOrderParams: function() {
    return {'selectedDate'        : this.selectDate.getSelectedDate(),
      'selectedTime'        : this.selectedTime
    };
  },

  showTimeSlots: function(timeSlots) {
    var self = this;
    var name = 'repairTimePreference';

    jQuery.each(timeSlots, function(index, timeslot) {
      var timeSlot = new TimeSlot(name, index, timeslot, function(option_value) {
        self.selectedTime = option_value;
      });
      $(timeSlot.option).appendTo($('#time_slots'));
    });
  },

  getDates: function() {
    var self = this;
    $("#repairTimePreference").show();

    var successFunction = function(datesData) {
      self.datesData = datesData;
      self.populateWithDates(datesData["serviceDates"]);
    };

    var errorFunction = function(repairError) {
      new RepairSchedulerServiceError($.evalJSON(repairError)).display();
    };

    new SchedulerRequest().httpGet(this.getDatesUrl(), this.createPackageParams(), successFunction, errorFunction, $(this.selectDate.scheduler_calender_container));
  },

  populateWithDates: function(dates) {
    this.selectDate.fillDates(dates);
  },

  updateMinimumServiceChargeDisplay : function() {
    var warranty = $("#warranty").val();
    if (warranty == "DONT_KNOW" || warranty == "NO_COVERAGE" || warranty == "NON_SEARS_WARRANTY" || warranty == $("#warranty").attr('title')) {
      var minimumChargeHtml = new RepairProductDataType(this.productDataType).getMinimumChargeHtml(this.minimumService);
      $('#priceForOmnitureTracking').val(this.minimumService);
      $("#service_date_desc").html(minimumChargeHtml).show();
    } else {
      $("#service_date_desc").hide();
    }
  },

  updateMinimumServiceCharge: function(productData) {
    this.minimumService = productData["productPrice"].price;
    if (productData["productPrice"].procId) {
      this.flatRateProcId = productData["productPrice"].procId;
    }
  },

  handleDynamicData:  function(productData) {
    this.updateMinimumServiceCharge(productData);
    this.updateDescriptionWithData();
  },

  updateDescriptionWithData: function() {
    if (!this.minimumService) {
      return;
    }
    this.updateMinimumServiceChargeDisplay();
  },

  getDatesUrl:function() {
    return this.datesForRepairURL;
  },

  updateCarryInStep3Message: function() {
    var message = '<h3>Next step</h3><p>Just print your confirmation form and bing it with your product to the service center you chosse.</p><p>Base pricing for your visit is:<span class="price">$'
        + this.minimumService
        + '</span> (excludes parts costs, taxes)</p>';
    $("#step3_description").html(message);
    this.cloneNavigation();
  },
  
  // This is a major hack to put the navigation in the right place for IE.
  cloneNavigation: function(){
    $('#contact_info .bottom .navigation').appendTo('#step3_description');
  },
  datesForRepairURL: '/shs/repairDateAvailabilityJSON',
  productDetailsUrl: '/shs/productDetailsJSON',
  carryInStoresUrl: '/shs/store-locations!show'
});

var RepairProductDataType = Class.create({
  init: function(type) {
    this.type = type;
  },

  getMinimumChargeHtml: function(minimumService) {
    return this.minimumServiceChargeMapping[this.type](minimumService);
  },
  
  getDynamicDescription: function(minimumService, dataDescription) {
    if (this.type == 'NORMAL') {
      return dataDescription;
    }
    return this.minimumServiceChargeMapping[this.type](minimumService);
  },

  minimumServiceChargeMapping : {
    "FLAT_RATE" : function(minimumService) {
      return '<div class="price"><em>$</em>' + minimumService + '</div> <h3>It’s just that simple.</h3> <p>This is the total charge for our visit and labor (part costs not included). No hourly rate, no hidden fees.</p>';
    },
    'PREVENTIVE_MAINTENANCE': function(minimumService) {
      return '<div class="price"><em>$</em>' + minimumService + '</div> <p>Keep running strong. You count on your appliances to run well. You can count on us to keep them running strong with prompt, professional maintenance service. We’ll stop problems before they start, and save you time and money.</p>';
    },
    'CARRY_IN' : function(minimumService) {
      return '<div class="price"><em>$</em>' + minimumService + '</div> <h3>It’s just that simple.</h3> <p>This is the total charge for your carry-in repair (part costs not included). No hourly rate, no hidden fees.</p>';
    },
    'NORMAL' : function(minimumService) {
      return '<h3>Minimum Charge:</h3> <p>includes product inspection and an estimate of labor and part costs, is available when you schedule online. Other costs only apply once you\'ve approved the estimate. </p> <p class="price"><em>$</em>' + minimumService + '</p>';
    }
  }
});
var RepairRescheduleDate = Class.create({
  init: function(element) {
    this.element = element;
    new SchedulerUtilities('.reschedule');
  },

  initialize: function() {
    var self = this;
    this.selectDate = new SelectDate(function(selectedDate) {
      self.updateTimeSlots(selectedDate);
    }, "reschedule_calendar");
    this.getDates();
  },

  updateTimeSlots: function(selectedDate) {
    new TimeSlot().resetTimeSlots();
    var self = this;
    jQuery.each(this.datesData["serviceDates"], function() {
      if (this.date == selectedDate) {
        self.showTimeSlots(this.timeSlots);
      }
    });
    $("#reschedule_service").addClass("disabled");
  },

  showTimeSlots: function(timeSlots) {
    var self = this;
    var name = 'reschedule_repair_time_preference';

    jQuery.each(timeSlots, function(index, timeslot) {
      var timeSlot = new TimeSlot(name, index, timeslot, function(input_value) {
        self.selectedTime = input_value;
        $("#reschedule_service").removeClass("disabled");
      });
      $(timeSlot.option).appendTo($('#time_slots'));
    });
  },

  getDates: function() {
    var self = this;
    $("#reschedule_repair_time_preference").show();
    var successFunction = function(datesData) {
      self.datesData = datesData;
      self.selectDate.fillDates(datesData["serviceDates"]);
    };
    var errorFunction = function() {
    };
    new SchedulerRequest().httpGet(this.getDatesUrl(), this.createPackageParams(), successFunction, errorFunction, $(this.selectDate.scheduler_calender_container));
  },

  createPackageParams: function() {
    return {'orderNumber': $("#orderId").val(), 'phoneNumber': $("#phoneNumber").val()
      ,'orderUnitNumber' :$("#orderUnitNumber").val(),'zip' :$("#zip").val(),'merchandiseCode' :$("#merchandiseCode").val()};
  },

  rescheduleOrder: function() {
      if ($("#phoneOrder").val() == "true") {
          return this.reschedulePhoneOrder();
      }
      return this.rescheduleOnlineOrder();
  },

  rescheduleOnlineOrder: function(){
    this.populateForm();
    $("#accessOrderForm").attr("action", this.rescheduleOnlineRepairOrderUrl);
    $("#accessOrderForm").submit();
  },

  reschedulePhoneOrder: function(){
    this.populateForm();
    $("#aptFormField").val($("#apt").val());
    $("#addressFormField").val($("#address").val());
    $("#zipFormField").val($("#zip").val());
    $("#lastNameFormField").val($("#customerLastName").val());
    $("#emailAddressFormField").val($("#emailAddress").val());
    $("#merchandiseCodeFormField").val($("#merchandiseCode").val());
    $("#accessOrderForm").attr("action", this.reschedulePhoneRepairOrderUrl);
    $("#accessOrderForm").submit();
  },

  populateForm: function(){
    $("#orderUnitNumberFormField").val($("#orderUnitNumber").val());
    $("#orderIdFormField").val($("#userOrderId").val());
    $("#rescheduleDateFormField").val(this.selectDate.getSelectedDate());
    $("#selectedTimeFormField").val(this.selectedTime);
    $("#phoneNumberFormField").val($("#phoneNumber").val());
  },

  getDatesUrl:function() {
    return this.datesForRepairRescheduleURL;
  },

  datesForRepairRescheduleURL: '/shs/repairRescheduleDateAvailabilityJSON',
  rescheduleOnlineRepairOrderUrl: '/shs/order/repair/online-reschedule',
  reschedulePhoneRepairOrderUrl: '/shs/order/repair/phone-reschedule'

});
var CleanRescheduleDate = Class.create({
  init: function(element) {
    this.element = element;
    new SchedulerUtilities('.reschedule');
  },

  initialize: function() {
    var self = this;
    var name = 'reschedule_clean_time_preference';
    
    this.selectDate = new SelectDate(function(selectedDate) {
      new TimeSlot().resetTimeSlots();
      new SchedulerUtilities('.reschedule');
      jQuery.each(['AM','PM'], function(index, timeslot) {
        var timeSlot = new TimeSlot(name, index, timeslot, function(input_value) {
          self.selectedTime = input_value;
          $("#reschedule_service").removeClass("disabled");
        });
        $(timeSlot.option).appendTo($('#time_slots'));
      })
      $("#reschedule_service").addClass("disabled");
    }, "reschedule_calendar");
    this.getDates();
  },


  getDates: function() {
    //data is array of date strings in yyyy-mm-dd format.
    var self = this;
    var successFunction = function(data) {
      self.selectDate.fillDates(data);
    }
    var errorFunction = function() {}
    new SchedulerRequest().httpGet(this.datesForCleanRescheduleURL, this.selectParams(), successFunction, errorFunction, $(this.selectDate.scheduler_calender_container));
  },

  selectParams: function() {
    return {'orderId': $("#orderId").val()};
  },

  rescheduleOrder: function() {
    $("#orderIdFormField").val($("#orderId").val());
    $("#rescheduleDateFormField").val(this.selectDate.getSelectedDate());
    $("#selectedTimeFormField").val(this.selectDate.selectedTime);
    $("#phoneNumberFormField").val($("#phoneNumber").val());
    $("#accessOrderForm").attr("action", this.rescheduleCleanOrderUrl);
    $("#accessOrderForm").submit();
  },


  getDatesUrl:function() {
    return this.datesForCleanRescheduleURL;
  },

  datesForCleanRescheduleURL: '/shs/cleanDateRescheduleAvailabilityJSON',
  rescheduleCleanOrderUrl: '/shs/order/clean/reschedule'
});
var RescheduleDateHandler = Class.create({
  init: function(element) {
    this.element = element;
    this.initializeErrorHolder();
  },

  initialize: function() {
    var dateHandler = this.createDateHandler();

    if (null != dateHandler) {
      dateHandler.initialize();
      this.bindEvents(dateHandler);
    }
  },

  initializeErrorHolder: function() {
      var self = this;
      self.errorHolder = null;
      self.errorHolder = new ErrorHolder($("#accessOrderForm").find('.warning'));
    },

  bindEvents: function(dateHandler) {
    var self = this;
    $("#reschedule_service").click(function(event) {
      if (!self.isRequestSubmitted) {
        var formValidation = new FormValidation($("#accessOrderForm"), self.errorHolder);
        if (formValidation.hasErrors) {
          event.preventDefault();
          return;
        }
        self.isRequestSubmitted = true;
        dateHandler.rescheduleOrder();
      }
      event.preventDefault();
    });
  },

  createDateHandler:function() {
    var dateHandler = null;
    var serviceType = $("#serviceType").val();
    if ("CLEAN" == serviceType) {
      dateHandler = new CleanRescheduleDate(this.element);
    } else if ("REPAIR" == serviceType) {
      dateHandler = new RepairRescheduleDate(this.element);
    }
    
    return dateHandler;
  },

  getDates: function(callback) {
    //data is array of date strings in yyyy-mm-dd format.
    $.get(this.getDatesUrl(), this.selectParams(), function(data) {
      callback(data);
    }, "json");
  }
});
var CancelHandler = Class.create({
  init: function(element) {
    this.element = element;
    this.serviceType = $("#serviceType").val();
  },

  initialize: function(event) {
    var dateHandler = this.createDateHandler();

    if (null != dateHandler) {
      dateHandler.initialize(event);
    } else {
      // console.log("unknown service type " + this.serviceType)
      // Ignore for now
    }

  },

  createDateHandler:function() {
    var dateHandler = null;

    if ("REPAIR" == this.serviceType) {
      dateHandler = new RepairCancel(this.element);
    } else if ("CLEAN" == this.serviceType) {
      dateHandler = new CleanCancel(this.element);
    } else if ("INSTALL" == this.serviceType) {
      dateHandler = new InstallCancel(this.element);
    }
    return dateHandler;
  }
});
var RepairCancel = Class.create({
  init: function(element) {
    this.element = element;
  },

  initialize: function(event) {
    this.cancel(event);
  },
  
  cancel: function(event) {
     if($("#phoneOrder").val()=="true"){
         this.cancelPhoneOrder(event);
     } else {
         this.cancelOnlineOrder(event);
     }
  },

  cancelOnlineOrder: function(event) {
      this.populateForm();
      $("#cancelReasonFormField").val($("#cancel_reason").val());
      $("#accessOrderForm").attr("action", this.cancelOnlineRepairOrderUrl);
      $("#accessOrderForm").submit();
      event.preventDefault();
  },

  populateForm: function (){
      $("#orderUnitNumberFormField").val($("#orderUnitNumber").val());
      $("#orderIdFormField").val($("#userOrderId").val());
      $("#phoneNumberFormField").val($("#phoneNumber").val());
  },

  cancelPhoneOrder: function(event) {
      this.populateForm();
      $("#aptFormField").val($("#apt").val());
      $("#addressFormField").val($("#address").val());
      $("#zipFormField").val($("#zip").val());
      $("#lastNameFormField").val($("#customerLastName").val());
      $("#merchandiseCodeFormField").val($("#merchandiseCode").val());
      $("#emailAddressFormField").val($("#emailAddress").val());
      $("#accessOrderForm").attr("action", this.cancelPhoneRepairOrderUrl);
      $("#accessOrderForm").submit();
      event.preventDefault();
  },

  cancelOnlineRepairOrderUrl:'/shs/order/repair/online-cancel',

  cancelPhoneRepairOrderUrl:'/shs/order/repair/phone-cancel'


});
var CleanCancel = Class.create({
  init: function(element) {
    this.element = element;
  },

  initialize: function(event) {
    this.cancel(event);
  },
  
  cancel: function(event) {
    $("#orderUnitNumberFormField").val($("#orderUnitNumber").val());
    $("#orderIdFormField").val($("#orderId").val());
    $("#phoneNumberFormField").val($("#phoneNumber").val());
    $("#accessOrderForm").attr("action", this.cancelCleanOrderUrl);
    $("#accessOrderForm").submit();
    event.preventDefault();
  },

  cancelCleanOrderUrl:'/shs/order/clean/cancel'
});
var InstallCancel = Class.create({
  init: function(element) {
    this.element = element;
  },

  initialize: function(event) {
    this.cancel(event);
  },
  
  cancel: function(event) {
    $("#orderIdFormField").val($("#orderId").val());
    $("#phoneNumberFormField").val($("#phoneNumber").val());
    $("#accessOrderForm").attr("action", this.cancelInstallOrderUrl);
    $("#accessOrderForm").submit();
    event.preventDefault();
  },

  cancelInstallOrderUrl:'/shs/order/install/cancel'
});
var InstallationType = Class.create({
  init: function(zipcode, product, installBack) {
    //TODO:use classes to hide/show
    this.productOptionSelect = $('#install_product_options');

    this.productWrapper = $('.product.fieldset_wrap').parents('fieldset');
    this.productWrapper.addClass('faux_hide');

    $('.product_group.fieldset_wrap').parents('fieldset').hide();
    $('.product.fieldset_wrap').parents('fieldset').hide();
    $('.install_product_category.fieldset_wrap').parents('fieldset').show();
    $('#service_date_desc').hide();
    $('#contact_info .county').removeClass("hide_county_field").addClass("show_county_field");
    $('#service_install_question').show();
    $('#scheduler .radio_group_container').hide();

    SchedulerObserver.scheduler.resetHeight($('#step_one'));


    this.zipcode = zipcode;
    this.productCategoriesElement = product;
    this.installBack = installBack;
    this.minTriggerResize = 3;
    this.addOnHeight = 100;
    this.heightIncresdForProductOption = false;
    this.dynamicDescription = "Tell us where you live and the service you want.";
    this.productDynamicDescription = "<strong>Service you trust at a price you can bank on.</strong> We promise to give you a solid, confident estimate for our work -- now and before we begin.";
    $("#dynamicDescription").html(this.dynamicDescription);
    this.appointment = new InstallationAppointment(new SelectDate(function() {
      $('#go_to_step_three').removeClass('disabled');
      $('#go_to_step_three').removeClass('blocked');
      $('#schedule_service').addClass('blocked');
    }));

    this.productOptions = new Array();
    this.productAdOns = new Array();
    this.selectedAddOnItemNumbers = new Array();
    this.schedulerPrepopulator = new SchedulerPrepopulator();
  },

  processProductCategoryChange: function() {
    $('#product').parents('fieldset').show();
    $("#product").parent("div.product").show();
    $('#dynamicDescription').html(this.getDescriptionForProductGroup(this.productCategoriesElement.val()));

    this.populateProducts();
  },

  populateProducts: function() {
    var self = this;
    if ($(this.productCategoriesElement).val() != $(this.productCategoriesElement).attr("title")) {
      this.update(this.installationProductsUrl, this.getParamsForProducts(), function(data) {
        self.jsonForProducts(data);
      });
    }
  },

  isValid: function() {
    return (this.zipcode.val() != null);
  },

  update: function(selectUrl, selectparams, callbackToPopulate) {
    if (this.isValid()) {
      var successFunction = function(data) {
        callbackToPopulate(data);
      };

      var errorFunction = function(installationError) {
        new SchedulerServiceError($.evalJSON(installationError)).display();
      };

      new SchedulerRequest().httpGet(selectUrl, selectparams, successFunction, errorFunction, $('#product'));
    } else {
      callbackToPopulate([]);
    }
  },

  populateProductCategories: function() {
    var self = this;
    this.update(this.installationProductCategoriesUrl, this.getParamsForProductCategories(), function(data) {
      self.jsonForProductCategories(data);
    });
  },

  showTotalPrice: function() {
    var self = this;
    var totalCost = 0;
    if (totalCost != typeof "number") {
      totalCost = 0;
    }
    jQuery.each(this.selectedAddOnItemNumbers, function(index, optionId) {
      var addOnPrice = self.getPriceForAdOn(optionId);
      totalCost = totalCost + addOnPrice;
    });

    totalCost = totalCost + this.getPriceForSelectedProductOption();

    $("#totalPrice").show();
    $("#totalPrice").html("Total cost <p class='price'><em>$</em>" + totalCost.toFixed(2) + "</p>");
    $('#priceForOmnitureTracking').val(totalCost.toFixed(2));
  },

  getDescriptionForProductGroup: function(selectedCategory) {
    var removeMatchingElement = false;
    var productCategory = jQuery.grep(this.productCategories, function(productCategory) {
      return productCategory.name == selectedCategory;
    }, removeMatchingElement);
    return productCategory.length == 0 ? '' : productCategory[0].description;
  },

  getPriceForAdOn: function(optionId) {
    var removeMatchingElement = false;
    var addOn = jQuery.grep(this.productAdOns, function(addOn) {
      return addOn.itemNumber == optionId;
    }, removeMatchingElement);
    return addOn.length == 0 ? 0 : addOn[0].itemPrice;
  },

  getPriceForSelectedProductOption: function() {
    var option = this.getSelectedProductOption();
    return option != null ? option.itemPrice : 0;
  },
  
  getSelectedProductOption: function() {
    var selectedOptionItemNumber = $('#install_product_options').val();
    var removeMatchingElement = false;
    var option = jQuery.grep(this.productOptions, function(option) {
      return option.itemNumber == selectedOptionItemNumber;
    }, removeMatchingElement);

    if (option.length != 0) {
      return option[0];
    }
    return null;
  },

  removeSelectedAddOn:function(itemNumber) {
    var removeMatchingElement = true;
    this.selectedAddOnItemNumbers = jQuery.grep(this.selectedAddOnItemNumbers, function(addOnItemNumber) {
      return addOnItemNumber == itemNumber;
    }, removeMatchingElement);

  },

  setProductOptionsAndAddOns: function(data) {
    this.productOptions = data.options;
    this.productAdOns = data.addOns;
  },

  showProductOptionsAndDescription: function(options) {
    var productOptions = new Select($("#install_product_options"));
    productOptions.populateWith(options, 'itemNumber', 'shortDescription', 'Product options', 'Product options');
    $("#dynamicDescription").html(this.productDynamicDescription);
    $('#installation_add_ons').html('');


    if (productOptions.forceChangeEventForSingleOption(true) > 1) {
      $(this.productOptionSelect).show();
    } else {
      $(this.productOptionSelect).hide();
    }


  },

  showProductAddOns: function(addOns) {
    var self = this;
    jQuery.each(addOns, function(index, addOn) {
      var addOn = new AddOn(name, index, addOn, function(itemNumber, isSelected) {
        $('#go_to_step_three').removeClass('disabled');
        $('#go_to_step_three').removeClass('blocked');
        $('#schedule_service').addClass('blocked');
        if (isSelected) {
          self.selectedAddOnItemNumbers.push(itemNumber);
        } else {
          self.removeSelectedAddOn(itemNumber);
        }
        self.showTotalPrice();
      });
      $(addOn.checkBoxGroup).appendTo($('#installation_add_ons'));
      // Needed to change up styles to fit in water heater options
      if ($('#install_product_category').val() == 'Water Heater') {
        $('#installation_add_ons').addClass('small_option_view');
      } else {
        $('#installation_add_ons').removeClass('small_option_view');
      }
    });
  },

  jsonForProductItems: function(data) {
    this.setProductOptionsAndAddOns(data);
    this.showProductOptionsAndDescription(data.options);
    this.showProductAddOns(data.addOns);
  },

  jsonForProducts: function(data) {
    var products = new Select($("#product"));
    products.populateWith(data, 'id', 'description', 'Product', 'Product');

    if (products.forceChangeEventForSingleOption(true) > 1) {
      this.productWrapper.removeClass('faux_hide');
    } else {
      this.productWrapper.addClass('faux_hide');
    }
  },

  jsonForProductCategories: function(data) {
    this.productCategories = data;
    new Select(this.productCategoriesElement).populateWith(data, 'name', 'name', 'Product category', 'Product category').forceChangeEventForSingleOption();
    this.schedulerPrepopulator.selectElementAndTriggerChangeForService(this.productCategoriesElement, $("#schedulerInformation_productGroup"));
  },

  register: function() {
    this.populateProductCategories();
    this.observe();
    this.observeScheduleService();
  },

  observeScheduleService: function() {
    var self = this;
    $("#schedule_service").unbind("click.install").bind("click.install", function() {
      var validation = new FormValidation($('#contact_info'), schedulerStep3ErrorHolder);
      if (!validation.hasErrors && !self.isRequestSubmitted) {
        self.isRequestSubmitted = true;
        new InstallationRequest(self.zipcode, self.getSelectedOptionItemNumber(), self.selectedAddOnItemNumbers, self.appointment.selectDate, self.addToCart).createOrder();
      }
      return false;
    });
  },

  getSelectedOptionItemNumber: function() {
    return this.getSelectedProductOption() != null ? this.getSelectedProductOption().itemNumber : null;
  },

  reset: function() {
    $(this.productOptionSelect).show();
    this.productWrapper.removeClass('faux_hide');

    $('.install_product_category.fieldset_wrap').parents('fieldset').hide();
    $('.install_product_options.fieldset_wrap').parents('fieldset').hide();
    $('#contact_info .county').removeClass("show_county_field").addClass("hide_county_field");

    $('.addons_group_container').hide();
    $('#product').unbind('change.install');
    $("#totalPrice").html("");
    $('#service_date_desc').show();
    $('#service_install_question').hide();
    $('#scheduler .radio_group_container').show();
    this.productCategoriesElement.unbind('change.install');
    $('#install_product_options').unbind('change.install');
    this.installBack.unbind('click.install');
    new SchedulerRequest().cancelPriorRequest();
    $("#schedule_service").unbind("click.install");
    this.appointment.reset();
    $("#email").addClass("js_required"); //toggle for CIR
  },

  observe: function() {
    var self = this;
    this.productCategoriesElement.unbind('change.install').bind('change.install', function() {
      $('.product.fieldset_wrap').parents('fieldset').hide();
      $('.addons_group_container').hide();
      self.processProductCategoryChange();
      $("#install_product_details").show();
    });
    this.installBack.unbind('click.install').bind('click.install', function() {
      $("#scheduler_wrapper").show();
      return false;
    });

    $('#product').unbind('change.install').bind('change.install', function() {
      self.showProductItems();
    });
    $('#install_product_options').unbind('change.install').bind('change.install', function() {
      self.showTotalPrice();
    });
    this.appointment.initialize();
  },

  showProductItems:function() {
    var self = this;
    self.selectedAddOnItemNumbers.length = 0;

    $("#dynamicDescription").html(this.productDynamicDescription);
    $('.install_product_options.fieldset_wrap').parents('fieldset').show();
    $('.addons_group_container').show();

    this.update(this.installationProductItemsUrl, this.getParamsForProductItems(), function(data) {
      self.jsonForProductItems(data);
    });

  },

  getParamsForProductCategories: function() {
    return {'zipCode': this.zipcode.val()};
  },

  getParamsForProductItems: function() {
    return {'zipCode': this.zipcode.val(), 'productNumber': $('#product').val()};
  },

  getParamsForProducts: function() {
    return {'categoryName': this.productCategoriesElement.val()};
  },



  installationProductCategoriesUrl: '/shs/installationProductCategories',
  installationProductsUrl: '/shs/installationProductsJSON',
  installationProductItemsUrl: '/shs/installationProductsItemsJSON'
});

var InstallationRequest = Class.create({
  init: function(zipcode, selectedOptionItemNumber, selectedAddOnItemNumbers, selectDate, addToCart) {
    this.zipcode = zipcode;
    this.selectedAddOnItemNumbers = selectedAddOnItemNumbers;
    this.selectedOptionItemNumber = selectedOptionItemNumber;
    this.selectDate = selectDate;
    this.addToCart = addToCart;
  },

  createOrder: function() {
    var self = this;
    var errorFunction = function(installationError) {
      new SchedulerServiceError($.evalJSON(installationError)).display();
    };
    var schedulerRequest = new SchedulerRequest();
    var orderParams = this.createOrderParams();
    if (this.addToCart) {
      var successAddToCartResponseHandler = function(data) {
        self.processAddToCartResponse(data);
      };
      new SchedulerRequest().httpPost(this.addInstallOrderToCartUrl, orderParams, successAddToCartResponseHandler, errorFunction, $('#schedule_service'));
      return false;
    }
    var successCreateOrderResponseHandler = function(data) {
      self.processOrderResponse(data);
    };
    new SchedulerRequest().httpPost(this.createInstallOrderUrl, orderParams, successCreateOrderResponseHandler, errorFunction, $('#schedule_service'));
    return false;
  },

  processAddToCartResponse:function(data) {
      window.location.href = data.redirectUrl;
      return;
  },

  processOrderResponse:function(data) {
    if (data.orderId) {
      this.successfullOrder(data);
    } else {
      //alert("Errors: " + data);
    }
  },

  createOrderParams: function() {
    return {'zipCode': this.zipcode.val(),
      'selectedDate': this.selectDate.getSelectedDate(),
      'productNumber': $("#product").val(),
      'productName': $("#product :selected").text(),
      'optionItemNumber': this.selectedOptionItemNumber,
      'addOnItemNumbers': $.toJSON(this.selectedAddOnItemNumbers),
      'firstName': $("#first_name").val(),
      'lastName': $("#last_name").val(),
      'phone': $("#phone").val(),
      'email': $("#email").val(),
      'optForEmail': $("#optForEmail").attr("checked") ? $("#optForEmail").val() : "N",
      'address': $("#address").val(),
      'city': $("#city").val(),
      'state': $("#state").val(),
      'county': $("#county").val(),
      'notes' : ($("#notes").val() != $("#notes").attr('title'))? $("#notes").val():""
    };
  },

  successfullOrder: function(data) {
    $("#successfullOrderForm").attr("action", this.orderSuccessfullyCreated);
    $("#successfullOrderForm").submit();
  },

  createInstallOrderUrl: '/shs/createInstallationOrder',
  addInstallOrderToCartUrl: '/shs/addInstallationOrderToCartJSON',
  orderSuccessfullyCreated: '/shs/order/installation/confirmation'
});
var InstallationAppointment = Class.create({
  init: function(selectDate) {
    this.selectDate = selectDate;
  },

  initialize: function() {
    this.getDates();
  },

  getDates: function() {
    new TimeSlot().resetTimeSlots();

    var self = this;
    var successFunction = function(datesData) {
      self.selectDate.fillDates(datesData);
    };

    var errorFunction = function() {
    };
    new SchedulerRequest().httpGet(this.availableDatesUrl, {}, successFunction, errorFunction, $(this.selectDate.scheduler_calender_container));
  },

  reset: function() {
    $("#scheduler_calendar").datepicker('destroy');
  },

  availableDatesUrl: '/shs/installDateAvailabilityJSON'
});
var TimeSlot = Class.create({
  init: function(name, index, timeslot, callback) {
    this.select = $(document).find('#time_slots');
    this.time_slot_option = $(this.select).find('.time_slot');

    var option = this.buildOption(name, timeslot, index);

    this.option = $(option);

    if (typeof callback != 'undefined') {
      this.attachSelectionObserver(option);
      this.attachCallbackObserver(option, callback);
    }

    if ($(this.select).children().length > 0) {
      $(this.select).show();
      $(this.select).trigger('change');
    }
  },

  resetTimeSlots: function() {
    $(this.time_slot_option).remove();
    $(this.select).val($(this.select).children()[0]);
    $(this.select).hide();
    $(this.select).trigger('change');
  },

  buildOption: function(name, timeslot, index) {
    var timeSlotId = 'timeslot_' + index;
    var option = document.createElement('option');

    $(option).attr('id', timeSlotId);
    $(option).attr('name', name);
    $(option).addClass('time_slot');
    $(option).val(timeslot);
    $(option).html(timeslot);

    return $(option);
  },

  attachSelectionObserver: function(option) {
    $(this.select).change(function() {
      if ($(this).val() != $(this).attr('title')) {
        $('#go_to_step_three').removeClass('disabled').removeClass('blocked');
      } else {
        $('#go_to_step_three').addClass('disabled').addClass('blocked');
      }
    });
  },

  attachCallbackObserver: function(option, callback) {
    $(this.select).change(function() {
      callback($(this).val());
    });
  }
});

var AddOn = Class.create({
  init: function(name, index, addOn, callback) {
    var input = this.buildInput(name, index, addOn);
    var price = this.buildPrice(name, index, addOn);
    var label = this.buildLabel(index, addOn);
    var checkBoxGroup = this.buildAddOnGroup(index, input, label, price);

//    this.attachSelectionObserver(input);
    this.attachCallbackObserver(input, callback);

    this.checkBoxGroup = $(checkBoxGroup);
  },

  buildPrice: function(name, index, addOn) {
    var span = $('<span>$' + addOn.itemPrice.toFixed(2) + '</span>');
    return $(span);
  },

  buildInput: function(name, index, addOn) {
    var addOnId = 'addOn_' + index;

    var input = $('<input name="' + name + '" type="checkbox"/>');
    $(input).attr('id', addOnId);
    $(input).attr('value', addOn.itemNumber);
    return $(input);
  },

  buildLabel: function(index, addOn) {
    var addOnId = 'addOn_' + index;

    var label = document.createElement('label');
    $(label).attr('for', addOnId);
    $(label).text(addOn.question);

    return $(label);
  },

  buildAddOnGroup: function(index, input, label, price) {
    var radioGroup = document.createElement('div');
    $(radioGroup).attr('id', 'addOnGroup_' +  index);
    $(radioGroup).addClass('installation_add_on');
    $(input).appendTo(radioGroup);
    $(label).appendTo(radioGroup);
    $(price).appendTo(radioGroup);

    return $(radioGroup);
  },

  attachSelectionObserver: function(input) {
    $(input).change(function() {
      $('.radio_group').removeClass('selected');
      $(this).parent('.radio_group').addClass('selected');
    });
  },

  attachCallbackObserver: function(input, callback) {
    $(input).click(function() {
       callback($(this).val(), this.checked);
    });
  }
});

var SchedulerServiceError = Class.create({
  init: function(response) {
    this.response = response;
  },

  build: function() {
    $("#error_text").text(this.response.message);
    $("#error_phone").text(this.response.phoneNumber);
    $("#error_title").text(this.response.title);
    $("#well_call_you").attr('href', this.response.serviceUrl);
    $("#click_to_call").attr('href', this.response.serviceUrl);
    if(this.response.serviceType=="INSTALLATION"){
      $("#error_time").text("Monday through Friday : 8AM - 10PM EST Saturday: 9AM - 8PM EST Sunday: 10AM - 8PM EST");
    }
    $("#well_call_you").addClass("js_click_to_call");
    $("#click_to_call").addClass("js_click_to_call");
  },

  swap: function() {
    if($('#step_one').hasClass('short_step')){
      SchedulerObserver.scheduler.next($('#go_to_step_two'));
    }
    $("#error_message").show();
    var wrapper = $("#error_message").siblings('.wrapper').get(0);
    $(wrapper).hide();
  },

  attachClickToCallObserver: function() {
    new UIObserver.attachClickToCall();
  },

  display: function() {
    this.build();
    this.swap();
    this.attachClickToCallObserver();
    OmnitureCall.reportServiceDown();    
  }
});
var RepairSchedulerServiceError = Class.create(SchedulerServiceError.prototype, {
  build: function() {
    this.sup();
    if ($("#warranty").find(':selected').attr("phonesupport") == "false") {
        $("#scheduler .click_to_chat_optional").show();
      //show default number
    } else {
      this.resetClickToCall();
      $("#scheduler .click_to_chat_optional").hide();
      $("#well_call_you").attr('href', this.response.serviceUrl);
      $("#click_to_call").attr('href', this.response.serviceUrl);
      $("#error_phone").text(RepairSelectPackage.callUsNumber);
    }
  },
  resetClickToCall: function() {
    $("#click_to_call.js_click_to_call").each(function(index,element) {
      if(typeof element.js_attached == 'undefined') {
        element.js_attached = {};
      }
      element.js_attached.js_click_to_call = false;
    });
  }
});
var Zipcode = {};
Zipcode.isValid = function(zipcode) {
  return !isNaN(zipcode)  && zipcode.length == 5;
};

Zipcode.isValidWithExtension = function(zipcode) {
  var elements = zipcode.split("-");
  var zip = elements[0];

  if (elements.length == 1) {
    return !isNaN(zip) && zip.length == 5;
  } else if (elements.length == 2) {
    var zipPlus4 = elements[1];
    return !isNaN(zip) && zip.length == 5 && !isNaN(zipPlus4) && zipPlus4.length == 4;
  }
  return false;
};
var ToggleAjaxResponse = Class.create({
  init: function(element) {
    var content = $(element).siblings('.ajax_response');
    
    if($(element).hasClass('hide_toggle')) {
      this.toggleToHide(element, content);
    } else {
      this.toggleToShow(element, content);
    }
  },
  
  toggleToShow: function(element, content) {
    $(element).text('- Hide');  
    $(element).addClass('hide_toggle');
    
    this.toggleAjaxContent(element, content);
  },
  
  toggleToHide: function(element, content) {
    $(element).text('+ Show more');
    $(element).removeClass('hide_toggle');
    
    this.toggleAjaxContent(element, content);
    
    // In case Ajax response hangs
    if($(element).hasClass('ajax_loading')) {
      $(element).removeClass('ajax_loading');
    }
  },
  
  toggleAjaxContent: function(element, content) {
    if($(content).html() == '') {
      $(element).addClass('ajax_loading');
      $.ajax({
        type: "GET",
        url: $(element).attr('href'),
        success: function updateMore(response) {
          $(content).html(response);
          $(element).removeClass('ajax_loading');
          $(content).toggle();
        }
      });
    } else { 
      $(content).toggle();
    }      
  }
});
var AnswerPaginationAjax = Class.create({
  init: function(element) {
    var self = this;
    
    //added an each iterator to make sure this works for all select dropdowns
    $(element).each(function(e,i){
    	$(e).click(function(event) {
    		self.getAjaxResponse(e);
    		event.preventDefault();
    	});
    });
    
  },
  getAjaxResponse: function(element) {
    $.ajax({
      type: "GET",
      url: $(element).attr('href'),
      success: function(response) {
        $('#answers').replaceWith(response);
        new UIObserver.attachAnswerPaginationAjax();
      }
    });
  }
});
var SchedulerService = {};

SchedulerService.productNameForService = function(service) {
  var all_services = {installation : "install_product_category",
    repair : "productGroup",
    cleaning : "product",
    home_improvement : "product"};
  var selected_option = $("#" + all_services[service]).find("option:selected");
  if (selected_option.val() != "")
    return selected_option.text();
};
var FilterSearchResults = Class.create({
  init: function(element) {
    this.element = $(element);
    this.filter_container = $(element).find('.filter_container');
    this.filter = $(element).find('.filter');
    this.search_results = $(element).find('.search_results');
    this.results = $(element).find('.result');
    this.spinner = $(element).find('.spinner');
  
    // set up
    this.setFilters();
  },
  
  bindEvents: function() {
    var that = this;

    $(this.filter).each(function() {
      $(this).change(function() {
        var serviceOption = $('.services').val();
        var productOption = $('.products').val();
        that.filterResults(serviceOption, productOption);
      });
    });
  },

  filterResults: function(serviceOption, productOption) {
    var that = this;
    var search = '?search=' + jQuery.url.param("search");
    var service = '&service=' + serviceOption;
    var product = '&product=' + productOption;
    var ajax = "&ajax=true";
    var new_search = jQuery.url.attr("path") + search + service + product + ajax;

    that.showSpinner();

    $.ajax({
      type: "GET",
      url: new_search,
      success: function(response) {
        $(that.search_results).html(response);
        that.hideSpinner();
        if(isIE6()) {
          that.resizeHeightForIE6();
        }
      }
    });
  },

  setFilters: function() {
    var that = this;

    if(this.results.length <= 1) {
      that.hideFilters();
    } else {
      that.bindEvents();
    }
  },
  
  hideFilters: function() {
    $(this.filter_container).hide();
  },
  
  showSpinner: function() {
    $(this.spinner).show();
  },
  
  hideSpinner: function() {
    $(this.spinner).hide();
  },
  
  resizeHeightForIE6: function() {
    var sidebar = $(document).find('#sidebar');
    
    var searchResultsHeight = $(this.element).height();
    var sidebarHeight = $(sidebar).height();
    var newHeight = sidebarHeight + 70;
    
    if(searchResultsHeight < sidebarHeight) {
      $(this.element).height(newHeight);
    } else {
      $(this.element).height(searchResultsHeight);
    }
  }
});
var UpdateProductsList = Class.create({
  init: function(element) {
    this.products_list = $(element).parents().find('.products');
    this.services_list = $(element);
    this.spinner = $(element).parents().find('.spinner');
  
    // set up
    this.bindEvents(element);
  },
  
  bindEvents: function(element) {
    var that = this;

      $(element).change(function() {
        var serviceOption = $('.services').val();
        var productOption = $('.products').val();
        that.update_products_list(serviceOption, productOption);
    });
  },

  update_products_list: function(selectedService, selectedProduct) {
    var that = this;
    var search = '?search=' + jQuery.url.param("search");
    var service = '&service=' + selectedService;
    var product = '&product=' + selectedProduct;
    var ajax = "&ajax=true";
    var update_products_list = jQuery.url.attr("path") + "!updateProductsList" + search + service + product + ajax;
    that.showSpinner();

    $.ajax({
      type: "GET",
      url: update_products_list,
      success: function(response) {
        $(that.products_list).html(response);
        that.products_list.val(selectedProduct);
        new UIObserver.attachFilterSearchResults();
        that.hideSpinner();
      }
  });
  },

  showSpinner: function() {
    $(this.spinner).show();
  },
  
  hideSpinner: function() {
    $(this.spinner).hide();
  }
});
var CancelDialog = Class.create({
  init:function() {
    this.cancel_dialog = $('#cancel_dialog');
    
    $("#cancel_ctc").hide();
    $("#cancel_dialog_default_message").hide();
    $(this.cancel_dialog).dialog({width:450, modal:true});
  },

  show:function() {
    if($("#productServiceType").val() == 'REPAIR') {
      this.initializeCancelPrevention();
    }else{
      this.showDefaultMessage();
      this.displayDialog();
    }
  },

  initializeCancelPrevention:function() {
    var self = this;

    var successFunction = function(data) {
      var cancelPrevention = data;
      if(cancelPrevention.message != '') {
        $("#cancel_dialog_product_message").html(cancelPrevention.message);
        self.showProductMessage();
      }else{
        self.showDefaultMessage();
      }
      $("#cancel_ctc_url").attr('href',cancelPrevention.clickToCallServiceUrl);
      $("#cancel_ctc_number").html(cancelPrevention.clickToCallNumber);

      if(cancelPrevention.displayClickToCall) {
        $("#cancel_ctc").show();
      }
      self.displayDialog();
    };

    var errorFunction = function(){
      self.showDefaultMessage();
      self.displayDialog();
    };

    new SchedulerRequest().httpGet(this.cancelPreventionUrl, this.getParams(), successFunction, errorFunction);
  },

  getParams: function() {
    return {
      'merchandiseCode':$("#productMerchandiseCode").val()
    };
  },


  displayDialog: function() {
    $("#cancel_dialog").dialog('open');
  },

  showProductMessage: function() {
    $("#cancel_dialog_product_message_holder").show();
    $("#cancel_dialog_default_message").hide();
  },

  showDefaultMessage: function() {
    $("#cancel_dialog_product_message_holder").hide();
    $("#cancel_dialog_default_message").show();
  },

  cancelPreventionUrl:"/shs/cancellationPreventionJSON"

});



var CancelReason = Class.create({
  init: function(accept) {
    this.accept = accept;
  },

  send: function() {
    if (!$("#submit_cancel_reason").hasClass('disabled') || !this.accept) {
      var self = this;
      var successFunction = function(data) {
        OmnitureCall.reportCancelSubmitReasonEvent(self.getReasons());
      };
      var errorFunction = function(data) {
        // do nothing
      };
      if (this.getEvaluatedReason() != '') {
        new SchedulerRequest().httpGet(this.cancelReasonUrl, this.getParams(), successFunction, errorFunction);
      }
      $("#cancelled_service_questions").hide();
    }
  },

  getParams: function() {
    return {
      'orderId':$("#orderId").val(),
      'orderUnitNumber':$("#orderUnitNumber").val(),
      'phoneNumber':$("#phoneNumber").val(),
      'cancelReason': this.getEvaluatedReason()
    };
  },

  getEvaluatedReason: function() {
    if (this.accept) {
      return this.getReasons();
    }
    return 'None';
  },

  getReasons:function() {
    var reason = '';
    reason += $("#reason1").attr("checked") ? $("#reason1").val() + "," : '';
    reason += $("#reason2").attr("checked") ? $("#reason2").val() + "," : '';
    reason += $("#reason3").attr("checked") ? $("#reason3").val() + "," : '';
    reason += $("#reason4").attr("checked") ? $("#reason4").val() + "," : '';
    reason += $("#reason5").attr("checked") ? $("#reason5").val() + "," : '';
    reason += $("#reason6").attr("checked") ? $("#reason6").val() + "," : '';
    reason += $("#reason7").attr("checked") ? $("#reason7").val() + "," : '';
    reason += $("#reason8").attr("checked") ? $("#reason8").val() + "," : '';
    if ($("#other_reason").val() != $("#other_reason").attr('title')) {
      reason += $("#other_reason").val() + ",";
    }
    return this.sanitize(reason);
  },

  sanitize:function(data) {
    if (data.length > 512) {
      data = data.substring(0, 511);
    }
    if (data.charAt(data.length - 1) == ',') {
      data = data.substring(0, data.length - 1);
    }
    return data;
  },

  updateSubmitStatus: function() {
    if (this.getReasons() != '') {
      $("#submit_cancel_reason").removeClass('disabled');
    }
    else {
      $("#submit_cancel_reason").addClass('disabled');
    }
  },

  cancelReasonUrl:"/shs/cancellationReasonJSON"
});
var BannerAnimation = Class.create({
  init: function(element) {
    this.items = $(element).children('.banner_item');
    this.initialSetUp(element);
  },
  
  initialSetUp: function(element) {
    // constants 
    this.delayTime = 5000;
    this.animationSpeed = 500;
    this.currentItem = 0;
    this.timeoutID = {};
    
    if(this.items.length > 1) {
      this.bindEvents(element);
      this.showItem(this.items[this.currentItem],true);
    } else { 
      $(this.items[this.currentItem]).show();
    }
  },
  
  getNextItem: function() {
    this.currentItem = (this.currentItem+1) % this.items.length;
    return this.items[this.currentItem]
  },
  
  showItem: function(item,firstItem) {
    $(item).css('opacity', (firstItem) ? 1:0);
    $(item).show();
    if(firstItem){
      this.triggerTimeout(this,item)
    } else {
      this.fadeIn(item);
    }
  },
  
  hideItem: function(item) {
    this.fadeOut(item);      
  },
  
  triggerTimeout:function(that,item) {
    that.timeoutID=setTimeout(function() {     
       that.hideItem(item);
    }, that.delayTime);
  },
  
  fadeIn:function(item) {
    var that = this; 
    $(item).addClass('fade_in');
    $(item).animate({opacity:1}, this.animationSpeed, 'swing', function(){
      $(item).removeClass('fade_in');
      that.triggerTimeout(that,item);
    });
  },
  
  fadeOut:function(item) {       
    var that = this;
    $(item).addClass('fade_out');
    $(item).animate({opacity:0}, this.animationSpeed, 'swing', function() {
      $(item).removeClass('fade_out');      
      $(that.items).hide();
      that.showItem(that.getNextItem());
    });
  },
  
  stopAnimation:function() {
    var currentItem = $(this.items[this.currentItem]);
    $(currentItem).css('opacity', 1);
    $(currentItem).stop();    
    clearTimeout(this.timeoutID);
  },
  
  resumeAnimation:function(){
    var currentItem = $(this.items[this.currentItem]);
    if(currentItem.hasClass('fade_out')) {
      this.fadeOut(currentItem);
    } else if(currentItem.hasClass('fade_in')) {
      this.fadeIn(currentItem);
    } else {
      this.triggerTimeout(this,currentItem);
    }
  },
  
  bindEvents: function(element) {
    var that = this;
    $(element).hover(
      function() {
        that.stopAnimation();   
      },
      function() {
        that.resumeAnimation();
      }
    );
  }
});
var OmniturePageInformation = Class.create({
  init: function(pageName, channel, category, pageType) {
    this.pageName = pageName;
    this.channel = channel;
    this.category = category;
    this.pageType = pageType;
  },

  getCategoryForSearchPages:function() {
    var category = "Search";
    if (!this.isSearchOrHome(OmnitureReport.pageInformation.pageName)) {
       category = "Srch " + OmnitureReport.pageInformation.category;
    }
    this.category = category;
    return category;

  },

  isSearchOrHome:function(pageName) {
    var searchHomes = new Array('Home', "Search");
    return (jQuery.inArray(pageName, searchHomes) > -1);
  },

  getPageNameForSearch:function() {
    var pageName = "Search";
    if (!this.isSearchOrHome(OmnitureReport.pageInformation.pageName)) {
        pageName = "Search: " + this.getCategoryForSearchPages();
    }
    this.pageName = pageName;
    return pageName;
  }
});
var OmnitureReport = Class.create({
  init: function(properties) {
    OmnitureReport.clearEventsAndEvars();
    this.addProperties(properties);
    OmnitureReport.submit();
  },

  addProperties: function(properties) {
    for (name in properties) {
      this.addProperty(name, properties[name]);
    }
  },

  addProperty: function(name, value) {
    var allowedProperties = this.getAllowedProperties();
    if (jQuery.inArray(name, allowedProperties) != -1) {
      if (name == 'pageName') {
        s[name] = this.formatPageName(value);
      } else {
        s[name] = value;
      }
    }
  },

  formatPageName: function(pageName) {
    return 'Sears Home Services > ' + pageName;
  },

  getAllowedProperties: function() {
    return OmnitureReport.allowedProperties;
  }
});

OmnitureReport.clearEventsAndEvars = function() {
  jQuery.each(this.allowedProperties, function() {
    s[this] = null;
  });
}

OmnitureReport.allowedProperties = ["pageName", "channel", "campaign", "events", "state", "zip", "eVar1", "eVar2",
  "eVar4", "eVar5", "eVar6", "eVar7", "eVar8", "eVar9", "eVar10", "eVar11","eVar12",  "eVa13", "eVar14", "eVar15",
  "eVar16"," eVar17", "eVar18", "eVar19", "eVar27", "eVar28", "prop1", "prop2", "prop3", "prop4", "prop5","prop6", "prop7", "prop8", "prop9","prop10", "prop11",
  "prop12", "prop13", "prop14", "prop15", "prop16", "prop17","prop18", "prop20", "prop21", "prop23","prop24",
  "prop25", "prop26", "prop27", "prop28", "prop29", "prop37", "products"];

OmnitureReport.submit = function() {
  s_code = s.t();
  if (s_code) {
    document.write(s_code);
  }
}

OmnitureReport.getProperties = function() {
  var properties = {};
  jQuery.each(this.allowedProperties, function() {
    if (typeof s[this] == 'undefined') {
      properties[this] = '';
    } else {
      properties[this] = s[this];
    }
  });
  return properties;
};

OmnitureReport.pageInformation = new OmniturePageInformation("", "", "");
var OmnitureReportSears = Class.create({
  init: function(properties, ajaxSubmit) {

    var ajaxSubmitProperty = this.shouldSubmit(ajaxSubmit);
    OmnitureReportSears.clearEventsAndEvars(ajaxSubmitProperty);
    this.addProperties(properties);

    if (ajaxSubmitProperty) {
      OmnitureReportSears.ajaxSubmit();
    } else {
      OmnitureReportSears.submit();
    }
  },

  shouldSubmit: function(submitProperty) {
    var submit = false;
    if (typeof submitProperty != 'undefined' && submitProperty == true) {
      submit = true;
    }
    return submit;
  },

  addProperties: function(properties) {
    for (name in properties) {
      this.addProperty(name, properties[name]);
    }
  },

  addProperty: function(name, value) {
    var allowedProperties = this.getAllowedProperties();
    if (jQuery.inArray(name, allowedProperties) != -1) {
      sears_s[name] = this.formatPageName(value);
    } else {
      sears_s[name] = value;
    }
  },

  formatPageName: function(pageName) {
    return 'SHS: ' + pageName;
  },

  getAllowedProperties: function() {
    return OmnitureReportSears.allowedProperties;
  }
});

OmnitureReportSears.clearEventsAndEvars = function(ajaxSubmitProperty) {

  if (ajaxSubmitProperty) {
    sears_s['pageName'] = null;
  }

  jQuery.each(this.allowedProperties, function() {
    if ((this != 'pageName') && (this != 'channel')) {
      sears_s[this] = null;
    }
  });
}

OmnitureReportSears.allowedProperties = ['pagename', 'channel', 'prop1', 'prop2','prop15'];

OmnitureReportSears.submit = function() {
  s_code = sears_s.t();
  if (s_code) {
    document.write(s_code);
  }
}

OmnitureReportSears.ajaxSubmit = function() {
  var s_code = sears_s.tl();
}

OmnitureReportSears.getProperties = function() {
  var properties = {};
  jQuery.each(this.allowedProperties, function() {
    if (typeof sears_s[this] == 'undefined') {
      properties[this] = '';
    } else {
      properties[this] = sears_s[this];
    }
  });
  return properties;
};

OmnitureReportSears.pageInformation = new OmniturePageInformation("", "", "");
var OmnitureProfileFields = {

prepareOmnitureParams: function(omnitureData) {
    var completedParameters = '';
    var emptyParameters = '';

    for (var name in omnitureData) {
      if (this.isEmpty(omnitureData[name])) {
        emptyParameters += this.delimitIfNotEmpty(emptyParameters) + name;
      } else {
        completedParameters += this.delimitIfNotEmpty(completedParameters) + name;
      }
    }

    return {
      'prop20': completedParameters,
      'prop21': emptyParameters
    }
  },

  delimitIfNotEmpty: function(value) {
    return this.isEmpty(value) ? '' : ',';
  },

  isEmpty: function(value) {
    return (value == null) || (jQuery.trim(value) == '') ? true : false;
  }

}
var SchedulerRequest = Class.create({
  httpGet: function(resourceUrl, params, successFunction, errorCallBack, elementId) {
    this.makeRequest(resourceUrl, "GET", params, successFunction, errorCallBack, elementId, "json");
  },

  httpPost: function(resourceUrl, params, successFunction, errorCallBack, elementId) {
    this.makeRequest(resourceUrl, "POST", params, successFunction, errorCallBack, elementId, "json");
  },

  httpGetHtml: function(resourceUrl, params, successFunction, errorCallBack, elementId) {
    this.makeRequest(resourceUrl, "GET", params, successFunction, errorCallBack, elementId, "html");
  },

  cancelPriorRequest: function() {
    $.discardPriorRequests();
  },

  defaultErrorHandler : function (errorMessage) {
    new SchedulerServiceError($.evalJSON(errorMessage)).display();
  },

  makeRequest : function(resourceUrl, method, params, successFunction, errorCallBack, elementId, returnType) {
    var errorFunction = function (xmlHttpRequest) {
      errorCallBack(xmlHttpRequest.responseText);
    };

    if (typeof elementId == 'undefined') {
      var wrappedSuccessFunction = successFunction;
    } else {
      var spinner = new AjaxSpinner(elementId);
      var wrappedSuccessFunction = function(data) {
        spinner.hide();
        successFunction(data);
      }
    }
    this.makeAjaxRequest(method, resourceUrl, params, wrappedSuccessFunction, errorFunction, returnType);
  },

  makeAjaxRequest: function(type, resourceUrl, params, sucessFunction, errorFunction, returnType) {
    $.ajaxSync({ type     : type,
      url      : resourceUrl,
      data     : params,
      success  : sucessFunction,
      error    : errorFunction,
      dataType : returnType});
  }
});


var SchedulerPrepopulator = Class.create({
  selectElementAndTriggerChange: function(elementToSelect, elementToPickValueFrom) {
    var elementValue = $(elementToPickValueFrom).val();
    var elementTitle = $(elementToPickValueFrom).attr('title');
    
    if(elementValue != '' && elementValue != elementTitle) {
		  if(isIE6()&&($(elementToSelect).is('select'))) {
		      setTimeout(function(){
			  $(elementToSelect).val(elementValue);
			  $(elementToSelect).trigger('change');
		      },1000);
		  } else {
		      $(elementToSelect).val(elementValue);
		      $(elementToSelect).trigger('change');
		  }
    }
  },

  selectElementAndTriggerChangeForService: function(elementToSelect, elementToPickValueFrom) {
    if ($("#service").val() != $("#schedulerInformation_serviceName").val()) {
      return;
    }
    this.selectElementAndTriggerChange(elementToSelect, elementToPickValueFrom);
  }
})

var GoogleMaps = Class.create({
  init:function(latitude, longitude, id) {
    this.latitude = latitude;
    this.longitude = longitude;
    this.id = id;
  },

  display: function(storeDetails) {
    var map = GoogleMaps.getMap(this.id);
    map.setCenter(new GLatLng(this.latitude, this.longitude));
    map.setZoom(13);
    map.setUIToDefault();
    var storeLocatorPos = new GLatLng(this.latitude, this.longitude);
    map.clearOverlays();
    var marker = this.createMarker(storeLocatorPos, 0, -1);
    map.addOverlay(marker);
    this.addWindowInfo(marker, storeDetails, 0, -1);
  },

  displayWithMultipleMarkers: function(details, zoomLevel, selectIndex) {
    var that = this;
    var map = GoogleMaps.getMap(this.id);
    map.setCenter(new GLatLng(this.latitude, this.longitude));
    map.setZoom(zoomLevel);
    map.setUIToDefault();
    map.clearOverlays();
    $.each(details['location'], function(i, element) {
      var marker = that.createMarker(element, i, selectIndex);
      map.addOverlay(marker);
      that.addWindowInfo(marker, details['info'][i], i, selectIndex);
    });
  },

  displayMultipleMarkers: function(details){
    this.displayWithMultipleMarkers(details, 8);
  },

  displayMultipleMarkersWithIndex: function(details, selectIndex){
    this.displayWithMultipleMarkers(details, 8, selectIndex);
  },

  createMarker: function(latlng, index, selectIndex) {
    var letteredIcon = new GIcon(G_DEFAULT_ICON);
    if (index == selectIndex) {
      letteredIcon.iconSize = new GSize(30, 50);
    }
    // Set up our GMarkerOptions object
    var markerOptions = { icon:letteredIcon };
    var marker = new GMarker(latlng, markerOptions);
    return marker;
  },

  addWindowInfo: function (marker, info, index, selectIndex) {
    marker.bindInfoWindowHtml(info.html());
    if (index == selectIndex) {
      marker.openInfoWindowHtml(info.html());
    }
  }
});

GoogleMaps.all_maps =[];

GoogleMaps.getMap = function(id) {
  if (!GoogleMaps.all_maps[id])
  GoogleMaps.all_maps[id] = new GMap2(document.getElementById(id));
  return GoogleMaps.all_maps[id];
};
var StoreDetailsDialog = Class.create({
  init: function(storeDetails) {
    this.storeDetails = storeDetails;
    this.storeDetailsTemplate = new StoreDetailsTemplate(storeDetails);
  },

  displayDialog:function() {
    var element = $('#store_details');
    this.storeDetailsTemplate.appendStoreDetailsHtml($("#store_info_container"));
    this.storeDetailsTemplate.replaceStoreHolidaysHtml($("#store_info_container .store_holidays_container"));
    var map = new GoogleMaps(this.storeDetails.getLatitude(), this.storeDetails.getLongitude(), "map_canvas");
    this.storeDetailsTemplate.appendMapCalloutHtml($("#store_details_for_map_callout"));
    element.show();
    $(element).dialog({
      close: function(event, ui) {
        if ($("#store_list").dialog('isOpen')) {
          //reloading the inner dialog box so that the radio buttons of that dialog box functions as expected.
          $("#store_list").dialog('close');
          $("#store_list").dialog('open');
        }
      }, width: 720, modal: true
    });
    map.display($("#store_details_for_map_callout"));
    $(element).dialog('open');
  }
})
var StoreDetails = Class.create({
  init: function(storeIndex) {
    this.index = storeIndex;
  },

  getStoreName:function() {
     return $('#storeName_' + this.index).val();
  },

  getStoreType:function() {
     return $('#storeType_' + this.index).val();
  },

  getStreetAddress:function() {
    return $('#streetAddress_' + this.index).val();
  },

  getCity:function() {
   return $('#city_' + this.index).val();
  },

  getState:function() {
    return $('#state_' + this.index).val();
  },

  getZipCode:function() {
    return $('#zipCode_' + this.index).val();
  },

  getDistance:function() {
    return $('#distance_' + this.index).val();
  },

  getPhoneNumber:function() {
      return $('#phoneNumber_' + this.index).val();
  },

  getWeekDayOpenTime:function() {
    return $('#weekDayOpenTime_' + this.index).val();
  },

  getWeekDayCloseTime:function() {
    return $('#weekDayCloseTime_' + this.index).val();
  },

  getSatOpenTime:function() {
    return $('#satOpenTime_' + this.index).val();
  },

  getSatCloseTime:function() {
    return $('#satCloseTime_' + this.index).val();
  },

  getSunOpenTime:function() {
    return $('#sunOpenTime_' + this.index).val();
  },

  getSunCloseTime:function() {
    return $('#sunCloseTime_' + this.index).val();
  },

  getStoreNumber:function() {
    return $('#storeNumber_' + this.index).val();
  },

  getStoreID:function() {
    return $('#storeID_' + this.index).val();
  },

  getLatitude:function() {
    return $('#store_list_latitude_' + this.index).val();
  },

  getLongitude:function() {
    return $('#store_list_longitude_' + this.index).val();
  },

  getHolidays: function() {
    var holidays = [];
    for (var holidayIndex = 0; holidayIndex < this.getHolidayCount(); holidayIndex++) {
      var holiday = { holidayDate: $('#holidayDate_' + this.index + '_' + holidayIndex).val(),
        holidayStartTime: $('#holidayStartTime_' + this.index + '_' + holidayIndex).val(),
        holidayCloseTime: $('#holidayCloseTime_' + this.index + '_' + holidayIndex).val()
      };
      holidays.push(holiday);
    }
    return holidays;
  },

  getHolidayCount:function() {
    return parseInt($('#holidayCount_' + this.index).val());
  },
  getServiceCount:function() {
    return parseInt($('#serviceCount_' + this.index).val());
  }
})
var StoreDetailsTemplate = Class.create({
  init: function(storeDetails) {
    this.storeDetails = storeDetails;
  },

  appendStoreDetailsHtml: function(element) {
    var storeDetailsTemplate = $.template($("#store_info_template").html(), { regx: 'ext' });
    element.empty();
    element.append(storeDetailsTemplate, {
      storeType:this.storeDetails.getStoreType(),
      storeName:this.storeDetails.getStoreName(),
      streetAddress:this.storeDetails.getStreetAddress(),
      city:this.storeDetails.getCity(),
      state:this.storeDetails.getState(),
      zipCode:this.storeDetails.getZipCode(),
      distance:this.storeDetails.getDistance(),
      phoneNumber:this.storeDetails.getPhoneNumber(),
      weekDayOpenTime:this.storeDetails.getWeekDayOpenTime(),
      weekDayCloseTime:this.storeDetails.getWeekDayCloseTime(),
      satOpenTime:this.storeDetails.getSatOpenTime(),
      satCloseTime:this.storeDetails.getSatCloseTime(),
      sunOpenTime:this.storeDetails.getSunOpenTime(),
      sunCloseTime:this.storeDetails.getSunCloseTime(),
      storeNumber:this.storeDetails.getStoreNumber(),
      storeID:this.storeDetails.getStoreID()

    });
  },
  replaceStoreHolidaysHtml: function(element){
    this.replaceTemplateHtml(element, $("#store_holiday_template"), this.storeDetails.getHolidays());
  },

  replaceTemplateHtml: function (targetElement, templateElement,  templateDataCollection) {
    if (templateDataCollection.length == 0) {
      targetElement.hide();
      return;
    }
    targetElement.show();
    var dataContainer = targetElement.children(".container_data");
    dataContainer.empty();
    var templateHtml = $.template(templateElement.html(), { regx: 'ext' });
    for (var templateData in templateDataCollection) {
      dataContainer.append(templateHtml, templateDataCollection[templateData]);
    }
  },

  appendMapCalloutHtml:function(element) {
    var storeDetailsTemplate = $.template($("#map_callout_template").html(), { regx: 'ext' });
    element.empty();
    element.append(storeDetailsTemplate, {
      storeType:this.storeDetails.getStoreType(),
      storeName:this.storeDetails.getStoreName(),
      streetAddress:this.storeDetails.getStreetAddress(),
      city:this.storeDetails.getCity(),
      state:this.storeDetails.getState(),
      zipCode:this.storeDetails.getZipCode()
    });
  }

})
var GeoLocation = Class.create({
  init: function(element) {
    this.element = $(element);
    // Controls
    this.change = $(element).find('.controls .change');
    this.close = $(element).find('.controls .close');
    // Fields
    this.input = $(element).find('.zipcode');
    this.location = $(element).find('.location');
    this.enter_zip = $(element).find('#enter_zipcode');
    this.source_url = $(element).find('.source_url');
    this.geo_location_zipcode = $(element).find('#zipCode_geolocation').html();

    this.setUp();
  },

  setUp: function() {
    if (this.geo_location_zipcode) {
    $.cookie('zipcode', this.geo_location_zipcode, {path:"/"});
    }
    if ($(this.location).children().hasClass('prompt')) {
      this.changeLocation();
      this.indicateZipErrors();
    }

    this.bindEvents();
  },


  bindEvents: function() {
    var that = this;

    $(this.change).click(function(event) {
      if (!$(this).hasClass('disabled')) {
        that.changeLocation();
      }
      event.preventDefault();
    });

    $(this.close).click(function(event) {
      that.closeLocationEdit();
      event.preventDefault();
    });
  },

  indicateZipErrors: function() {
    if ($(this.input).hasClass("invalid_zip")) {
      $(this.input).addClass('field_error');
      new ErrorHolder($(".warning")).add('Invalid zip code.');
    }
  },

  changeLocation: function() {
    $(this.change).addClass('disabled');
    $(this.enter_zip).show();
    $(this.close).show();
    $(this.change).hide();
    $(this.source_url).val(window.location.href);
  },

  closeLocationEdit: function() {
    $(this.change).removeClass('disabled');
    $(this.enter_zip).hide()
    if ($(this.input).hasClass('field_error')) {
      $(this.input).removeClass('field_error');
    }
    $(this.close).hide();
    $(this.change).show();
    if ($(this.warning).is(':visible')) {
      $(this.warning).hide().empty();
    }
  }
});

var RepairOrder = Class.create({

  init:function(selectedProduct, zipcode) {
    this.initialise(selectedProduct, zipcode)
  },

  initialise:function(selectedProduct, zipcode) {
    this.selectedProduct = selectedProduct;
    this.zipcode = zipcode;
  },

  create:function() {
    var self = this;
    var successFunctionHandler = function(data) {
      self.successFunction(data)
    }

    var errorFunction = function(repairError) {
      new RepairSchedulerServiceError($.evalJSON(repairError)).display();
    }
    new SchedulerRequest().httpPost(this.orderUrl, this.orderParams(), successFunctionHandler, errorFunction, $('#schedule_service'));
    return false;
  },



  orderParams: function() {
    return jQuery.extend(this.baseOrderParams(), {
      'searsWarranty': $("#warranty").val(),
       'brand': $("#brand").val()
    }, this.selectedProduct.getOrderParams());
  },

  successFunction:function(data) {
    if (data.orderId) {
      this.successfullOrder(data);
    }
  },

  baseOrderParams:function() {
    return {'zipCode': this.zipcode.val(),
      'firstName': $("#first_name").val(),
      'lastName': $("#last_name").val(),
      'phoneNumber': $("#phone").val(),
      'alternatePhoneNumber':$("#secondary_phone").val(),
      'email': ($("#email").val() != $("#email").attr('title')) ? $("#email").val(): "",
      'optForEmail': $("#optForEmail").attr("checked") ? $("#optForEmail").val() : "N",
      'streetLine1': $("#address").val(),
      'city': $("#city").val(),
      'state': $("#state").val(),
      'problemDescription': $("#in_home_problem_description").val(),
      'specialInstructions' : ($("#notes").val() != $("#notes").attr('title')) ? $("#notes").val() : "",
      'merchandiseCode': this.selectedProduct.product.val()
    };
  },

  successfullOrder: function(data) {
    $("#successfullOrderForm").attr("action", this.orderSuccessfullyCreated);
    $("#successfullOrderForm").submit();
  },

  orderUrl:'/shs/createRepairOrderJSON',
  orderSuccessfullyCreated: '/shs/order/repair/confirmation'



});
var CarryInRepairOrder = Class.create(RepairOrder.prototype, {

  init:function(selectedRepairProduct, zipcode) {
    this.initialise(selectedRepairProduct, zipcode);

  },

  initialise:function(selectedProduct, zipcode) {
    this.sup(selectedProduct, zipcode)
  },

  successFunction: function(data) {
    this.successfullOrder(data)
  },


  successfullOrder: function(data) {
    $("#successfullOrderForm").attr("action", this.orderSuccessfullyCreated);
    $("#successfullOrderForm").submit();
  },

  collectCarryInNatureOfProblems: function() {
    var fieldset = $('#problem_description').children('.select_flyout_option');
    var problems = '';
    $(fieldset).each(function() {
      if ($(this).children('input').attr('checked') == true) {
        var nop = $(this).children('label').html();
        if (nop == 'Other :') {
          var otherDetails = $(this).children('input[type=text]');
          if (otherDetails.val() != otherDetails.attr('title'))
            nop += otherDetails.val();
        }
        problems += nop + ';';
      }
    });
    return problems;
  },
  
  orderParams: function() {
    var self = this;
    return jQuery.extend(this.baseOrderParams(),{
      "storeNumber" : $('#schedulerInformation_storeNumber').val(),
      "carryInPrice" : self.selectedProduct.selectedPackage.minimumService,
      'problemDescription': self.collectCarryInNatureOfProblems()
    });
  },

  orderUrl:'/shs/createCarryInRepairOrderJSON',
  orderSuccessfullyCreated: '/shs/order/carryin/confirmation'
});
var AddToCartRepairOrder = Class.create(RepairOrder.prototype,{

  init:function(selectedRepairProduct,zipcode){
   this.initialise(selectedRepairProduct,zipcode);
  },

  initialise:function(selectedProduct, zipcode) {
    this.sup(selectedProduct, zipcode)
  },

  successFunction: function(data){
    window.location.href = data.redirectUrl;
    return;
  },

  orderUrl:'/shs/addRepairOrderToCartJSON'
});
// Form validation
var FormValidation = Class.create({
  init: function(form, errorHolder) {
    this.hasErrors = false;
    this.container = form;
    if (typeof errorHolder == 'undefined') {
      this.errorHolder = false;
    } else {
      this.errorHolder = errorHolder;
    }

    this.validate();
  },

  validate: function() {
    this.removeErrors();

    var fields = this.getFields();
    var self = this;
    $(fields).each(function() {
      for (var rule in self.validationRules) {
        if (self.validationRules.hasOwnProperty(rule)) {
          self.validationRules[rule]($(this), self);
        }
      }
    });

  },

  getLabel: function(field) {
    if ($('label[for=' + field.attr('id') + ']').length) {
      return $('label[for=' + field.attr('id') + ']').text().replace('*', '')
    }
  },

  getFields: function() {
    var enabled_fields = this.getFieldSelector();
    var fields = $(this.container).find(enabled_fields);
    return fields;
  },

  getFieldSelector: function() {
    var selector = "";
    var tags = ["input", "select", "textarea"];

    var self = this;
    jQuery.each(tags, function(i, tag) {
      for (var rule in self.validationRules) {
        if (rule == 'numbersOnly') {
          rule = "numbers_only";
        }
        selector += tag + '.' + 'js_' + rule + ':enabled,';
      }
    });
    return selector.substring(0, (selector.length - 1));
  },

  removeErrors: function() {
    var enabled_fields = this.getFieldSelector();
    var self = this;
    $(this.container).find(enabled_fields).each(function() {
      self.removeErrorClass($(this));
    });
    if (this.errorHolder != false) {
      this.errorHolder.clear();
    }
    this.hasErrors = false;
  },

  addError: function(field, message, self) {
    self.addErrorClass(field);
    if (this.errorHolder != false) {
      self.errorHolder.add(message);
    }
    self.hasErrors = true;
  },

  addErrorClass: function(field) {
    var parent = $(field).parent();

    if($(parent).hasClass('input_container')) {
      $(parent).addClass('field_error');
    }
    if($(parent).hasClass('textarea_container')) {
      $(parent).addClass('field_error');
    } else {
      $(field).addClass('field_error');
    }
  },

  removeErrorClass: function(field) {
    var parent = $(field).parent();

    if($(parent).hasClass('input_container')) {
      $(parent).removeClass('field_error');
    }
    if($(parent).hasClass('textarea_container')) {
      $(parent).removeClass('field_error');
    } else {
      $(field).removeClass('field_error');
    }
  },

  validationRules: {
    required: function(field, self) {
      if (field.hasClass('js_required')) {
        switch (field.attr('type')) {
          case 'checkbox':
            if (!field.attr('checked')) {
              self.addError(field, self.getLabel(field) + ' is required.', self);
            }
            break;
          case 'select-one':
            if ((field.val() == '') || (field.val() == field.attr('title'))) {
              self.addError(field, self.getLabel(field) + ' is required.', self);
            }
            break;
          case 'text':
          default:
            if ((field.val() == '') || (field.val() == field.attr('title')) || (field.val().replace(/[' ']{1,}/, '') == '')) {
              self.addError(field, self.getLabel(field) + ' is required.', self);
            }
        }
      }
      return true;
    },

    numbersOnly:function(field, self) {
      if (field.hasClass('js_numbers_value')) {
        if (field.val() != (parseInt(field.val() + ""))) {
          self.addError(field, self.getLabel(field) + ' is invalid.', self);
        }
      }
    },

    text: function(field, self){
     var textWithSpacesRegex = /[a-zA-Z]([a-zA-Z]|\s[a-zA-Z])*/;
      if (field.val() != '') {
        if (field.hasClass('js_text') && (field.val() != field.attr('title')) && !field.val().match(textWithSpacesRegex)) {
          self.addError(field, self.getLabel(field) + ' is invalid.', self);
        }
      }
      return true;
    },
    phone: function(field, self) {
      var phoneRegEx = /(\D*\d\D*){10}/;
      if (field.val() != '') {
        if (field.hasClass('js_phone') && (field.val() != field.attr('title')) && !field.val().match(phoneRegEx)) {
          self.addError(field, self.getLabel(field) + ' is invalid.', self);
        }
      }
      return true;
    },
     phone_extension: function(field, self) {
      var name,correspondingPhone;
      if (field.val() != '') {
        if (field.hasClass('js_phone_extension') && (field.val() != '')) {
          name = field.attr('id');
          correspondingPhone = $('#' + name.replace('extension','number'));
          if(correspondingPhone.val() == '')
          self.addError(field, self.getLabel(field) + ' is invalid without ' + self.getLabel(correspondingPhone) + '.', self);
        }
      }
      return true;
    },
    email: function(field, self) {
      var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
      if (field.val() != '') {
        if (field.hasClass('js_email') && (field.val() != field.attr('title')) && !field.val().match(emailRegEx)) {
          self.addError(field, self.getLabel(field) + ' is invalid.', self);
        }
      }
      return true;
    },
    match: function(field, self) {
      if (field.hasClass('js_match')) {
        var classes, matchingField;
        classes = field.attr('class').split(' ');
        for (var i = 0; i < classes.length; i++) {
          if (classes[i].match('js_match_')) {
            matchingField = $('#' + classes[i].replace('js_match_', ''));
          }
        }
        if (field.val() && field.val() != matchingField.val()) {
          self.addError(field, self.getLabel(field) + ' does not match ' + self.getLabel(matchingField) + '.', self);
        }
      }
      return true;
    },
    password: function(field, self) {
      // Need to test for hasClass for safari, IE7 and IE8 need the not null test...
      var isPasswordPresent = false;
      if (field.hasClass('js_password')) {
        var passwordRegEx = /(?=^.{6,}$)(\w*(?=\w*\d)(?=\w*[a-zA-Z])\w*)/;
        //var passwordRegEx = /(\w*(?=\w*\d)(?=\w*[a-zA-Z])\w*).{6,}/; >> this expression have issues with IE
        var wordsMatchingRegEx = field.val().match(passwordRegEx);
        if (wordsMatchingRegEx != null) {
          for (var i = 0; i < wordsMatchingRegEx.length; i++) {
            if (wordsMatchingRegEx[i].match(field.val()))
              isPasswordPresent = true;
          }
        }
        if (field.hasClass('js_password') && (field.val() == '' || !isPasswordPresent)) {
          self.addError(field, 'Please enter a valid password that contains 6 characters, with at least one letter and one number. The password cannot contain spaces or special characters like ! or ?. Note that passwords are case sensitive.', self);
        }
        return true;
      }
    },
    zipcode: function(field, self) {
      if (field.hasClass('js_zipcode') &&  field.val() != '' && (field.val() != field.attr('title'))) {
        if (!Zipcode.isValid(field.val())) {
          self.addError(field, 'Invalid zip code.', self);
        }
      }
    },
    zipcode_with_extension: function(field, self) {
      if (field.hasClass('js_zipcode_with_extension') &&  field.val() != '' ) {
        if (!Zipcode.isValidWithExtension(field.val())) {
          self.addError(field, 'Invalid zip code.', self);
        }
      }
    }
  }
});
// Scheduler validation
///Extended from the form validator
var SchedulerValidation = Class.create(FormValidation.prototype,{ 
  init: function(fieldset, callbackFunctions, errorHolder) {
    if(typeof errorHolder == 'undefined') {
      this.hideErrors = true;
    } else {
      this.hideErrors = false;
    }
    this.validated = false;
    this.hasErrors = false;
    this.container = fieldset;
    this.errorHolder = errorHolder;
    this.button = $($(this.container).parents('.wrapper').get(0)).find('.button');
    this.initialState = $(fieldset).html();
    if(isIE()) {
      //IE tweak
      this.IEtimeoutDuration=500;
    }
    
    if(!$('#scheduler').hasClass('carry_in')) { 
      this.disableButton();
    }
    $('#scheduler .warning').hide();
    this.storeCallbacks(callbackFunctions);
    this.attachChangeValidationActivition();
    this.attachClickValidationActivation();
  },
  
  storeCallbacks: function(callbackFunctions) { 
    this.noErrorsCallback = this.buildNoErrorsCallback(callbackFunctions);
    this.errorsCallback = this.buildErrorsCallback(callbackFunctions);
  },
  
  buildNoErrorsCallback: function(callbackFunctions) {
    var noErrorsCallback;
    if(typeof callbackFunctions.onComplete == 'undefined') {
      noErrorsCallback = function(container) {
        this.enableButton();
      }
    } else {
      noErrorsCallback = function(container) {
        this.enableButton();
        callbackFunctions.onComplete();
      }
    }
    return noErrorsCallback;
  },
  
  buildErrorsCallback: function(callbackFunctions) {
    var errorsCallback;
    if(typeof callbackFunctions.onError == 'undefined') {
      errorsCallback = function(container) {
        this.disableButton();
      }
    } else {
      errorsCallback = function(container) {
        this.disableButton();
        callbackFunctions.onError();
      }
    }
    return errorsCallback;
  },

  removeErrors: function() {
    if(this.hideErrors == false) {
      var enabled_fields = this.getFieldSelector();
      var self = this;    
      $(this.container).find(enabled_fields).each(function() {
        self.removeErrorClass($(this));
      });
      if(this.errorHolder != false && this.validated) {
        this.errorHolder.clear();
      }
    }
    this.hasErrors = false;
  },

  addError: function(field, message, self) {	 
    if(this.hideErrors == false) {
      self.addErrorClass(field);
      if(this.errorHolder != false) {
        self.errorHolder.add(message);
      }
    }
    self.hasErrors = true;
  },

  attachChangeValidationActivition:function() {
		var fields = this.getFields();  
    var self = this;
    var events = [			
      'change',
      'onblur'	
    ];
    
    $(fields).each(function(index,element) {     
	    $.each(events, function(eventIndex,eventItem) {
        if((eventIndex == 0) || ($(element).is('input'))) {
          $(element).bind(eventItem, function(event){
            if((isIE()) && ((eventIndex == 0) && ($(element).is('select'))) && $(element).attr('id') == 'product') {
							
              if(typeof $(element).timeoutId !='undefined') {
                clearTimeout($(element).timeoutId);
              }
              var timeoutId=setTimeout(function() {
                self.validate.call(self);   
              }, self.IEtimeoutDuration);
              
              $(element).timeoutId = timeoutId;
        
            } else {
              self.validate.call(self);
            }
          });
        }
		  });  
    });    
  },

  attachClickValidationActivation:function() {
    var fields = this.getFields();  
    var self = this;
    
    $(this.button).each(function() {
      if($(this).attr('id') != 'store_locator') {
        $(this).click(function(event) {
          self.validate.call(self, true);
        });
      }
    });
  },
  
  silenceValidate: function() {
    var fields = this.getFields();
    var self = this;
    $(fields).each(function() {
      if($(this).is(':visible')){
        for(var rule in self.validationRules) { 
	        if(self.validationRules.hasOwnProperty(rule)) {
	          self.validationRules[rule]($(this), self);					
          }
        }
      }
    });

    if(this.hasErrors) {
      this.disableButton();
    } else {
      this.enableButton();
    }
  },

  validate: function(forceValidate) {
    var fields = this.getFields();
    this.removeErrors();
    
    if((this.shouldValidate(fields)) || (forceValidate)) {
      var self = this;
      $(fields).each(function(event) {
	      if($(this).is(':visible')) {
          for(var rule in self.validationRules) { 
            if(self.validationRules.hasOwnProperty(rule)) {
	            self.validationRules[rule]($(this), self);
            }
          }
        }
      });

      this.callCallback();
    }
  },

  shouldValidate: function(fields) {
    var shouldValidate = true;
    if(!this.validated){
      $(fields).each(function(event) {
        if($(this).val() == '' || $(this).val() == $(this).attr('title')) {
          shouldValidate = false;
        }
      });
    }
    return shouldValidate;
  },

  callCallback: function() {
    if(this.hasErrors){
      this.errorsCallback(this.container);
    } else {
      this.noErrorsCallback(this.container);
      this.validated=true;   
    }
  },
  
  reset:function(keepBinding){
    if(!keepBinding){
      $(this.container).find('*').unbind();
    }
    $(this.container).html(this.initialState);
  },
  
  enableButton: function() {
    //console.log('enableButton');
    $(this.button).removeClass('disabled')
    $(this.button).removeClass('blocked');

  },
  
  disableButton: function() {
    //console.log('disableButton');
    //$(this.button).each(function() {
      if($(this.button).attr('id') != 'store_locator') {
        $(this.button).addClass('disabled');
        $(this.button).addClass('blocked');
      }
    //});
  }

});
// Horizontal Accordion
var HorizontalAccordion = Class.create({
  init: function(horizontal_accordion) {
    this.setupUI(horizontal_accordion);
    this.attachObservers(horizontal_accordion);
  },
  
  setConstants: function() {
    this.additionalGrow = 0;
    this.handlerWidth = 67;
    this.wideHandlerWidth = 214;      
    this.shortStepWidth = 490;  
    this.standardStepWidth = 748;
    this.standardContainerHeight = 263;
    this.initialAnimationBGPosition='-21px 0';
    this.finalAnimationBGPosition='-67px 0';
    this.standardNewCleaningHeight=165;
    this.snapshot=$('#scheduler').clone();
  },
  
  resetDataInfo:function(){
    var parentForm=$('#scheduler').parents('form')[0];
    //parentForm.reset();
    $(parentForm).find('[disabled]').removeAttr('disabled');
      //$('.product.fieldset_wrap').parents('fieldset').hide();
      //$('.add_service').hide();
  },
  
  setupUI: function(horizontal_accordion) {
    this.setConstants();
    this.resetDataInfo();
    this.containers = $(horizontal_accordion).children('.container');
    
    $(this.containers).addClass('disabled_container');
    $(this.containers[0]).removeClass('disabled_container');
    $(this.containers[0]).addClass('selected_container');
    $(this.containers[0]).find('.handle').addClass('height_fixed');
    $(this.containers).children('div.content').css('visibility', 'hidden');   
    $('#scheduler').width(this.wideHandlerWidth+(2*this.handlerWidth));
   
    // Hack for IE6 positioning
    if(isIE6()) {
      $(this.containers).find('div.content, a.handle, div.section').bgiframe();
    }

    var self=this;
    
    $('.close_warning').live('click',function(event){
	    event.preventDefault();
	    var parent=$(this).parents('.required_warning');
	    
	    $(parent).animate({height:"0px"},'normal','swing', function() {
	      $(this).hide();
	    });
	  });  
  },
  
  attachObservers: function(horizontal_accordion) {
    var self = this;
    var container;
    $(horizontal_accordion).find('.js_handle').each(function() {
      $(this).click(function(event) {
        var parentContainer = $(this).parents('.container');
        var direction = ($(parentContainer).hasClass('selected_container'))?-1:1;
        
        if(!$(parentContainer).hasClass('disabled_container')) {
          container = $(this).parents('.container')[0];
          self.animateTo(container, self);
        }
        event.preventDefault();
      });
    });
  },
  
  // Transition by animation
  animateTo: function(container, self, direction) {
    self.animate(container, self.containers, direction);
  },
  
  animate: function(container, containers, direction) {  
    var direction = (!direction) ? 1 : direction;

    //Reseting scheduler width
    $('#scheduler').width($(container).width()+(2*this.handlerWidth));
    
    var factor = this.getIndexOfOpenedContainer(containers);
    var rightTargetPosition = this.calculateTargetPosition(container, direction, factor);

    //this.disableControls(this.containers);
    this.setPreAnimationVisibility(container, direction);  

    var self = this;  
    //Tweak for IE6 opacity issue... dunno why
    $('.handle').css('opacity',1);
    $(container).animate({right:rightTargetPosition},'slow','swing',function(){
      
      //self.enableControls(self.containers,true);
      
      self.setPostAnimationVisibility(container, direction);

      self.populateSchedulerInfo();
      /*
      TODO: Fix this
      */
        if(isIE()){
          $(".handle").css("filter", "");
        }
        

      // if the array of form fields are all filled out on the blur fo the last one do not silenceValidate
      // -- 
      // else do this 
      try{
      	var info=$('#scheduler').data('infoValidation');
      	info.silenceValidate();
      }catch(e){}
    });
  },
  
  calculateTargetPosition: function(container, direction, factor) {
    var targetPosition = 0;
    
    if(direction < 0){      
      targetPosition = this.getRightPosition(container)-$(container).width()+this.handlerWidth;
    }else{
      targetPosition = ($('#scheduler').width()-$(container).width())-(this.handlerWidth*factor);
    }
    return targetPosition;
  },
  
  getIndexOfOpenedContainer: function(containers) {
    var opened_container_index = 0;
    $(containers).each(function() {
      if($(this).hasClass('selected_container')) {
        return false;
      } else { 
        opened_container_index++;
      }
    }); 
    return opened_container_index;
  },

  setPreAnimationVisibility: function(container, direction) {		
    //var height = $(container).height()-2;
    
    if(direction < 0) {
      $(container).prev().children('.content').css('visibility', 'visible');
    } else {  
      $(container).children('.content').css('visibility', 'visible');    
      //$('#scheduler').height(height);
    }
  },
  
  setPostAnimationVisibility: function(container, direction) {
    //var height = $(container).prev().height();
    
    if(direction < 0) {
      $(container).children('.content').css('visibility', 'hidden');  
      //$('#scheduler').height(height); 
    } else {
      $(container).prev().children('.content').css('visibility', 'hidden');
    }    
  },
 
 
  growHeight:function(newHeight,container){
    if(newHeight!=0){
      //TODO: this is a patch for an error... gotta find the real issue cause
      var handleTweak=-10;
      var growableElements=[$(container).find('.wrapper'),$(container).find('.more_info'),$(container),$(container).children('.handle')];
      var fixedNewHeight=0;
      var self=this;
       
      $('#scheduler').height($('#scheduler').height() + newHeight);
      $(container).addClass('additional_height');
      
      $(growableElements).each(function(index,element) {
        
        //hack for IE6
        if((isIE6())&&(($(element).hasClass('wrapper'))&&!(self.isEven($(element).height() + newHeight)))){
          newHeight--;  
        } 
        
		//fix for last tab... gotta found why is doing that
		if($(element).hasClass('handle')&&$(element).hasClass('step_3')){
			fixedNewHeight=handleTweak;
        }else{
			fixedNewHeight=0;
		}	    
        element.height($(element).height() + newHeight+fixedNewHeight);
      });
       
      if(!$(container).data('additionalHeight')){
        $(container).data('additionalHeight',0);
      }
      
      $(container).data('additionalHeight',newHeight+$(container).data('additionalHeight'));
       
      this.additionalGrow=$(container).data('additionalHeight');
      if(this.additionalGrow==0){
        $(container).removeClass('additional_height');
      }
    }
  },
  
  resetHeight:function(container,limit){
    var additionalHeight=0;
    limit=(!limit)?0:limit;
    if($(container).find('.section_add_service').length==0){
      if($(container).data('additionalHeight')){
        additionalHeight=parseInt($(container).data('additionalHeight'));
      }
      
      if($(container).hasClass('closed_container')){
				limit=additionalHeight;
      }

      $(container).data('additionalHeight',limit);
      $(container).removeClass('additional_height');
    }
  },

  // Transition with no animation
  
  jumpTo:function(container, self){
    self.jump(container);
  },
  
  jump: function(container) { 
    //Reseting scheduler width
    $('#scheduler').width($(container).width()+(2*this.handlerWidth));
    
    var factor = this.getIndexOfOpenedContainer(this.containers);
    var rightTargetPosition = this.calculateTargetPosition(container, 1, factor);
    
    this.setPreAnimationVisibility(container, 1);
    $(container).css('right',rightTargetPosition);
    this.setPostAnimationVisibility(container, 1);
  },
  
  
  // Reset to starting position
  
  reset:function(){
    var self = this;
    var containers = this.containers;
    var rightTargetPosition=0;
    
    //this.disableControls(this.containers);
    
    $(containers).each(function(index,element){
      rightTargetPosition = self.getRightPosition(element)-$(element).width()+$(element).children('a.handle').width(); 
      $('#scheduler').css('height', '250px');
      
      $(element).animate({right:rightTargetPosition},'slow','swing', function() {
        $(self.containers[index]).children('.content').css('visibility', 'hidden');
        
        if($(element).hasClass('selected_container')){
          var rightTargetPosition=self.getRightPosition(self.containers[0])+(self.standardStepWidth-self.shortStepWidth);
          
          $(self.containers[0]).removeClass('selected_container');
          $('#scheduler').width(self.wideHandlerWidth+(2*self.handlerWidth));
          //self.enableControls(self.containers);
          
          if($(self.containers[0]).width()>self.shortStepWidth){
            $(self.containers[0]).css('width', self.shortStepWidth);
            $(self.containers[0]).css('right',rightTargetPosition);
          }
        }
        
        if(index==0){
          self.resetLogic();
        };  
      });
      
      return !$(element).hasClass('selected_container');    
    });
    this.updateContainerClassNames(containers[0], containers)
  },
  
//  disableControls: function(containers) {
//    console.log('disableControls');
//    $(containers).find('a.secondary_button, a.js_handle').each(function(index,element){
//      if($(element).attr('id') != 'store_locator'){
//        $(element).addClass('disabled');
//      } 
//    });
//  },
   
//  enableControls: function(containers) {
//    console.log('enableControls');    
//    $(containers).find('a.secondary_button, a.js_handle').each(function(){
//      //class used to block the enable function
//      if(!$(this).hasClass('blocked')) { 
//        $(this).removeClass('disabled');
//      }
//    });
//  }, 
  
  updateContainerClassNames: function(container, containers) {    
    // Toggle Selected Class
    var firstFormElement=$(container).find('input[type=text]:visible,select:visible').get(0);
     
    $(containers).removeClass('selected_container');
    $(container).addClass('selected_container');
  
    // Toggle Closed Container Class
    $(containers).each(function() {
      if($(container) == $(this)) {
        return false;
      } else {
        $(this).addClass('closed_container');
      }
    });
    $(container).removeClass('closed_container');
  },
  
  //Helper functions
  getRightPosition:function(container){ 
    var targetRight=parseInt(($(container).css('right')).replace('px',''));
    return targetRight;
  },
  
  isEven:function(number){
    return ((number/2) == parseInt(number/2));
  }
  
});
var Scheduler = Class.create(HorizontalAccordion.prototype, {
  init: function(element) {
    this.setCustomEventsBinding();
    this.setupUI(element);
    this.attachObservers(element);
    this.toggleClassNames();
    this.createStartingPosition();
    this.setAjaxBind();
    this.schedulerPrepopulator = new SchedulerPrepopulator();
    this.isSchedulerPrepopulator = false;
    this.setElementsVisibility();
    this.schedulerUtilities = new SchedulerUtilities(element);
  },
  
  
  /*
    Custom events refactor
  ----------------------------------------------------------------------------*/
  setCustomEventsBinding:function(){
    this.NEXT="doNext";
    this.BACK="doBack";
  },
  
  setElementsVisibility:function(){
    $('#contact_info .county').removeClass("show_county_field").addClass("hide_county_field");
  },
  
  doShortStep:function(container){
    if (($(container).hasClass('short_step'))&&($('#store_locator:visible').length == 0)){
      this.next($('#go_to_step_two'));
    } 
  },
  /*--------------------------------------------------------------------------*/
  setAjaxBind:function(){
    this.service = $("#service");
    this.zipcode = $("#zip_code");

    this.order = new Order(this.service,this.zipcode);
    this.order.observe();
  },

  resetLogic:function() {
    var parent=$('#scheduler').parent();
    $('#scheduler').remove();
    $(parent).prepend(this.snapshot);

    // Needed to recreate the error holders
    delete(schedulerStep1ErrorHolder);
    delete(schedulerStep2ErrorHolder);

    $('#store_locator').addClass('js_external_link');
    SchedulerObserver.attachAllResetObservers();
    LinkObserver.attachAllObservers();
    UIObserver.attachAllObservers();
    if(isIE6()) {
      addInputTypeAsClass();
    }
    ElementObserver.attachAllObservers();
  },

  toggleClassNames: function() {
    $(this.containers[0]).addClass('starting_position');
    $(this.containers[0]).removeClass('selected_container');
    $(this.containers[0]).css('width', this.shortStepWidth);
  },

  createStartingPosition: function() {
    var horizontalOffset = 0;
    var self = this;

    for (var i = (this.containers.length - 1); i > -1; i--) {
      horizontalOffset += $(this.containers[i]).children('a.handle').width();
      $(this.containers[i]).css({
        'z-index':4 + i,
        'right':horizontalOffset - $(this.containers[i]).width()
      });
    }
  },

  attachObservers: function(horizontal_accordion) {
    var self = this;

    $(horizontal_accordion).find('.js_handle').each(function() {
      $(this).click(function(event) {
        var container = $(this).parents('.container');
        if (!$(container).hasClass('disabled_container') && $(container).hasClass('starting_position')) {
          if (!$(container).children('.js_handle').hasClass('disabled')) {
            SchedulerValidationObserver.attachAllObservers();
            $('.message').fadeOut();
            self.next($(this));
          }
        }
        event.preventDefault();
      });
    });
  },

  populateSchedulerInfo: function() {
    //Flag added as animate for div#step_one is called twice. In this case flag will avoid duplicate change trigger.
    if (this.isSchedulerPrepopulator) {
      return;
    }
    this.isSchedulerPrepopulator = true;
    this.schedulerPrepopulator.selectElementAndTriggerChange($("#service"), $("#schedulerInformation_serviceName"));
  },

  // Special Animations & Jumps

  animateFromStartingPosition: function(handle, self) {
    var self = this;
    var container = $(handle).parents('.container');
	  var originalWidth = $(handle).width();
	  var pauseTime = 75;

    //this.disableControls();
    //Tweak for IE6 opacity issue... dunno why
    // 1 (scheduler_validation_observer.js line 129)
    $(handle).css('opacity',1);

	  $(handle).animate({ right:-originalWidth }, { duration:250,complete:function() {
  		// 2 (scheduler_validation_observer.js line 129)
  		if(!$(handle).hasClass('button')){
		  $(handle).width(self.handlerWidth);
		}
  		
		setTimeout( function(){
  			$(container).removeClass('starting_position');
  			// 3 (scheduler_validation_observer.js line 129)
  			$(handle).css('right',0);
  			self.animateTo(container, self);
  		}, pauseTime);
      }
    });
  },

  jumpFromStartingPosition: function(handle, self) {
    var container = $(handle).parents('.container');
    $(container).removeClass('starting_position');
    
    if(!$(handle).hasClass('button')){
      $(handle).width(self.handlerWidth);
    }
    
    $('.message').hide();
  },

  animateToStartingPosition: function() {
    var self = this;

    var targetContainer = $(this.containers[0]);
    var handle = $(targetContainer).find('.js_handle');

    this.resetHeight(targetContainer);

    schedulerStep1ErrorHolder.clear();
    schedulerStep3ErrorHolder.clear();

    //this.disableControls();
    //Tweak for IE6 opacity issue... dunno whyhy
    $(handle).css('opacity',1);

    $(handle).animate({width:this.wideHandlerWidth}, { duration:"fast",complete:function() {
      self.reset();
      $(targetContainer).find('.handle').removeAttr('style');
    }});
  },

  animateToStandardWidth: function(element) {
    //get position and width to set back again to short-step setup
    if($(element).hasClass('short_step')){
      this.shortStepWidth=$(element).width();
      this.shortStepRightPos=$(element).css('right');
    }

    var self = this;
    //this.disableControls();

    $('#scheduler').width(this.standardStepWidth + (2 * this.handlerWidth));
    var rightTargetPosition = $('#scheduler').width() - this.standardStepWidth;

    $(element).animate({width:this.standardStepWidth,right:rightTargetPosition}, { duration:"slow",complete:function() {
        $(element).removeClass('short_step');
        $('.step_1_5').fadeIn('fast', function() {
          var input = $(this).find('input[type=text], select');
          $(input).each(function() {
            if($(this).val() != $(this).attr('title')) {
              $(this).removeClass('prompt_text');
            }
          });
        });
        //self.enableControls();
      }
    });
  },

//  For Store Locator...

  animateToShortWidth: function() {
    var self = this;
    var element=$(this.containers[0]);
    if(!$(element).hasClass('short_step')){
      //this.disableControls();
       $('.step_1_5').hide();

      $(element).animate({width:this.shortStepWidth,right:this.shortStepRightPos}, { duration:"fast",complete:function() {
          $(element).addClass('short_step');
          $('#scheduler').width(self.shortStepWidth+ (2 * self.handlerWidth));
        }
      });
    }
  },

  jumpToStandardWidth: function(element) {
    var leftTargetPosition = $(element).position().left - (this.standardStepWidth - this.shortStepWidth);
    $(element).css('width', this.standardStepWidth);
    $(element).css('left', leftTargetPosition);
    $(element).removeClass('short_step');
    $(element).find('a.secondary_button').removeClass('disabled');
  },

  // Next, Previous, Open a step, and Reset

  next: function(handle, jumpToTransition) {
    var container = $(handle).parents('.container');
    var inputs = $('#scheduler').find(':input');

    // resets fields in contact form if the values are empty
    // this is a hack and needs to be fixed
    if($(container).attr('id') == 'step_two') {
      $(inputs).each(function() {
        $(this).trigger('blur');
        if($(this).val() != $(this).attr('title') && $(this).val() != "") {
          $(this).removeClass('prompt_text');
        }
      });
      // if all input val != title, then enable button
    }

    if ($(container).hasClass('starting_position')) {
      this.updateContainerClassNames(container, this.containers);
      $(container).addClass('short_step');

      if (jumpToTransition) {
        this.jumpTo($(container), this);
        this.jumpFromStartingPosition(handle, this);
      } else {
        this.animateFromStartingPosition(handle, this);
      }

    } else if ($(container).hasClass('short_step')) {
      this.updateContainerClassNames(container, this.containers);
      if (jumpToTransition) {
        this.jumpToStandardWidth(container);
      } else {
        this.animateToStandardWidth(container);
      }

    } else {
      if(this.getIndexOfOpenedContainer(this.containers) == 1) {
        var third_step = $($(container).siblings('#step_three'));
	
        var validation = new SchedulerValidation($(container), {});
	      
	      validation.silenceValidate(); 
      }
      container = $(container).next();
      $("#error_message").insertAfter($($(container)).find('.content > .wrapper'));

      container.removeClass('disabled_container');
      this.updateContainerClassNames(container, this.containers);

      if(jumpToTransition) {
        this.jumpTo(container, this);
      } else {
        this.animateTo(container, this);

        var content = $('#step_three').children('.content');
        var height = $(content).children('.wrapper').css('height');

        //$('#error_message').css('height', height);

      }
    }
  },

  previous: function(element) {
    var container = $(element).parents('.container');
    this.animateTo(container, this, -1);
    container = container.prev();
    $("#error_message").insertAfter($($(container)).find('.content > .wrapper'));
    this.updateContainerClassNames(container, this.containers);
  },

  openStep:function(step) {
    var self = this;
    var handle;
    step--;

    $(this.containers).each(function(index, element) {
      handle = $(element).find('.js_handle');
      self.next(handle, true);
      if (step == index) {
        return false;
      }
    });
  },

  openSchedulerOnLoad: function(element) {
    $(element).trigger('click');
  },

  resetToStart: function() {
    $(this.containers[0]).addClass('starting_position');
    $(this.containers[0]).removeClass('short_step');
    $('.step_1_5').fadeOut();
    $('.message').fadeIn();
    this.resetDataInfo();
    this.animateToStartingPosition();
  }
});
var ErrorHolder = Class.create({
  init: function(element) {
    this.element = element;
    this.configure();
  },

  configure: function() {
    this.list = this.buildList();
    this.closeButton = this.buildCloseButton();
    this.insertList(this.list, this.element);
    this.insertCloseButton(this.closeButton, this.element);

    $(this.element).addClass('warning');
    $(this.element).hide();
  },

  buildList: function() {
    var list = document.createElement('ul');
    return list;
  },

  buildCloseButton: function() {
    var button = document.createElement('a');
    $(button).attr('href','#');
    $(button).addClass('close');
    $(button).text('close');
    
    button = this.attachCloseEvent(button);
    return button;
  }, 

  attachCloseEvent: function(button) {
    var self = this;    
    $(button).click(function(event) {
      self.element.hide();
      self.clear();
      event.preventDefault();
    });
    return button;
  },

  insertList: function(list, element) {
    $(list).appendTo(element);
  },

  insertCloseButton: function(closeButton, element) { 
    $(closeButton).appendTo(element);
  },
  
  add: function(message) {
    listItem = document.createElement('li');
    $(listItem).text(message);
    //check for duplicated messages
    if($(this.list).find('li:contains('+message+')').length == 0){
      $(listItem).appendTo(this.list);
    } 
    $(this.element).show();
  },

  addHtml: function(message) {
    listItem = document.createElement('li');
    $(listItem).html(message);
    $(listItem).appendTo(this.list);
    $(this.element).show();
  },

  clear: function() {
    $(this.element).hide();
    $(this.list).html('');
  }
});
var InfoBox = Class.create({
  init: function(element) {
    this.element = element;
    this.configure();
  },

  configure: function() {
    this.closeButton = this.buildCloseButton();
    this.insertCloseButton(this.closeButton, this.element);
  },
  
	buildCloseButton: function() {
    var button = document.createElement('a');
    $(button).attr('href','#');
    $(button).addClass('close');
    $(button).text('close');
    
    button = this.attachCloseEvent(button);
    return button;
  }, 

  attachCloseEvent: function(button) {
		var parent = this.element;	
    $(button).click(function(event) {
			$(parent).hide();
      event.preventDefault();
    });
    return button;
  },

  insertCloseButton: function(closeButton, element) { 
    $(closeButton).appendTo(element);
  }
  
});
var Flyover = Class.create({
  init: function(element, dialog) {
	  this.element = element;
	  this.dialog = dialog;
	  this.setConstants();
	  this.stopClick();
	  this.attachHover();
	},
	
	setConstants: function() {
	  //vertical offset for flyovers
    this.flyoverOffsetTop=-91;
    //horizontal offset for flyovers
    this.flyoverOffsetLeft=-57;
    //default time for the flyover show (miliseconds)
    this.flyoverDefaultInitTime=500;

	},
	
	stopClick: function() {
	  $(this.element).find('a[href]').click(function(event){
		  event.preventDefault();
	  }); 
	},
	
  attachHover: function() {
	  var hoverOver = this.buildHoverOverFunction();
	  var hoverOut = this.buildHoverOutFunction();
	  $(this.element).find('a[href]').hover(hoverOver, hoverOut);
  },
  
  buildHoverOverFunction: function() {
    var self = this;
    var hoverOver = function(){
		  var timeoutId = "";
		  
		  $(self.dialog).dialog('close');
		  clearTimeout($(self.dialog).data("timeoutId"));

      var x_position = self.getHorizontalFlyoverPosition(this, self.flyoverOffsetLeft);      
      var y_position = self.getVerticalFlyoverPosition(this, self.flyoverOffsetTop);

	    $(self.dialog).dialog('option', 'position', [x_position, y_position]);
	    $(self.dialog).dialog('option', 'dialogClass', 'flyover' );
	    $(self.dialog).addClass('loading');	
	  
	    href=$(this).attr('href');

	    timeoutId = setTimeout(function(){
        self.manageRequest(href, self);
        $(self.dialog).dialog('open');
	    }
	    ,self.flyoverDefaultInitTime);
	    
      $(self.dialog).data("timeoutId",timeoutId);
    }
	  return hoverOver;
  },
  
  buildHoverOutFunction: function() {
    var self = this;
    var hoverOut = function(){
      clearTimeout($(self.dialog).data("timeoutId"));
      var timeoutId=setTimeout(function(){
        $(self.dialog).dialog('close');
          
      }
      ,self.flyoverDefaultInitTime);
      $(self.dialog).data("timeoutId",timeoutId);
    }
    return hoverOut;
  },
  
  getHorizontalFlyoverPosition: function(_this, flyoverOffsetLeft) {
   return $(_this).offset().left - $(document).scrollLeft() + flyoverOffsetLeft + $(_this).parents('ul').width()
  },
  
  getVerticalFlyoverPosition: function(_this, flyoverOffsetTop) {
    return $(_this).offset().top - $(document).scrollTop() + flyoverOffsetTop;
  },
  
  manageRequest:function(URL, self){ 
    $(self.dialog).load(URL, function(){
      if(isIE()) {
        new ElementObserver.attachPseudoClass();
	    }
	    $(self.dialog).removeClass('loading');
    });
  }
});
// Pseudo class
var PseudoClass = Class.create({ 
  init: function(autotarget) {
	  this.targets = [];
	  if((autotarget != undefined) && (autotarget == true)) {
		  this.attach(true);
	  }
  },
  addTarget: function(target) {
	  this.targets.push(target);
	  return target;
  },
  attach: function(autotarget) {
	  var self = this;
	  if((autotarget != undefined) && (autotarget == true)) {
		  $('.js_pseudo_class').each(function(index, element) {
			  self.byTarget(element);
		  });
	  }
	  jQuery.each(self.targets, function(index, target) {
		  self.byTarget(target);
	  });
	  self.targets = null;
  },
  byTarget: function(target) {
	  var children = $(target).children();
	  if(children.length > 1) {
		  $(children.get(0)).addClass('first-child');
		  $(children.get(children.length - 1)).addClass('last-child');
	  } else if(children.length == 1) { 
		  $(children.get(0)).addClass('only-child');
	  }
  }
});
var createdDialogs = {};

var Dialog = Class.create({
  init: function(element, options) {
    var divSelector = "#"+(($(element).attr('href')).split('#'))[1];
    var divName = divSelector.replace('#', '');
    this.setupConstants(divSelector)
      
    if(this.checkIfNotCreated(divName)) {
      this.createAndStore(divName, divSelector);
    }
    this.loadFromStoredDialogs(divName);
  },
  
  setupConstants:function(divSelector){
  	var self = this;
	this.firstOpen=true;
  	this.modal = $(divSelector).hasClass('modal');
  	if(this.modal) {
	  //mod to allow modal	
	  this.defaultConfig = {
	    bgiframe: true,
	    modal: true,
	    autoOpen: false,
	    draggable: false,
	    resizable: false,
	    width: 355,
	    position: ['center', 'center'],
	    open: function(event, ui){
	      $('body').css('overflow', 'hidden');
	    },
	    close: function(event, ui){
	      $('body').css('overflow', '');
	    }
	  }
  	} else {
	  this.defaultConfig = this.getDefaultConfiguration();
  	}	
  },

  getDefaultConfiguration:function() {
    var self = this;
    var defaultConfig = {
      autoOpen: false,
      width: 360,
      open: function(event, ui) {
        self.checkIfOutOfWindow();
      }
    };
    return defaultConfig;
  },

  createAndStore: function(divName, divSelector) {
    createdDialogs[divName] = {};
    this.storeDefaultDimensions(divName, divSelector);
    createdDialogs[divName].dialog = this.create(divSelector);
  },
  
  storeDefaultDimensions: function(divName, divSelector) {
    $(divSelector).addClass('set_dialog_dimensions');
    createdDialogs[divName].height = $(divSelector).height();
    createdDialogs[divName].width = $(divSelector).width();
    $(divSelector).removeClass('set_dialog_dimensions');
  },
  
  loadFromStoredDialogs: function(divName) {
    this.dialog = createdDialogs[divName].dialog;
    this.dialogHeight = createdDialogs[divName].height;
    this.dialogWidth = createdDialogs[divName].width;
  },
  
  create: function(divSelector) {
    var self=this;			
    var dialog = $(divSelector).dialog(self.defaultConfig);
	
    if(!isIE6() && !this.modal) {
      dialog = this.insertMarkup(dialog);
    }
	
	if(this.modal){
		 dialog.dialog('option', 'dialogClass', 'modal_dialog');	
	}else{
		 dialog.dialog('option', 'dialogClass', 'dialog');
	}
   
    return dialog;
  },
  
  checkIfOutOfWindow:function() {
    var tmpElement = this.dialog.parents('.ui-dialog');
    var tmpElementTop = parseInt($(tmpElement).css('top'));
    var tmpElementHeight = parseInt($(tmpElement).height());
    var tmpDocHeight = parseInt($('body').height()) - 20;
    var tmpOffset = 0;
    
    tmpOffset = (tmpElementTop + tmpElementHeight) - tmpDocHeight;
    
    if(tmpOffset >= 0) {
      tmpOffset = (tmpElementTop - (tmpOffset + 120));
      $(tmpElement).css('top', tmpOffset);
    }
  },
  
  open:function() {
    var self = this;
    this.dialog.find('input, textarea').val("");
    this.clearErrors();
    this.dialog.dialog('open');
    if(this.firstOpen){
      $(this.dialog).find('.close').each(function(){
	$(this).click(function(e){
	  self.dialog.dialog('close');
	  e.preventDefault();
	});
      });
      this.firstOpen=false;
    }
  },

  clearErrors: function() {
    var self = this;
    self.dialog.find('.warning').hide();
    var fields = self.dialog.find('input, select, textarea');
    fields.each(function(){
       self.removeErrorClass($(this));
    });
  },

  removeErrorClass: function(field) {
    if($(field).is('input')) {
      $(field).parents('.input_container').removeClass("field_error");
    }
    if($(field).is('textarea')) {
      $(field).parents('.textarea_container').removeClass("field_error");
    } else {
      $(field).removeClass("field_error");
    }
  },
  
  insertMarkup: function(dialog) {
    dialog = this.insertContent(dialog);
    dialog = this.insertCorners(dialog);
    dialog = this.insertBorders(dialog);
    dialog = this.insertInterior(dialog);
    
    return dialog;
  },
  
  insertContent: function(dialog) {
    dialog.html('<div class="content">' + dialog.html() + '</div>');
    return dialog;    
  },
  
  insertInterior: function(dialog) {
    dialog.html('<div class="interior">' + dialog.html() + '</div>');
    return dialog;    
  },
  
  insertCorners: function(dialog) {
    var corners = this.buildCorners();
    dialog.html(dialog.html() + corners);
    return dialog;
  },
  
  insertBorders: function(dialog) {
    var corners = this.buildBorders();
    dialog.html(dialog.html() + corners);
    return dialog;
  },
  
  buildCorners: function() {
    var top_left_corner = '<div class="dialog_corner top_left"></div>';
    var top_right_corner = '<div class="dialog_corner top_right"></div>';
    var bottom_left_corner = '<div class="dialog_corner bottom_left"></div>';
    var bottom_right_corner = '<div class="dialog_corner bottom_right"></div>';
    return top_left_corner + top_right_corner + bottom_left_corner + bottom_right_corner;
  },
  
  buildBorders: function() {
    var top_border = '<div class="dialog_border top"></div>';
    var right_border = '<div class="dialog_border right"></div>';
    var bottom_border = '<div class="dialog_border bottom"></div>';
    var left_border = '<div class="dialog_border left"></div>';
    return top_border + right_border + bottom_border + left_border;
  },
  
  configure: function(element, options) {
    if (!this.modal) {
		  var y = this.getVerticalPosition(element, options.y);
		  var x = this.getHorizontalPosition(element, options.x);
		
		  this.setDialogPosition(x, y);
	  }
  },
  
  checkIfNotCreated: function(divName) {
    return (typeof createdDialogs[divName] == 'undefined');
  },
  
  getHorizontalPosition: function(element, x) {
    return x + $(document).scrollLeft() - (this.dialogWidth / 2);
  },
  
  getVerticalPosition: function(element, y) {
    return y - $(document).scrollTop() - this.dialogHeight - $(element).height();
  },
  
  setDialogPosition: function(x, y) {
    this.dialog.dialog('option', 'position', [x, y]);
  },

  getCloseFunction:function() {
    return this.dialog.dialog('option', "close");
  },

  setCloseFunction:function(closeFunction) {
    this.dialog.dialog('option', "close", closeFunction);
  }
});
var Button = Class.create({
  init: function(element, button_name) {
    this.element = this.buildButton(element, button_name);    
  }, 
  
  buildButton: function(element, button_name) {
    var class_names = $(element).attr('class');
    var button_id = $(element).attr('id');
    if (button_name == null) {
     button_name = $(element).text();
    }

    if($(element).is('button')) {
      element = this.buildFromButtonTag(element, class_names, button_id, button_name);
    } else {
      element = this.buildFromAnchorTag(element, button_name);
    }
    $(element).addClass('button');
    return element;
  },
  
  buildFromButtonTag: function(element, class_names, button_id, button_name) {
    var anchor = document.createElement('a');
    var tabindex = $(element).attr('tabindex');
    
    $(anchor).attr('href', '#');
    if(button_id) {
      $(anchor).attr('id', button_id);
    }
    $(anchor).attr('class', class_names);
    $(anchor).html('<span>' + button_name + '</span>');
    if($(element).attr('tabindex') != '') {
      $(anchor).attr('tabindex', tabindex)
    }
    
    $(element).replaceWith(anchor);
    $(anchor).removeClass('js_button');
    return anchor;
  },
  
  buildFromAnchorTag:function(element, button_name) {
    var span = document.createElement('span');
    var tabindex = $(element).attr('tabindex');
    $(span).html(button_name);
    $(element).html(span);
    
    if($(element).attr('tabindex') != '') {
      $(span).attr('tabindex', tabindex)
    }
    return element;
  }
});
var Textbox = Class.create ({
  init: function(element) {
    if($(element).is('textarea')) {
      this.buildFromTextarea(element);
    } else {
      this.buildFromInput(element);
    }
  },
  
  buildFromInput: function(element) {
		$(element).wrap('<div class="input_container"></div>');
		$(element).addClass('textbox');
  },
  
  buildFromTextarea: function(element) {
    var corners = this.buildTextareaCorners();
    $(element).wrap('<div class="textarea_container"><div class="interior"></div></div>');
    $(element).before(corners);
    $(element).addClass('textbox');
  },
  
  buildTextareaCorners: function() {
    var top_left_corner = '<div class="textarea_corner top_left"></div>';
    var top_right_corner = '<div class="textarea_corner top_right"></div>';
    var bottom_left_corner = '<div class="textarea_corner bottom_left"></div>';
    var bottom_right_corner = '<div class="textarea_corner bottom_right"></div>';
    return top_left_corner + top_right_corner + bottom_left_corner + bottom_right_corner;
  }
});
var CharacterCount = Class.create({
  init: function(element) {
    var counter = $(element).parents('fieldset').find('.counter');
    var limit = $(counter).text();
    
    this.updateCount(counter, element, limit);
    this.attachKeyListeners(counter, element, limit);
  },
  
  attachKeyListeners: function(counter, element, limit) {
    this.attachKeypress(element, limit);
    this.attachKeyup(counter, element, limit);
  },
  
  attachKeypress: function(element, limit) {
    var self = this;
    $(element).keypress(function(event) {
      var remainingCharacters = self.getRemainingCharacters(element, limit);
      if(!self.isKeyAllowable(remainingCharacters, event.keyCode)) {
        event.preventDefault();
		  }
    });
  },
  
  attachKeyup: function(counter, element, limit) {
    var self = this;
    $(element).keyup(function(event){
      self.updateCount(counter, element, limit);
    });
  },
  
  isKeyAllowable: function(remainingCharacters, keyCode) {
    var allow = true;
    if(remainingCharacters == 0) {
      var allowableKeyCodes = [8,9,12,27,35,36,37,38,39,40,46];

      if(($.inArray(keyCode, allowableKeyCodes) == -1)||(isIE())) {
        allow = false
      }
    }
    return allow;
  },
  
  getRemainingCharacters:function(element, limit){
    var value;
    if($(element).hasClass('prompt_text')){
      value = limit;
    } else {  
      value = limit - $(element).val().length;
    }
    return value;
  },
  
  updateCount: function(counter, element, limit) {
    var starting_count = this.getRemainingCharacters(element, limit);
    $(counter).text(starting_count + ' characters remaining');
  }
});
var PromptText = Class.create({
  init: function(element) {
    if($(element).val() == $(element).attr('title')) {
      $(element).addClass('prompt_text');
    }
    
    this.attachFocus(element);
    this.attachBlur(element);
  },
  
  attachFocus:function (element) {
    $(element).focus(function() {
      if($(element).val() == $(element).attr('title')) {
      	$(element).val('');
		    $(element).removeClass('prompt_text');
      }
    });
  },
  
  attachBlur: function(element) {
    $(element).blur(function() {
      if($(element).val() == '') {
      	$(element).val($(element).attr('title'));
      	$(element).addClass('prompt_text');
      }
    });
  },
  
  isPrePopulated: function(element) {
    $(element).removeClass('prompt_text');
  }
});
// Goodies to extend scheduler
var SchedulerUtilities = Class.create({
  init: function(element) {
    this.element = $(element);
    
    this.addPromptText();
    this.addInputTitleFlag();
  },
  
  addPromptText: function() {
    var inputs = $(this.element).find('input[type=text], textarea, select');
    
    $(inputs).each(function() {
      if($(this).val() == $(this).attr('title')){
        $(this).addClass('prompt_text');
      } else {
        $(this).removeClass('prompt_text');
      }
      
      if($(this).is('select')) {
        
        $(this).change(function() {
         if($(this).val() == $(this).attr('title')){
            $(this).addClass('prompt_text');
          } else {
            $(this).removeClass('prompt_text');
          }
        });
        
      } else {
        
        $(this).focus(function() {
          if($(this).val() == $(this).attr('title')){
            $(this).val('');
            $(this).removeClass('prompt_text');
          }
        });

        $(this).blur(function() {
          if($(this).val() == ''){
            $(this).val($(this).attr('title'));
            $(this).addClass('prompt_text');
          }
        }); 
        
      }
    });
  },
  
  addInputTitleFlag: function() {
    var inputs = $(this.element).find('input[type=text], textarea'); 
    var that = this;
    
    $(inputs).each(function() {
      var input_flag = that.createInputTitleFlag($(this).parent(), $(this).attr('title'));

      $(this).focus(function() {
        $(input_flag).fadeIn(100);
      });
      $(this).blur(function() {
        $(input_flag).fadeOut(100);
      });
    });
  },
  
  createInputTitleFlag: function(input_container, title) {
    var input_flag = document.createElement('span');

    $(input_flag).text(title);
    $(input_flag).addClass('input_title_flag');
    $(input_flag).appendTo(input_container);
    $(input_flag).hide();
    $(input_container).css({'position':'relative'});
    
    return input_flag;
  }
});

var NumbersOnly = Class.create({
  init: function(element) {
    this.attachKeyListener(element);
  },
  
  attachKeyListener: function(element) {
    var self = this;
    $(element).keydown(function(event) { 
      var keyCodes = self.buildNumberCodes();
      if(!self.isKeyAllowable(event, keyCodes)) {
        event.preventDefault();
      }
    });
  },
  
  isKeyAllowable: function(event, keyCodes) {
    var allow = true;
    if(jQuery.inArray(event.keyCode, keyCodes) == -1 || event.shiftKey == true) {
      allow = false;
    }
    return allow;
  },
  
  buildNumberCodes: function() {
    var navigationCodes = [8,9,12,27,35,36,37,39,46];
    var numberCodes = [48,49,50,51,52,53,54,55,56,57];
    var numberKeyPadCodes = [96,97,98,99,100,101,102,103,104,105];
    
    var temp = jQuery.merge(navigationCodes, numberCodes);
    return jQuery.merge(temp, numberKeyPadCodes);
  }
});
var ListToggler = Class.create({
  init: function(toggle) {
    this.toggle = toggle;
    this.attachClickBehavior();
  },

  attachClickBehavior: function() {
    var self = this;
    $(this.toggle).children('a').click(function() {
      self.toggleLinkText(this);
      $(this).parents('ul').children('.extra_list_element').toggle();
      return false;
    });
  },

  toggleLinkText: function(anchor) {
    var currentText = $(anchor).text();
    if (currentText.match(/^View all/)) {
      $(anchor).text(currentText.replace(/View all/, 'Hide'));
    } else {
      $(anchor).text(currentText.replace(/Hide/, 'View all'));
    }
  }
});
var ShowMessage = Class.create({
  init: function(element) {
    this.element = $(element);
    this.trigger = $(element).find('.message_trigger');
    this.flyout = $(element).find('.message_flyout'); 

    this.wrapElements();
    this.bindEvents();
  },

  bindEvents: function() {
    var that = this;

    if($(this.trigger).is(':input')) {
      $(this.trigger).focus(function() {
        that.positionRight();
        that.showMessage();
      });

      $(this.trigger).blur(function() {
        that.hideMessage();
      });
    }
    
    if($(this.trigger).is('a')) {
      $(this.trigger).hover(
        function(event) {
          that.positionBottom();
          that.showMessage();
        }, 
        function () {
          that.hideMessage();
        }
      );
    }
  },

  showMessage: function() {
    $(this.flyout).fadeIn('fast');
  },

  hideMessage: function() {
    $(this.flyout).fadeOut('fast');
  },

  positionRight: function() {
    var triggerWidth = $(this.trigger).width();
    var triggerHeight = $(this.trigger).height();

    var top = (triggerHeight / 2) - 40;
    var left = triggerWidth + 10;
    
    if(isIE6) {
    	var left = (triggerWidth/2) - 20;
    }

    $(this.flyout).css({
      'position':'absolute',
      'top':top,
      'left':left
    });
  },

  positionBottom: function() {
    var triggerWidth = $(this.trigger).width();
    var triggerHeight = $(this.trigger).height();
    var flyoutWidth = $(this.flyout).width();

    var top = triggerHeight + 5;
    var left = ((triggerWidth / 2) - (flyoutWidth / 2)) + 69;

    $(this.flyout).css({
      'position':'absolute',
      'top':top,
      'left':left
    });
  },

  wrapElements: function() {
    var wrap = document.createElement('span');
    
    $(wrap).css({
      'position':'relative'
    });
    $(wrap).appendTo(this.element);
    if($(this.trigger).parent().hasClass('input_container')) {
      $(wrap).append($(this.trigger).parent());
    } else {
      $(wrap).append(this.trigger);
    }
    $(wrap).append(this.flyout);
  }
});
var AjaxSpinner = Class.create({
  init: function(element) {
    this.spinner = document.createElement('div');
       
    this.setAttributes(element);
    this.insert(element);
    
    this.show();
  },
  
  setAttributes: function(element) {
    var id = this.getSpinnerId(element);

    $(this.spinner).addClass('ajax_loading');
    $(this.spinner).attr('id', id);
    $(this.spinner).css('display', 'none');
  },

  insert: function(element) {
    var parent = $(element).parent().get(0); 
    $(this.spinner).appendTo(parent);
  },

  getSpinnerId: function (element) {
    return element.attr('id') + '_spinner';
  },

  hide: function() {
    $(this.spinner).hide();
  },

  show: function() {
    $(this.spinner).show();
  }
});
var EditFormInPlace = Class.create({
  init: function(form, objectCallback, persistant) {
    this.form = form;
    this.attachEdit(form);
    this.attachSave(form, objectCallback);
    this.attachDelete(form, objectCallback);
    this.attachCancel(form);
    this.attachToggle(form);
    this.errorHolder = new ErrorHolder($(form).find('.warning'));
    this.FORM_SELECTED = 'onFormSelected';
    this.FORM_DEFAULT = 'onSetDefault';
    this.FORM_DELETED = 'onDelete';
		this.FORM_CANCELLED = 'onCancel';
    this.persistant = persistant;
    //after creation, set in edit mode
  },

  attachEdit: function(form) {
    var self = this;
    
    $(form).find('.edit').click(function(event) {
      self.transformToEditing();
      event.preventDefault();
    });
  },

  attachDelete: function(form) {
    var self = this;
    var dialogContainer = $("#delete_dialog");
    
    $(form).find('.delete').click(function(event) {
    
    	self.disableOtherFormsEdit(form);
    
    	dialogContainer.dialog('open');
    	dialogContainer.dialog({width:340, modal:true});
    	
    	dialogContainer.find(".yes").click(function(e) {
    		$(self).trigger(self.FORM_DELETED);
    		dialogContainer.dialog('close');
    		e.preventDefault();
    	});
    	
    	dialogContainer.find(".no").click(function(e) {
    		dialogContainer.dialog('close');
    		e.preventDefault();
    	});
 
      event.preventDefault();
    });
  },

  attachSave: function(form, objectCallback) {
    var self = this;
    $(form).find('.save').click(function(event) {
      formValidation = new FormValidation($(form), self.errorHolder);
      if (!formValidation.hasErrors) {
        objectCallback.update(form);
      }
      event.preventDefault();
    });
  },

  attachCancel: function(form) {
    var self = this;
    $(form).find('.cancel').click(function(event) {
    
    	$(self).trigger(self.FORM_CANCELLED);
        
      if(self.persistant){
        self.cancelToViewing(form);
      } else {
        self.remove();
      }  
      
      formValidation = new FormValidation($(form), self.errorHolder);
      formValidation.removeErrors();
      
	    event.preventDefault();
    });
  },

  remove: function(callback) {
    var content = $(this.form).parents('.address');
    var self = this;
    $(this).remove();

    content.fadeOut('fast',function() {
      $(self.form).parents('.address').remove();
      if(typeof callback == "function"){
        callback();
      }
    });
  },

  attachToggle: function(form) {
    var self = this;
    var toggleElement = $(form).find('.primary_toggle input[type=radio]');
    if (toggleElement.attr('checked') == true) {
      toggleElement.parents('.primary_toggle').addClass('default_address');
    }
    toggleElement.click(function(event) {
      $(this).parents('.primary_toggle').addClass('default_address');
      $(self).trigger(self.FORM_DEFAULT);
      event.preventDefault();
    });
  },

  resetForm: function(){
    this.form.reset();
    this.removeChecked();
    //clean P tags for the viewable mode... future refactor!    
    $(this.form).find('input[type=text],select').parents('fieldset').find('p').text('');
  },

  removeChecked: function(){
    $(this.form).find('.primary_toggle input[type=radio]').attr('checked','');
    $(this.form).find('.primary_toggle').removeClass('default_address');
  },

  transformToEditing: function(form) {
    var inputs = $(form).find('input, select, textarea');
    if(typeof form == 'undefined') {
      form = this.form;
    }
    $(form).removeClass('viewing').addClass('editing');
    
    this.disableOtherFormsEdit(form);

    $(inputs).each(function() {
      new EditableField(this);
    });

    $(this).trigger(this.FORM_SELECTED);
    
  },
  
  disableOtherFormsEdit: function(form) { 
  	$(".js_profile_forms").find("form").not(form).each(function(element){
  		if( $(this).hasClass("editing") ){
  			$(this).find(".cancel").eq(0).trigger("click");
  		}
  	});
  },
  
  transformToViewing: function(form) {
    var ptags = $(form).find('p');
    if(typeof form == 'undefined'){
      form=this.form;
    }

    $(form).removeClass('editing').addClass('viewing');

    $(ptags).each(function() {
      new ViewableField(this);
    });
  },

  cancelToViewing: function(form) {
    $(form).get(0).reset();
	  $(form).removeClass('editing').addClass('viewing');
  },

  makeAjaxRequest: function(type, resourceUrl, params, sucessFunction, errorFunction) {
    return $.ajax({
      type     : type,
      url      : resourceUrl,
      data     : params,
      success  : sucessFunction,
      error    : errorFunction
    });
  },

  hideErrors: function() {
    this.errorHolder.clear();
  },

  showErrors: function(errorMessage) {
    this.hideErrors();
    this.errorHolder.add(errorMessage);
  }
});


/* EditableField - Transforms field to edit mode
----------------------------------------------------------------- */
var EditableField = Class.create({
  init: function(input) {
    var p = $(input).parents('fieldset').find('p');

    if($(input).parents('fieldset').hasClass('primary_toggle')) {
      this.setRadioValueForPrimaryToggle(p, input);
    } else {
      if($(input).attr('type') != 'hidden'){
        this.setInputValue(p, input);
      }
    }
  },

  setRadioValueForPrimaryToggle: function(p,input) {
    if($(p).text() == 'Default') {
      $(input).attr('checked', 'checked');
    }
  },

  setInputValue: function(p, input) {
    if($(input).attr('type') != 'hidden' || $(input).attr('type') != 'radio') {
      var value = $(p).text();
      $(input).val(value);
    }
  }
});


/* ViewableField - Transforms field to view mode
----------------------------------------------------------------- */
var ViewableField = Class.create({
  init: function(p) {
    var input = $(p).parents('fieldset').find('input, select, textarea');
    if($(p).parents('fieldset').hasClass('primary_toggle')) {
      this.setTextForPrimaryToggle(p, input);
    } else {
      this.setText(p, input);
    }
  },

  setText: function(p, input) {
    if($(input).attr('type') != 'hidden' || $(input).attr('type') != 'radio') {
      var text = $(input).val();
      $(p).text(text);
    }

    if($(input).attr('type') == 'radio') {
      $(p).text('who are you..');
    }
  },

  setTextForPrimaryToggle: function(p, input) {
    if($(input).attr('checked')) {
      $(p).text($(p).prev().text());
    } else {
      $(p).text('');
    }
  }
});

var PersonalInformation = Class.create({
  init: function(forms_container) {
    this.forms = [];
    this.instance = forms_container;
    this.getForms();
    this.addAddress();
    this.editFormInPlace = {};
    this.observeFirstAddress();
  },

  enableDelete:function(form){
  
		if (form) {
			var value = 0;
	  	var self = this;
	  
	  	var deleteLinks = $(form).find('.delete');
			value = this.getValidFormsLength()[1];
			var editMode = this.getValidFormsLength()[2];
	
			if( value >= 1 && !self.detectEmptyAddress() && !editMode ) {
				deleteLinks.show();
			} else if ( self.detectEmptyAddress()) {
				deleteLinks.hide();
			} else if (editMode) {
			  deleteLinks.hide();
			}
		}  
  },

  getValidFormsLength:function(){
  	var count = 0;
  	var formsWithDelete= 0;
  	var editMode = false;
  	 
  	for (var i = 0; i<this.forms.length; i++){
  	
			if(this.forms[i] != undefined || this.forms[i] != null){
				count++;
				var eachForm = this.forms[i].form;
				if( $(eachForm).find(".delete") ) {
					formsWithDelete++;
				}
				if( $(eachForm).hasClass("editing") ) {
					editMode = true;
				}
				
			}
		}
	
    return [count, formsWithDelete, editMode];  
  },

  getForms: function() {
    var self = this;
    this.forms = new Array();
            
    $(this.instance).find('form').each(function(element) {
      //adding forms with a flag - addresses coming from BE are marked as persistant
      self.addForm(this,false,true);
      self.enableDelete(this);      
    });
    
    if( self.detectEmptyAddress() ) {
    	$('.add_address').hide();
    }
    
  },
  
  detectEmptyAddress: function() {
  	var formCount = $("div.address").length;
    var addressCheck = $("div.address").eq(0).find(".street_address p").text();
    
    if( formCount == 1 && addressCheck == "" ){
    	$('.primary_toggle').removeClass('default_address');
  		return true;
    }
    else {
    	return false;
    }

  },

  detectEditableForms: function() {
    var self = this;
		$('.add_address').hide();
		
    $(self.forms).each(function() {
      if (this != self.editFormInPlace) {
        try {
					this.transformToViewing();		
				} catch(e){};
      }
    });
  },

  detectDefaultForm: function() {
    var self = this;
    $(self.forms).each(function() {
      if (this != self.editFormInPlace) {
        this.removeChecked();
      }
    })
  },

  addForm:function(form, createInEditMode, persistant) {

    var self = this;
    var newForm = new EditFormInPlace(form, this, persistant);
   
   $(newForm).bind(newForm.FORM_SELECTED, function() {
      self.editFormInPlace = this;
      self.detectEditableForms();
    });

   $(newForm).bind(newForm.FORM_DELETED, function() {
      self.editFormInPlace = this;
      self.discard(this.form);
    });
	
	$(newForm).bind(newForm.FORM_CANCELLED, function() {
	  if( !self.detectEmptyAddress() ) {
    	$('.add_address').show();
    }
  });

    $(newForm).bind(newForm.FORM_DEFAULT, function() {
      self.editFormInPlace = this;
      self.detectDefaultForm();
    });

    if (createInEditMode) {
      newForm.transformToEditing();
    }

    this.forms.push(newForm);
    
    return newForm;
  },

  showTwoAddresses: function() {
    if ($("div.address").length == 1) {
      $('.add_address').trigger('click');
    }
  },

  updateLabels:function(){
    var header_re = /Address\s(\d+)/gi; 
   // $(this.instance).find('form ul li h4').each(function(index,elem) {
    $(this.instance).find('.address_number').each(function(index,elem) {
      $(this).text($(this).text().replace(header_re, 'Address ' + (index+1)));
    })    
  },

  addAddress: function() {
    var self = this;
    
	$('.add_address').click(function(event) {
      //self.getValidFormsLength();
	  
    // decrement length only for addAddress method
	  	var counter = self.forms.length -1;
      var copy = $("div.address:last").clone(true);
      var header_re = /Address\s(\d+)/gi;
      var input_re = /_(\d+)/gi;

      if (copy.html().match(header_re)) {
        copy.html(copy.html().replace(input_re, '_' + (counter)));
      }

      $(copy).find('input[type=hidden]').val('');
	  	$(copy).find('.warning').html('');

      $(copy).insertAfter("div.address:last");

      var currentForm = self.addForm($(copy).find('form').get(0), true, false);
      currentForm.form.reset();
      currentForm.removeChecked();
      self.updateLabels();
      self.enableDelete(form.form);     

      event.preventDefault();
    });
  },

  update : function(element) {
    var self = this;

    if ($(element).parents().hasClass('address')) {
      //find a better way to get the form ID -- there is a better way now yoohoo!
      var formIndex=this.forms.indexOf(this.editFormInPlace) -1;
      if(formIndex>0){
        this.makeAjaxRequest(
            "POST",
            PersonalInformation.updateAddressUrl,
            this.prepareAddressParams(formIndex),
            function(addressId) {
              
              $(self.editFormInPlace).find('#pr_address_id_' + formIndex).val('addressId');
              self.editFormInPlace.persistant=true;            
              self.showSuccessMessageOnAddressUpdate(element, addressId, formIndex);
              $('.add_address').show();
              self.enableDelete(element);
            },
            function(validationErrorMessage) {
              self.showErrorMessage(validationErrorMessage);
            }
        );
      }

    } else if($(element).parents().hasClass('primary_email')) {
        this.makeAjaxRequest(
            "POST",
            PersonalInformation.updatePrimaryAddressUrl,
            this.preparePrimaryAddressParams(),
            function() {
              self.emailAddressUpdateSuccess(element);
            },
            function(validationErrorMessage) {
              self.showErrorMessage(validationErrorMessage);
            }
        );
    }else {
      this.makeAjaxRequest(
          "POST",
          PersonalInformation.updateProfileUrl,
          this.prepareProfileParams(),
          function(redirectUrl) {
            self.reportProfileUpdateToOmniture();
            self.showSuccessMessageOnProfileUpdate(element, redirectUrl);
          },
          function(validationErrorMessage) {
            self.showErrorMessage(validationErrorMessage);
          }
          );
    }
  },

  discard : function(element) {
    var self = this;
    // TODO: find a better way of finding the form besides incrementing/dec index - Seamus  
    var formIndex=this.forms.indexOf(this.editFormInPlace)-1;

    if($('#pr_address_id_'+formIndex).val() != '') {
      this.makeAjaxRequest(
          "POST",
          PersonalInformation.discardAddressUrl,
          this.prepareDiscardAddressParams(formIndex),
         
            function(addressId) {
              if($('.pr_edit_address').length > 1) { 
                self.forms[formIndex+1].remove(function() {
                  self.forms[formIndex+1] = null;
  			  			  self.updateLabels();
  			  			  $('.add_address').show();
  			  			  self.enableDelete(element);
                });
              } else {
                self.forms[formIndex+1].resetForm();
                $('.add_address').hide();
              };
              self.showSuccessMessageOnAddressDiscard(element, addressId, formIndex);
              self.enableDelete(element);
            },
          
          function(validationErrorMessage) {
            self.showErrorMessage(validationErrorMessage);
          }
        );
      } else {
        this.forms[formIndex].remove(function() {
	    	$('.add_address').show();
	    });
    };
    self.enableDelete(element);
  },


  prepareProfileParams: function() {
    return {
      '_method': "PUT",
      'firstName': $('#pr_first_name').val(),
      'middleName': $('#pr_middle_initial').val(),
      'lastName': $('#pr_last_name').val(),
      'email': $('#pr_email_id').val(),
      'languagePref': $('#pr_language_pref').val(),
      'zipCode': $('#pr_zip_code').val()
    };
  },

  prepareAddressParams: function(id) {
    return {
      '_method': "PUT",
      'id':$('#pr_address_id_' + id).val(),
      'name.first':$('#pr_address_first_name_' + id).val(),
      'name.middle':$('#pr_address_middle_name_' + id).val(),
      'name.last':$('#pr_address_last_name_' + id).val(),
      'address1':$('#pr_address_line1_' + id).val(),
      'address2':$('#pr_address_line2_' + id).val(),
      'city':$('#pr_city_' + id).val(),
      'state':$('#pr_state_' + id).val(),
      'postalcode':$('#pr_zip_' + id).val(),
      'phoneNumbers[0].number':$('#pr_home_phone_number_' + id).val(),
      'phoneNumbers[0].ext':$('#pr_home_phone_extension_' + id).val(),
      'phoneNumbers[1].number':$('#pr_mobile_phone_number_' + id).val(),
      'phoneNumbers[1].ext':$('#pr_mobile_phone_extension_' + id).val(),
      'defaultAddressId':$('#pr_default_address_' + id).is(":checked") ? true : false
    }
  },

  preparePrimaryAddressParams: function() {
    return {
      '_method': "PUT",
      'email':$('#pr_confirm_email_id').val(),
      'password':$('#pwd_profile_password').val(),
      'uuid':$('#pr_sso_uid').val()
    }
  },

  prepareDiscardAddressParams: function(id) {
    return {
      '_method': "DELETE",
      'id':$('#pr_address_id_' + id).val()
    }
  },

  setEmptyStringOnUndefined :function(value) {
    return value == null ? "" : jQuery.trim(value);
  },

  showSuccessMessageOnProfileUpdate: function(element, redirectUrl) {
    if (redirectUrl != null) {
      window.location.href = redirectUrl;
    }
    this.editFormInPlace.hideErrors();
    this.editFormInPlace.transformToViewing(element);
  },

  showSuccessMessageOnAddressUpdate: function(element, addressId, formId) {
    $('#pr_address_id_' + formId).val(addressId);
    this.editFormInPlace.hideErrors();
    this.editFormInPlace.transformToViewing(element);
  },

  emailAddressUpdateSuccess: function(element) {
    $('#pr_email_id').val($('#pr_confirm_email_id').val());
    this.editFormInPlace.hideErrors();
    this.editFormInPlace.transformToViewing(element);
  },

  showSuccessMessageOnAddressDiscard: function(element, addressId, formId) {
    $('#pr_address_id_' + formId).val(addressId);
  },

  showErrorMessage: function(errorMessage) {
    this.editFormInPlace.showErrors($.evalJSON(errorMessage.responseText));
  },

  makeAjaxRequest: function(type, resourceUrl, params, sucessFunction, errorFunction) {
    return $.ajax({
      type     : type,
      url      : resourceUrl,
      data     : params,
      success  : sucessFunction,
      error    : errorFunction,
      dataType : "json"
    });
  },

  reportProfileUpdateToOmniture: function() {
    var omnitureParamaters = OmnitureProfileFields.prepareOmnitureParams(this.profileFieldsForOmniture());
    OmnitureCall.reportProfileUpdate(omnitureParamaters);
  },

  profileFieldsForOmniture: function() {
    return {
      'FirstName':$('#pr_first_name').val(),
      'MiddleInitial':$('#pr_middle_initial').val(),
      'LastName':$('#pr_last_name').val(),
      'Zipcode':$('#pr_zip_code').val(),
      'Lang': $('#pr_language_pref').val()
    }
  },

  observeFirstAddress: function(){
    $("#pr_profile_1").find('.prepopulator').click(function(event) {

      var personalForm = $(".js_profile_forms").find("form").eq(0);

      var firstName = $(personalForm).find(".firstname p").text();
      var middleName = $(personalForm).find(".middle p").text();
      var lastName = $(personalForm).find(".lastname p").text();

      $("#pr_profile_1").find(".firstname input").val(firstName);
      $("#pr_profile_1").find(".middle input").val(middleName);
      $("#pr_profile_1").find(".lastname input").val(lastName);
    });
  }

});
PersonalInformation.updateProfileUrl = "/shs/update-personal-information!update";
PersonalInformation.updateAddressUrl = "/shs/update-user-address!update";
PersonalInformation.discardAddressUrl = "/shs/delete-user-address!delete";
PersonalInformation.updatePrimaryAddressUrl = "/shs/primary-email-address!update";


var ContactPreferences = Class.create({
  init: function(form) {
    this.editFormInPlace = new EditFormInPlace(form, this,true);
  },

  update : function(element) {
    var self = this;
    this.editFormInPlace.makeAjaxRequest(
      "POST",
      ContactPreferences.updateUrl,
      this.prepareParams(),
      function() {
        self.reportProfileUpdateToOmniture();
        self.showSuccessMessage(element)
      },
      function(errorResponse) {
        self.showErrorMessage(errorResponse)
      }
    );
  },
  prepareParams: function() {
    return {
      '_method': "PUT",
      'optForEmail': $("#email_communications").is(":checked")? "YES":"NO"
    };
  },

  showSuccessMessage: function(element) {
    this.editFormInPlace.hideErrors();
    this.editFormInPlace.transformToViewing(element);
  },

  showErrorMessage: function(errorResponse) {
    this.editFormInPlace.showErrors($.evalJSON(errorResponse.responseText));
  },

  reportProfileUpdateToOmniture: function() {
    var omnitureParamaters = OmnitureProfileFields.prepareOmnitureParams(this.profileFieldsForOmniture());
    OmnitureCall.reportProfileUpdate(omnitureParamaters);
  },

  profileFieldsForOmniture: function() {
    return {
      'OptForEmail': $('#email_communications').is(":checked") ? 'checked' :''
    }
  }

});

ContactPreferences.updateUrl = '/shs/update-contact-preferences!update'
var ChangePassword = Class.create({
  init: function(form) {
    this.editFormInPlace = new EditFormInPlace(form, this,true);
  },
    
  update : function(element) {
    var self = this;
    this.editFormInPlace.makeAjaxRequest(
      "POST",
      ChangePassword.updateUrl,
      this.prepareParams(),
      function() {
        self.reportProfileUpdateToOmniture();
        self.showSuccessMessage(element);
      },
      function(errorResponse) {
        self.showErrorMessage(errorResponse);
      }
    );
  },

  prepareParams: function() {
    return {
      '_method': "PUT",
      'password': $("#pwd_current_password").val(),
      'newPassword': $("#pwd_new_password").val(),
      'emailId': $("#pr_email_id").val()
    };
  },

  showSuccessMessage: function(form) {
    $("#pwd_profile input").val('');
    this.editFormInPlace.hideErrors();
    this.editFormInPlace.transformToViewing(form);
    $("#pwd_information").html("<b>Password changed successfully.</b>");
    $("#pwd_information").show();
    $("#pwd_information").fadeOut(5000, function(){
      $("#pwd_information").html("");
      $("#pwd_information").hide();
    });
  },

  showErrorMessage: function(errorResponse) {
    this.editFormInPlace.showErrors($.evalJSON(errorResponse.responseText));
    $("#pwd_profile").removeClass("js_password_form");
  },

  reportProfileUpdateToOmniture: function() {
    var omnitureParamaters = OmnitureProfileFields.prepareOmnitureParams(this.profileFieldsForOmniture());
    OmnitureCall.reportProfileUpdate(omnitureParamaters);
  },

  profileFieldsForOmniture: function() {
    return {
      'Password': $("#pwd_new_password").val()
    }
  }
});

ChangePassword.updateUrl = "/shs/change-password!update"

var EnhancedTooltip = Class.create({
  init: function(element) {
	  this.element = element;
	  this.dialog = $('#tooltip');
	  this.setConstants();
	  this.attachHover();
	},
	
	setConstants: function() {
		// vertical offset for tooltip
    this.topOffset=30; 
    // horizontal offset for tooltip
    this.leftOffset=-this.dialog.width()/2;
    // default time for the flyover show (miliseconds)
    this.defaultInitTime=200;
	  // can use title or text
	  if($(this.element).attr('title') != '') {
	    this.getTitle();
	  } else {
	    this.getText();
	  }
	},
	
	getTitle: function() {
	  this.text = $(this.element).attr('title');
	  $(this.element).removeAttr('title');
	},
	
	getText: function() {
	  this.text = $(this.element).text();
	},
	
  attachHover: function() {
	  var hoverOver = this.buildHoverOverFunction();
	  var hoverOut = this.buildHoverOutFunction();
	  $(this.element).hover(hoverOver, hoverOut);
  },
  
  buildHoverOverFunction: function() {
    var self = this;
    var element = $(self.element);
    var dialog = $(self.dialog);
	
    var hoverOver = function(event) {
      var x_position = self.getHorizontalPosition(element, self.leftOffset);      
      var y_position = self.getVerticalPosition(element, self.topOffset);
      var timeoutId = "";
      
      dialog.hide();
      clearTimeout($(self.dialog).data("timeoutId"));
      dialog.css('top',y_position);
      dialog.css('left',x_position);
      // for tooltip over ui dialog
      dialog.css('z-index',1010);
      dialog.find('.content').text(self.text);

      timeoutId = setTimeout(function(){
	      $(self.dialog).fadeIn('fast');	
      }
      ,self.defaultInitTime);
	    
      $(self.dialog).data("timeoutId",timeoutId);
    }
    return hoverOver;
  },
  
  buildHoverOutFunction: function(event) {
    var self = this;
    var dialog = $(self.dialog);
    var hoverOut = function() {
      clearTimeout(dialog.data("timeoutId"));
      dialog.hide();
    }
    
    return hoverOut;
  },
  
  getHorizontalPosition: function(reference, offsetLeft) {
    var targetLeft = $(reference).offset().left+($(reference).width()/2)+offsetLeft;
    return targetLeft;
  },
  
  getVerticalPosition: function(reference, offsetTop) {
    var targetTop =	$(reference).offset().top+$(reference).height()+offsetTop;
    return targetTop;
  }
});
var Pagination = Class.create({
  init: function(element) {
    // basic elements
    var pagination = $(element).find('.pagination');
    var controls = $(pagination).find('ul.prev_next');
    // links
    var a = $(pagination).find('a');
    var prev = $(pagination).find('.prev a');
    var next = $(pagination).find('.next a');
    // form
    var form = $(pagination).find('form');
    var select = $(form).find('select');
    var option = $(select).find('option');
    // results block for ajax
    var results = $(element).find('.pagination_results');
    var items = $(results).find('.item');
    // page counts
    var range = $(pagination).find('.range');
    var total = $($(pagination).find('.total')[0]).text();
    
    // methods    
    this.pageCount(option);
    this.initialSetup(next, prev, option, form, controls, items, range, total);
    this.attachNext(next, prev, select, option, results, items, range, total);
    this.attachPrevious(prev, next, select, option, results, items, range, total);
    this.attachPageSelect(select, option, prev, next, results, items, range, total);
  },
  
  pageCount: function(option) {
    var select = $(option).parents('select')[0];
    var option = $(select).find('option');
    this.page_count = $(option).length;
    this.current_page = 1;
  },
  
  initialSetup: function(next, prev, option, form, controls, items, range, total) {
    var href = $($(option)[1]).attr('value');
    var self = this;

    self.updateCounter(items, range, total);     
    if(this.page_count == 1) {
      $(form).hide();
      $(controls).hide();
    } else {
      self.enableNextLink(next, option);
      self.disablePreviousLink(prev); 
    }
  },
  
  attachNext: function(next, prev, select, option, results, items, range, total) {
    var self = this;
    $(next).click(function(event) {
      if($(next).attr('href') != '#') {
        self.updateResults($(this).attr('href'), results);
        self.current_page++;
        self.toggleNextControls(option, next, prev);
        self.updateCounter(items, range, total);
      
        var value = $($(option)[self.current_page-1]).val();
        $(select).val(value);
      }
      event.preventDefault();
    });
  },
  
  attachPrevious: function(prev, next, select, option, results, items, range, total) {
    var self = this;
    $(prev).click(function(event) {
      if($(prev).attr('href') != '#') {
        self.updateResults($(this).attr('href'), results);
        self.current_page--;
        self.togglePreviousControls(option, prev, next);
        self.updateCounter(items, range, total); 
      
        var value = $($(option)[self.current_page-1]).val();
        $(select).val(value);
      }
      event.preventDefault();
    });
  },
  
  attachPageSelect: function(select, option, prev, next, results, items, range, total) {
    var self = this;
    $(select).change(function(event) {
      self.updateResults($(this).val(), results);   
      self.current_page = self.getCurrentPageFromSelect(this, option);

      self.toggleNextControls(option, next, prev);
      self.togglePreviousControls(option, prev, next);      
      self.updateCounter(items, range, total); 
      event.preventDefault();
    });
  },
  
  getCurrentPageFromSelect: function(select, option) {
    var index = 1;
    $(option).each(function() {
      if($(this).val() != $(select).val()) {
        index++;
      } else {
        return false;
      }
    });

    return index;
  },
  
  toggleNextControls: function(option, next, prev) {
    if(this.current_page == this.page_count) {
      this.disableNextLink(next);
    } else {
      this.enableNextLink(next, option);
    }
    
    if(this.current_page == 1) {
      this.disablePreviousLink(prev);
    } else {
      this.enablePreviousLink(prev, option);
    }
  },
  
  togglePreviousControls: function(option, prev, next) {    
    if(this.current_page == 1) {
      this.disablePreviousLink(prev);
    } else {
      this.enablePreviousLink(prev, option);
    }
    
    if(this.current_page == this.page_count) {
      this.disableNextLink(next);
    } else {
      this.enableNextLink(next, option);
    }
  },
  
  enableNextLink: function(next, option) {
    var href = $($(option)[this.current_page]).attr('value');

    $(next).removeClass('disabled');
    $(next).attr('href', href);
  },
  
  enablePreviousLink: function(prev, option) {
    var href = $($(option)[this.current_page-2]).attr('value');
    
    $(prev).removeClass('disabled');
    $(prev).attr('href', href);
  },
  
  disableNextLink: function(next) {
    $(next).addClass('disabled');
    $(next).attr('href', '#');
  },
  
  disablePreviousLink: function(prev) {
    $(prev).addClass('disabled');
    $(prev).attr('href', '#');
  },

  updateResults: function(href, results) {
    $.ajax({
      type: "GET",
      url: href,
      success: function(response) {
        $(results).html(response);
      }
    });
  },
  
  updateCounter: function(items, range, total) {
    var interval = $(items).length;
    if(this.current_page == 1) {
      var start_at = 1;
    } else {
      var start_at = (interval * (this.current_page-1)) + 1;
    }
    
    var end_at = (start_at + interval) - 1;
    if(end_at > total) {
      end_at = total;
    }
    
    $(range).text(start_at + ' to ' + end_at);
  }
});
var LeadAvailability = Class.create({
  init: function(element) {
    this.check();
    $("#lead_aggregator_form_fields :input").removeClass('warning');
  },

  check : function() {
    var self = this;
    this.makeAjaxRequest(
      "GET",
      LeadAvailability.Url,
      self.prepareParams(),
      self.sucessFunction,
      self.errorFunction
    );
  },

  makeAjaxRequest: function(type, resourceUrl, params, sucessFunction, errorFunction) {
    return $.ajax({
      type     : type,
      url      : resourceUrl,
      data     : params,
      success  : sucessFunction,
      error    : errorFunction,
      dataType : "json"
    });
  },

  prepareParams: function() {
    return {
      '_method': "GET",
      'zipCode': $("#lead_zipcode").val(),
      'selectedProductId': $("#lead_productId").val(),
      'selectedProductDescription': $("#lead_productId option:selected").text()
    };
  },

  sucessFunction: function(form) {
    $('.warning').hide();
    $("#lead_aggregator_warning").hide();
    $("#lead_aggregator_form_fields").removeClass('disabled');
    $("#lead_aggregator_form_fields :input").removeAttr('disabled').removeClass('disabled');
  },

  errorFunction: function(errorResponse) {
    $("#lead_aggregator_warning").html($.evalJSON(errorResponse.responseText));
    $('.warning').show();
    $("#lead_aggregator_warning").show();
    $("#lead_aggregator_form_fields").addClass("disabled");
    $("#lead_aggregator_form_fields").attr("disabled", "disabled");
  }
    
});

LeadAvailability.Url = "/shs/lead-aggregator!checkAvailability"

var LeadShipAppointment = Class.create ({
  init : function(element) {
    var element = element;
  },

  initialize: function() {
    var self = this;
    this.hideTimePicker();
    //$('#lead_aggregator_appointment_section').removeClass('ajax_loading');
    this.selectDate = new SelectDate(function(selectedDate) {
      self.updateTimeSlots(selectedDate);
    }, "lead_aggregator_calendar");
    this.getDates();
  },

  
  // HI Marketing doesnt want to show the time picker. but it needs to be selected
  hideTimePicker: function(){
     $("div.date_and_time").addClass("faux_hide");
  },

  getDates: function() {
    var self = this;
    $("#lead_aggregator_time_preference").show();
    var successFunction = function(datesData) {
      $('#lead_aggregator_appointment_section').show();
      self.datesData = datesData;
      self.selectDate.fillDates(datesData["shipDateTimeSlots"]);
//      self.updateHiddenVariables(datesData);
      $('#lead_aggregator_appointment_section').removeClass('ajax_loading');
    };
    var errorFunction = function(data) {
      if(data.readystate == 4 && !data.status == 0){
        window.location.href = '/shs/lead-confirmation?error=true'
      }
    };
    this.makeAjaxRequest("GET", LeadShipAppointment.Url, this.prepareParams(), successFunction, errorFunction);
  },

//  updateHiddenVariables: function(datesData) {
//    $("#driveTime").val(datesData.driveTime);
//    $("#latitude").val(datesData.latitude);
//    $("#longitude").val(datesData.longitude);
//    $("#officeId").val(datesData.officeId);
//  },

  updateTimeSlots: function(selectedDate) {
    var self = this;
    var timeSlots;
    $("#chosenDate").val(selectedDate);
    jQuery.each(this.datesData["shipDateTimeSlots"], function() {
      if (this.date == selectedDate) {
        timeSlots = jQuery.map(this["timeSlots"], function(datum) {
          return datum;
        });
        self.showTimeSlots(timeSlots);
      }
    });
  },

  showTimeSlots: function(timeSlots) {
    var self = this;
    var name = 'lead_aggregator_time_preference';

    jQuery.each(timeSlots, function(index, timeslot) {
      var timeSlot = new TimeSlot(name, index, timeslot.time, function(input_value) {
        self.selectedTime = input_value;
        $("#chosenDate").val(self.selectedDate);
      });

      $(timeSlot.option).appendTo($('#time_slots'));
      $(timeSlot.option).attr("salesRepId", timeslot.salesRepId)
      $(timeSlot.option).attr("overnightAreaId", timeslot.overnightAreaId)
    });
  },

  prepareParams: function() {
    return {
      '_method': "GET",
      'zipCode': $("#schedule_zipcode").val(),
      'product': $("#schedule_productId").val(),
      'service': "Home Improvement",
      'serviceType': "home_improvement",
      'city': $("#schedule_city").val(),
      'state': $("#schedule_state").val(),
      'address': $("#schedule_streetAddress1").val()
    };
  },

  makeAjaxRequest: function(type, resourceUrl, params, sucessFunction, errorFunction) {
    return $.ajax({
      type     : type,
      url      : resourceUrl,
      data     : params,
      success  : sucessFunction,
      error    : errorFunction,
      dataType : "json"
    });
  }

})

LeadShipAppointment.Url = '/shs/shipDateAvailabilityJSON'
var ToggleSimpleContainer = Class.create({
  init: function(element) {
    this.element = $(element);
    this.toggler = $(element).find('.toggler');
    this.container = $(element).find('.simple_container');
    
    if(!$(this.container).hasClass('hide')) {
      this.close();
    }
    this.toggleEvent();
  },
  
  toggleEvent: function() {
    var that = this;
    
    $(this.toggler).each(function() {
      $(this).click(function(event) {
        if($(this).hasClass('expanded')) {
          that.close();
        } else {
          that.expand();
        }
        event.preventDefault();
      });
    });
  },
  
  expand: function() {
    $(this.toggler).addClass('expanded');
    $(this.container).removeClass('hide');
  },
  
  close: function() {
    $(this.toggler).removeClass('expanded');
    $(this.container).addClass('hide');
  }
  
});
//carousel

var Carousel = Class.create({
    init: function(carousel,itemsNumber,dataSrc,isVertical) {
	    this.dataSource=dataSrc;
	    this.itemsNumber=itemsNumber;
	    this.setupConstants();
	    this.setupInit(itemsNumber,isVertical);
	    this.setupUI(carousel);
    },
    
/************************************************************
  constants
  IMPORTANT: We must set the width/height explicitly. No width/height causes infinite loops.
  (taken from the original jCarousel reference)
************************************************************/
    setupConstants:function(){
	//constants
	this.DIALOG_PADDING=10;
	this.VIDEO_ZINDEX=2000;
	this.SPLASH_URL='/shs/images/icons/carousel_video_big.gif';
	this.PLAYER_ID='videoPlayer';
	this.PLAYER_WIDTH=480;
	this.PLAYER_HEIGHT=360;
	this.FLOWPLAYER_URL='/shs/swf/flowplayer-3.1.3.swf';
	this.THUMBNAIL_SUFFIX='_Thumbnail.jpg';
	this.ELEMENT_WIDTH=75;
	this.ELEMENT_HEIGHT=75;
	this.ITEM_BORDER=1;
	this.EMPTY_CONTAINER_CONTENT='...';
	this.THUMBNAIL_ERROR='Thumbnail not available';
	this.PICTURE_ERROR='Sorry, there is no detailed image for this selection.';
    },
    
    setupInit:function(itemsNumber,isVertical){
	var self=this;
	this.visibleElements=itemsNumber;
	this.elementsStep=itemsNumber;
	this.isVertical=isVertical;
	this.itemsInfo=[];
	this.parent={};
	this.carousel={};
	this.itemsCallback=function(){};
	
	this.detailDialogConfig={
	    bgiframe: true,
	    modal: true,
	    autoOpen:false,
	    draggable:false,
	    resizable:false,
	    minHeight:300,
	    minWidth:300,
	    width:'auto',
	    dialogClass:'carousel_item_detail',
	    open: function(event, ui){
		self.onOpenDialog();
	    },
	    close: function(event, ui){
		self.onCloseDialog();
	    }
	};
 	//this.elementsStep=4;
    },

/************************************************************
  UI setup
************************************************************/
    onOpenDialog:function(){
		var callback=this.itemsCallback;
		$('body').css('overflow','hidden');
		$('.ui-dialog').css('visibility','hidden');
		$('.ui-widget-overlay').removeClass('loaded');
		
		if(typeof callback != 'undefined'){
		    callback();
		}
    },
    
    onCloseDialog:function(){
		$(this.detailDialog).find('img').remove();
		$('body').css('overflow','');
		if(isIE6()||isIE7()){
		//if(isIE()){
			$(this.videoContainer).stop();
		}
		$(this.videoContainer).hide();
    },

    setPlayerDefault:function(container){
		this.videoContainer=document.createElement('div');
		$(this.videoContainer).css('height',this.PLAYER_HEIGHT).css('width',this.PLAYER_WIDTH).css('position','absolute').css('top','0');	
		$(container).append(this.videoContainer);
    },

    setupUI:function(carousel,vertical){
		var self=this;
		this.carousel=carousel;
		this.parent=carousel.parentNode;
		this.detailDialog=document.createElement('div');
		this.setPlayerDefault('body');
		/*
		    taking out the carousel of its original container and appending to the body
		    done to avoid errors produced when the container have 'display:none'
		    the carousel returns to its original container once is loaded in the setContainer function
		*/
		
		$('body').append(carousel);
		$('body').append(this.detailDialog);
		$(this.detailDialog).dialog(self.detailDialogConfig);
		$('.jcarousel-list li,.jcarousel-item').css('width',this.ELEMENT_WIDTH);
		$('.jcarousel-list li,.jcarousel-item').css('width',this.ELEMENT_WIDTH);
			    
		$(carousel).jcarousel({
		    scroll: self.elementsStep,
		    vertical:self.isVertical,
		    
		    itemLoadCallback:function(carousel, state){
			self.itemLoadCallback(carousel, state)
		    },
		    
		    itemVisibleInCallback: function(carousel, item, index, state){
			if($(item).html()==self.EMPTY_CONTAINER_CONTENT){
			    carousel.add(index,self.getItemHTML(self.itemsInfo[index-1]));
			}
		    }
		});
    },
 
/************************************************************ 
    callback after every new item is loaded
************************************************************/
    createCarouselItems:function(carousel, first, last, data){
	var content="";
	carousel.unlock();
	//method to implement - see parseData
	this.itemsInfo=this.parseData(data);
	for (i = 0; i < this.itemsInfo.length; i++) {	
	    if(i<this.visibleElements){ 
	      content=this.getItemHTML(this.itemsInfo[i]);
	    }else{
	      content=this.EMPTY_CONTAINER_CONTENT;
	    }
	    carousel.add(i+1,content);
	}
	
	carousel.size(this.itemsInfo.length);
	this.setContainer();
    },
	
/************************************************************
  Callback after carousel load
************************************************************/
    itemLoadCallback:function(carousel, state){
		if (state != 'init'){
		    return;
		}
		carousel.lock();
		this.loadDataSource(carousel)
    },

    loadDataSource: function(carousel) {
		this.createCarouselItems(carousel, carousel.first, carousel.last, this.dataSource);
    },
	
/************************************************************
    Resize the carousel to display the selected number of items
************************************************************/
    setContainer:function(){
	var targetProperty="";
	var targetValue=this.ITEM_BORDER;
	
	if($(this.carousel).parents('div.jcarousel-container').hasClass('jcarousel-container-horizontal')){
	    targetProperty='width';
	    targetValue+=
	    this.ELEMENT_WIDTH+getNumericValue($('.jcarousel-item-horizontal').css('margin-right'));
	}else{
	    targetProperty='height';	
	    targetValue+=
	    this.ELEMENT_HEIGHT+getNumericValue($('.jcarousel-item-vertical').css('margin-bottom'));
	}
	targetValue*=this.visibleElements;
	
	/*
	    the carousel returns to its original container once its settings are fully loaded
	    (gotta decide if use append or prepend for the "welcome home" op... using append meanwhile)
	*/
	
	$(this.parent).append($(this.carousel).parents('div.jcarousel-container').parents('div'));
	
	$(this.carousel).parents('div.jcarousel-container').css(targetProperty,targetValue);
	$(this.carousel).parents('div.jcarousel-container').css('position','relative');
	$(this.carousel).parents('div.jcarousel-container').css('visibility','visible');
	$(this.carousel).children('li').each(function(){
	    if(($(this).html()).replace(/\s+/,'').length == 0){
		$(this).remove();
	    }
	});
    },
	
/************************************************************
    ajax response parser function
    
    TODO: Refactor this function to the AJAX response used (see parseData)
************************************************************/
    parseData:function(data){
	var tmpData=data.replace(/(^\s*\||\|$)|(\W+$)/g,'');
	var tmpDataArray = tmpData.split('|');
	return tmpDataArray
    },
	
/************************************************************
    inner HTML helper for the content of the items (writing in DOM)
************************************************************/
    getItemHTML:function(url){
	url=url.replace(/\s+/,'');
	var self=this;
	var element=document.createElement('a');
	var replaceableExtensionsExp=/\.(jpg|flv|mp4)\s*/gi;
	var extension=url.substr(url.lastIndexOf('.'));
	var thumbnailUrl = url.replace(replaceableExtensionsExp,this.THUMBNAIL_SUFFIX);
	var elementType=((extension=='.flv')||(extension=='.mp4'))?'video':'image';
	
	$(element).attr('href', url);
	$(element).addClass(elementType);
	
	$(element).append(self.setImageItem(thumbnailUrl,function(){},function(){
	    $(element).addClass('error');
	    $(element).html(self.THUMBNAIL_ERROR);
	}));
	
	$(element).click(function(event) {
	    event.preventDefault();
	    self.itemsCallback=self.getContextualBehavior(extension,url,self)
	     $(self.detailDialog).dialog('open');
	});
	return element;
    },

    getContextualBehavior:function(extension,url,self){
	var f={};
	if((extension=='.flv')||(extension=='.mp4')){
	    f=function(){
		self.setVideoItem(self.videoContainer,url,function(){
		//self.setVideoItem(self.detailDialog,url,function(){
		    $(self.detailDialog).css('width',self.PLAYER_WIDTH);
		    $(self.detailDialog).css('height',self.PLAYER_HEIGHT);
		    self.defaultDialogPosition(self.detailDialog);
		    
		    $(self.videoContainer).css('z-index',self.VIDEO_ZINDEX);
		    $(self.videoContainer).css('top',$(self.detailDialog).parent().position().top+self.DIALOG_PADDING);
		    $(self.videoContainer).css('left',$(self.detailDialog).parent().position().left+self.DIALOG_PADDING);
		    
		    if(isIE6()||isIE7()){
		    //if(isIE()){
			$(self.videoContainer).show(0,$f(self.videoContainer).play());
		    }else{
			$(self.videoContainer).show();
		    }
		});
	    };
	    
	}else{
	    f=function(){
		$(self.detailDialog).append(self.setImageItem(url,function () {    	    
		    self.defaultDialogPosition(self.detailDialog);    
		},function(){
		    $(self.detailDialog).html(self.PICTURE_ERROR);
		}));
	    };
	}
	return f;
    },

    setImageItem:function(url,onSuccess,onError){
	var imgContainer=new Image();
	$(imgContainer).load(onSuccess).error(onError).attr('src', url);
	return imgContainer;
    },
    
    setVideoItem:function(itemContainer,url,onSuccess){
	var self=this;
	if(typeof $f() == 'undefined'){
	    $(itemContainer).flowplayer(this.FLOWPLAYER_URL,{ 
		clip: { 
		    url: url, 
		    autoPlay: true,
		    scaling:'fit'
		},
		onLoad:onSuccess,
		plugins:  {
		    controls:  {
			backgroundColor: '#666666',
			backgroundGradient: 'none',
			all:false,
			scrubber:true,
			volume:true,
			mute:true,
			play:true,
			height:30,
			progressColor: '#0033FF',
			progressGradient:'none',
			buttonColor:'#999999',
			bufferColor: '#333333',
			tooltips: { 
			    buttons: true
			},
			tooltipColor: '#FFFFFF', 
			tooltipTextColor: '#333333'  
		    }
		}
	    });
	}else{
	    onSuccess();
	}
    },

/************************************************************
  Position adjustments for dialogs
************************************************************/
    defaultDialogPosition:function(itemContainer){
	$(itemContainer).dialog('option', 'position', ['center','center']);
	$('.ui-dialog').css('visibility','visible');
	$('.ui-widget-overlay').addClass('loaded');
    }
});
//carousel

var CarouselGallery = Class.create({
    init: function(carousel,itemsNumber) {
	    this.carouselReady = false;
		this.itemsNumber=itemsNumber;
	    this.setupConstants();
	    this.setupInit(itemsNumber,carousel);
	    this.setElements();
	    this.attachBehaviors();
		if ($(carousel).is(':visible')) {
			this.setupUI();
		}
    },
	
    setupConstants:function(){
		//constants
		this.ITEMS_PADDING = 48;
		this.BORDER_WIDTH = 1;
		this.CAROUSEL_CLASSNAME = '.jcarousel-skin-enhanced-gallery';
    },
    
    attachBehaviors:function(carousel){
		var self=this;
		this.container = $(this.carousel).parents('div').get(0);
		
		$(this.carousel).find('a.lightbox').each(function(){
		    self.lightbox.attachOpener(this);
		});
		
		$(this.container).bind('visible',function(){
			self.setupUI();
		})
    },
    
    getInternalWidth:function(carousel){
		var value=0;
		var self=this;
		$(this.carousel).find('.jcarousel-item').each(function(){
		    value+=this.offsetWidth+self.BORDER_WIDTH;
		});
		return value;
    },
    
    setupInit:function(itemsNumber,carousel){
		this.visibleElements=itemsNumber;
		this.elementsStep=itemsNumber;
		this.itemsInfo=[];
		this.parent={};
		this.carousel=carousel;
		this.itemsCallback=function(){};
		this.lightbox=new Lightbox();
    },
    
    setElements:function(){
		$(this.carousel).find('li:last').css('border-right','none');
		$(this.carousel).find('li:last').css('padding-right',this.ITEMS_PADDING);
		$(this.carousel).find('li:first').css('padding-left',this.ITEMS_PADDING);
    },
    
	show:function(element){
		$(this.ui).prependTo(this.container);
		$(this.ui).removeClass('faux_hide');
	},
	
	hide:function(element){	
		
		$(this.ui).addClass('faux_hide');
		$(this.ui).appendTo('body');
	},

    
/************************************************************
 
	IMPORTANT:
	----------
	There is a "trick" to make the carousel hide/show possible that must be used due an 
	"No width/height causes infinite loops" (taken from the original jCarousel reference) error
	so it can't be created if the ":visible" selector in jQuery equals true.
	
	To fix this we have used a faux-hide class (position absolute + visibility hidden) and 
	the carousel must be place changed of parent (current parent -> <body>) while is not visible
	and taken back when visible (<body> -> original parent)
	
************************************************************/
	
    setupUI:function(){
		var self = this;
		
		if (!self.carouselReady) {
			
			$(this.carousel).jcarousel({
				initCallback: function(){
					self.ui = $(self.carousel).parents(self.CAROUSEL_CLASSNAME).get(0);
					if (self.ui.offsetWidth > self.getInternalWidth(self.carousel)) {
						$(self.ui).css('width', self.getInternalWidth(self.carousel) + self.ITEMS_PADDING);
					}
					
					self.carouselReady = true;
				},
				reloadCallback:function(){
					
					if(!$(self.carousel).is(':visible')){
						self.hide();	
					}
				}
			});
		}else{
			self.show();
		}
    }
});
var SpotlightGallery = Class.create( {

	init: function(element) {
		this.element = element;
		//gallery
    this.gallery = $(this.element).find('.gallery');
		this.items  = $(this.gallery).find('.gallery_item');
		//controls
		this.controls = $(this.element).find('.controls');
	  this.prev = $(this.controls).find('.prev');
	  this.next = $(this.controls).find('.next');
	  //constants
	  var total_items = this.items.length - 1;
		this.current_item = 1;
    this.first_item = $(this.items)[0];
    this.last_item = $(this.items)[total_items];
		this.duration = 'normal';
		
    this.initialSetup();
	},

	initialSetup: function() {
    if(this.items.length > 0) {
			$(this.items[0]).addClass('active').siblings().hide();
      
			if(this.items.length > 1) {
        this.showControls();
			} else {
        this.hideControls();
      }

    } else {
      $(this.element).hide();
    }

	},

  showControls: function() {
		this.showNext();
		this.showPrev();
  },

  hideControls: function() {
    this.controls.hide();
  },

	showNext: function() {
		var that = this;
		
		$(this.next).click(function(event) {
      var active_item = $(that.element).find('.active');
		  that.nextItem(active_item);
		  event.preventDefault();
	  });
	},
	
	showPrev: function() {
		var that = this;
		
		$(this.prev).click(function(event) {
      var active_item = $(that.element).find('.active');
			that.prevItem(active_item);
		  event.preventDefault();
	  });
	},
  
  nextItem: function(active_item) {
    var that = this; 
    
    $(active_item).fadeOut(that.duration, function() {
	    $(this).removeClass('active');
	    
      if(that.current_item == that.items.length) {
        $(that.first_item).addClass('active').fadeIn(that.duration);
      } else {
        $(this).next().addClass('active').fadeIn(that.duration);
      }
      
      if(that.current_item == that.items.length) {
        that.current_item = 1;
      } else {
        that.current_item++;
      }
    });	
  },
  
  prevItem: function(active_item, x) {
    var that = this; 
    
		$(active_item).fadeOut(that.duration, function() {
			$(this).removeClass('active');
			
      if(that.current_item == 1) {
        $(that.last_item).addClass('active').fadeIn(that.duration);
      } else {
        $(this).prev().addClass('active').fadeIn(that.duration);
      }
      
      if(that.current_item == 1) {
        that.current_item = that.items.length;
      } else {
        that.current_item--;
      }
		});
  }
});
//Lightbox using UI-dialog from JQuery UI

var Lightbox = Class.create({
    init: function() {
	    this.setupConstants();
	    this.setupInit();
	    this.setupUI();
    },
    
/************************************************************
  constants
  IMPORTANT: We must set the width/height explicitly. No width/height causes infinite loops.
  (taken from the original jCarousel reference)
************************************************************/
    setupConstants:function(){
		//constants
		this.DIALOG_PADDING=10;
		this.VIDEO_ZINDEX=2000;
		this.SPLASH_URL='/shs/images/icons/carousel_video_big.gif';
		this.PLAYER_ID='videoPlayer';
		this.PLAYER_WIDTH=480;
		this.PLAYER_HEIGHT=346;
		this.FLOWPLAYER_URL='/shs/swf/flowplayer-3.1.3.swf';
		this.PICTURE_ERROR='Sorry, there is no detailed image for this selection.';
    },
    
    setupInit:function(){
		var self=this;
		this.labelsInfo="";
		this.detailDialogConfig={
		    bgiframe: true,
		    modal: true,
		    autoOpen:false,
		    draggable:false,
		    resizable:false,
		    minHeight:300,
		    minWidth:300,
		    width:'auto',
		    dialogClass:'carousel_item_detail',
		    open: function(event, ui){
				self.onOpenDialog();
		    },
		    close: function(event, ui){
				self.onCloseDialog();
		    }
		};
    },

/************************************************************
  UI setup
************************************************************/
    onOpenDialog:function(){
		var callback=this.itemsCallback;
		$('body').css('overflow','hidden');
		$('.ui-dialog').css('visibility','hidden');
		$('.ui-widget-overlay').removeClass('loaded');
		this.addLabels(this.labelsInfo);
		if(typeof callback != 'undefined'){
		    callback();
		}
    },
    
    onCloseDialog:function(){
		$(this.detailDialog).find('img').remove();
		$('body').css('overflow','');
	    
		if(isIE6()||isIE7()){
			$(this.videoContainer).stop();
		}
		$(this.videoContainer).hide();
    },

    addLabels:function(URIString){
		$(this.detailDialog).siblings('p').remove();
		var labels=new Array();
		var block=document.createElement('p');
		$(block).addClass('content');
		if(URIString.length>0){
		  $(URIString.split('&')).each(function(index,element){
			  var elem=document.createElement('span');
			  $(elem).text((this.split('=')).join(':'));
			  labels.push(elem);
		  });
		}
		$(block).html(labels)
		$(this.detailDialog).after(block);
    },
    
    setPlayerDefault:function(container){
		this.videoContainer=document.createElement('div');
		$(this.videoContainer).css('height',this.PLAYER_HEIGHT).css('width',this.PLAYER_WIDTH).css('position','absolute').css('top','0');	
		$(this.videoContainer).addClass('faux_hide');
		$(container).append(this.videoContainer);
    },

    setupUI:function(){
		this.detailDialog=document.createElement('div');
		this.setPlayerDefault('body');
		$('body').append(this.detailDialog);
		$(this.detailDialog).dialog(this.detailDialogConfig);
    },
	
/************************************************************
    inner HTML helper for the content of the items (writing in DOM)
************************************************************/
    attachOpener:function(element){
		  var self=this;
		  var url=$(element).attr('href');

		  var extension=url.substr(url.lastIndexOf('.'));
		  $(element).click(function(event) {
		    event.preventDefault();
		    self.itemsCallback=self.getContextualBehavior(extension,url,self)
        self.labelsInfo=$(element).attr('title');
  		  $(self.detailDialog).dialog('open');
		  });
		  return element;
    },

    getContextualBehavior:function(extension,url,self){
		var f={};
		if((extension=='.flv')||(extension=='.mp4')){
		    f=function(){
				self.setVideoItem(self.videoContainer,url,function(){
				//self.setVideoItem(self.detailDialog,url,function(){
				    $(self.detailDialog).css('width',self.PLAYER_WIDTH);
				    $(self.detailDialog).css('height',self.PLAYER_HEIGHT);
				    self.defaultDialogPosition(self.detailDialog);
				    
				    $(self.videoContainer).css('z-index',self.VIDEO_ZINDEX);
				    $(self.videoContainer).css('top',$(self.detailDialog).parent().position().top+self.DIALOG_PADDING);
				    $(self.videoContainer).css('left',$(self.detailDialog).parent().position().left+self.DIALOG_PADDING);
				    $(this.videoContainer).removeClass('faux_hide');
				    
				    if(isIE6()||isIE7()){
				    //if(isIE()){
						$(self.videoContainer).show(0,$f(self.videoContainer).play());
				    }else{
						$(self.videoContainer).show();
				    }
				});
		    };   
		}else{
		    f=function(){
				$(self.detailDialog).append(self.setImageItem(url,function () {    	    
				    self.defaultDialogPosition(self.detailDialog);    
				},function(){
				    $(self.detailDialog).html(self.PICTURE_ERROR);
				}));
		    };
		}
		return f;
    },

    setImageItem:function(url,onSuccess,onError){
		var imgContainer=new Image();
		$(imgContainer).load(onSuccess).error(onError).attr('src', url);
		return imgContainer;
    },
    
    setVideoItem:function(itemContainer,url,onSuccess){
	var self=this;
	if(typeof $f() == 'undefined'){
	    $(itemContainer).flowplayer(this.FLOWPLAYER_URL,{ 
		clip: { 
		    url: url, 
		    autoPlay: true,
		    scaling:'fit'
		},
		onLoad:onSuccess,
		plugins:  {
		    controls:  {
			backgroundColor: '#666666',
			backgroundGradient: 'none',
			all:false,
			scrubber:true,
			volume:true,
			mute:true,
			play:true,
			height:30,
			progressColor: '#0033FF',
			progressGradient:'none',
			buttonColor:'#999999',
			bufferColor: '#333333',
			tooltips: { 
			    buttons: true
			},
			tooltipColor: '#FFFFFF', 
			tooltipTextColor: '#333333'  
		    }
		}
	    });
	}else{
	    onSuccess();
	}
    },

/************************************************************
  Position adjustments for dialogs
************************************************************/
    defaultDialogPosition:function(itemContainer){
	$(itemContainer).dialog('option', 'position', ['center','center']);
	$('.ui-dialog').css('visibility','visible');
	$('.ui-widget-overlay').addClass('loaded');
    }
});
// JS class observer

var JSClassObserver = Class.create({
  findElements: function(property, callback) {
    var self = this;
    
    $('.' + property).each(function(index, element) {
      self.setupNamespace(element);
      
      if(self.shouldAttachBehavior(element, property)) {
        var new_element = self.attachBehavior(element, index);
        
        element = self.updateElement.call(self, element, new_element);
        
        self.setProperty(element, property);
        $(element).removeClass(property);
      }
    });
    
    if(typeof callback != 'undefined') {
      callback();
    }
  },

  findTags: function(tag_selector, property) {
    var self = this;
    $(tag_selector).each(function(index, element) {
      
      self.setupNamespace(element);
      
      if(self.shouldAttachBehavior(element, property)) {
        self.attachBehavior(element, index);
        self.setProperty(element, property);
      }
      
    });
  },
  
  setupNamespace: function(element) {
    if(element.js_attached == null) {
      element.js_attached = {};
    }
  },
  
  shouldAttachBehavior: function(element, property) {
    return element.js_attached[property] != true;
  },
  
  updateElement: function(element, new_element) { 
    if(typeof new_element != "undefined") {
      element = new_element;
      this.setupNamespace(element);
    }
    return element;
  },

  setProperty: function(element, property) {
    element.js_attached[property] = true;
  }

});
var JSClassTrackingObserver = Class.create(JSClassObserver.prototype, {
  attachBehavior: function(element) {
    var tracking_name;
    var classes = $(element).attr('class').split(' ');
    for (var i = 0; i < classes.length; i++) {
      if (classes[i].match('js_tracking_')) {
        tracking_name = classes[i].replace('js_tracking_','').replace(/_/g," ");
        $(element).removeClass(classes[i]);
      }
    }
    this.attachTrackingBehavior(element, tracking_name);
  }
});
var DialogObserver = {};

DialogObserver.attachDialog = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_dialog');
  },
  attachBehavior: function(element) {
    var dialog = new Dialog(element);
    $(element).click(function(event) {
      event.preventDefault();
      dialog.configure($(this), { x:event.pageX, y:event.pageY });
      dialog.open();
    });
  }
});

DialogObserver.attachRecaptchaDialog = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_dialog_with_captcha');
  },
  attachBehavior: function(element) {
    var dialog = new Dialog(element);

    this.wrapCloseFunctionToReCreateCaptcha(dialog);

    $(element).click(function(event) {
      event.preventDefault();
      dialog.configure($(this), { x:event.pageX, y:event.pageY });
      dialog.open();
      ReCaptchaCreator.createCaptcha('recaptcha_container');
    });
  },

  wrapCloseFunctionToReCreateCaptcha: function(dialog) {
    var closeFunction = dialog.getCloseFunction();
    var self = this;
    var closeFunctionWrapper = function(event, ui){
       //If page has recaptcha, it gets removed when recaptcha is added to dialog.
      //We need to recreate it on the page, when dialog closes.
      if(self.pageHasRecaptchaContainer()) {
        self.recreateRepatchaOnPage();
      }
      if(closeFunction != null) {
        closeFunction(event, ui);
      }
    }
    dialog.setCloseFunction(closeFunctionWrapper);
  },

  recaptchaContainerElementId:"recaptchaaaaaa",

  idSelector:function(id) {
    return '#' + id;
  },
  
  pageHasRecaptchaContainer:function() {
    return ($(this.idSelector(this.recaptchaContainerElementId)).length > 0);
  },

  recreateRepatchaOnPage:function() {
    ReCaptchaCreator.createCaptcha(this.recaptchaContainerElementId);
  }
});



DialogObserver.attachLoginDialog = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_login_dialog');
  },
  attachBehavior: function(element) {
    var dialog = new Dialog(element);
    $(element).click(function(event) {
      LoginObserver.resetLoginDialog();
      event.preventDefault();
      dialog.configure($(this), { x:event.pageX, y:event.pageY });
      dialog.open();
      // Store the current location of user
      $("#sourceUrl").val($("#srcUrl").text());
      var userIdCookie = $.cookie("userid");
      if(userIdCookie != null && userIdCookie != "null") {
        $("#inp_email").val($.cookie("userid"));
      }
      FormObserver.attachAllObservers();
    });
  }
});

DialogObserver.attachAllObservers = function() {
  new DialogObserver.attachDialog();
  new DialogObserver.attachRecaptchaDialog();
}
// Button observers
var ButtonObserver = {};

ButtonObserver.attachConstructButton = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_button'); 
  },
  attachBehavior: function(element) {
    var button = new Button(element);
    var newElementToReplaceOriginalElement = button.element;
    return newElementToReplaceOriginalElement;
  }
});

ButtonObserver.attachAllObservers = function() {
  new ButtonObserver.attachConstructButton();
}
var LinkObserver = {};

LinkObserver.opened_windows = [];

LinkObserver.attachExternalLink = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_external_link');
  },
  attachBehavior: function(element) {
    $(element).click(function(event) {
      new_window = window.open($(this).attr('href'));
      LinkObserver.opened_windows.push(new_window);
      event.preventDefault();
    });
  }
});

LinkObserver.attachShowContainer = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_show_container');
  },
  attachBehavior: function(element) {
    $(element).click(function(event) {
      // TODO: Refactor to be more general
      var container = $(element).parent();
      
      if($(container).hasClass('hide')) {
        $(container).removeClass('hide').addClass('show');
      } else {
        $(container).next('.hide').removeClass('hide').addClass('show');
      }
      
      event.preventDefault();
    });
  }
});

LinkObserver.attachHideContainer = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_hide_container');
  },
  attachBehavior: function(element) {
    $(element).click(function(event) {
      var container = $(element).parents('.show');
      var form = $(element).parents('form');
      var warning = $(form).find('.warning');
      
      $(container).removeClass('show').addClass('hide');
      $(warning).empty();
      
      event.preventDefault();
    });
  }
});

LinkObserver.attachPrintLink = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_print');
  },
  attachBehavior:function(element) {
    $(element).click(function(event) {
      event.preventDefault();
      window.print();
    });
  }
});


LinkObserver.attachAllObservers = function() {
  new LinkObserver.attachExternalLink();
  new LinkObserver.attachHideContainer();
  new LinkObserver.attachShowContainer();
  new LinkObserver.attachPrintLink();
}
// UI Widgets (home accordion, flyover openers, etc) observers

var UIObserver = {};

UIObserver.flyover = {};

UIObserver.attachAccordion = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_accordion');
  },
  attachBehavior: function(element) {
    $(element).accordion({
      collapsible: true,
      autoHeight: false,
      active: 0
    });
  }
});

UIObserver.attachFlyoverOpener = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_flyoverOpener');
  },
  attachBehavior: function(element) {
    new Flyover(element, UIObserver.flyover);
  }
});


UIObserver.attachFlyover = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_flyover');
  },
  attachBehavior: function(element) {
    $.ui.dialog.defaults.bgiframe = true;
    UIObserver.flyover = $(element).dialog({
      autoOpen:false,
      draggable:false,
      resizable:false,
      minHeight:180,
      minWidth:390,
      width:390
    });

    var hoverOver = function() {
      clearTimeout($(UIObserver.flyover).data("timeoutId"));
    }

    var hoverOut = function() {
      var timeoutId = setTimeout(function() {
        $(UIObserver.flyover).dialog('close');
      }, 500);

      $(UIObserver.flyover).data("timeoutId", timeoutId);
    }

    $(element).parents('div.ui-dialog').hover(hoverOver, hoverOut);
  }
});

UIObserver.attachAccessOrderDialog = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_anchor_dialog');
  },
  attachBehavior: function(element) {
    // Errors coming from this

    var dialog = $(element).dialog({
      autoOpen:false,
      draggable:false,
      resizable:false,
      minHeight:180,
      minWidth:351,
      width:351
    });
    new AccessOrder(element, dialog);

  }
});

UIObserver.attachListToggler = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('toggle_list');
  },
  attachBehavior: function(element) {
    new ListToggler(element);
  }
});

UIObserver.attachClickToCall = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_click_to_call');
  },
  attachBehavior: function(element) {
    $(element).click(function(event) {
      OmnitureCall.reportToolUsage("click to call");
      window.open($(element).attr('href'), height=1, width=1);
      event.preventDefault();
    });
  }
});

UIObserver.attachClickToChat = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.index = 0;
    this.findElements('js_click_to_chat', function() {

      if (typeof ii_247Var == 'undefined') {
        if (window.ii_247VarObj) {
          ii_247Var = new ii_247VarObj();
        }
      }
    });
  },
  attachBehavior: function(element, index) {
    // Click to chat ID's must be unique (third party code...)
    $(element).attr('id', 'id_SmartButton_' + this.index);
    //console.log('placeholder');
    this.index++;
  }
});

/*
  Tweaked Click to chat for marketing pages
*/
UIObserver.attachClickToChatButton = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_click_to_chat_button');
  },
  attachBehavior: function(element) {
    $(element).append('<div class="click_to_chat_container js_click_to_chat"/>');
    new UIObserver.attachClickToChat();
  }
});

UIObserver.attachToggleAjaxResponse = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_toggle_ajax');
  },
  attachBehavior: function(element) {
    $(element).click(function(event) {
      new ToggleAjaxResponse(element);

      event.preventDefault();
    });
  }
});

UIObserver.attachPagination = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_pagination');
  },
  attachBehavior:function(element) {
    new Pagination(element);
  }
});

UIObserver.attachFilterSearchResults = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_filter_search_results');
  },
  attachBehavior:function(element) {
    new FilterSearchResults(element);
  }
});

UIObserver.attachUpdateProductsList = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_update_products_list');
  },
  attachBehavior:function(element) {
    new UpdateProductsList(element);
  }
});

UIObserver.attachPersonalInformationForm = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_personal_information');
  },
  attachBehavior:function(element) {
    new PersonalInformation(element);
  }
});

UIObserver.attachChangePasswordForm = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_change_password_form');
  },
  attachBehavior:function(element) {
    new ChangePassword(element);
  }
});

UIObserver.attachContactPreferencesForm = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_contact_preferences_form');
  },
  attachBehavior:function(element) {
    new ContactPreferences(element);
  }
});

UIObserver.attachSwitchableContent = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_content_switcher');
  },
  attachBehavior:function(element) {
    var cIndex=0;
    var contents=$(element).find('.js_state');
    var contentLabel=$(element).find('.js_label');
    var self=this;
    
    $(element).data('currentContent',0);
    
    
    $(element).find('.js_next_case,.js_previous_case').click(function(e){
      e.preventDefault();
      $(contents).hide();
      $(contentLabel).text($(this).attr('title'));
    });
    
    if(contents.length>0){
      $(contents).each(function(index,content){
	$(content).find('.js_next_case').click(function(){
	  cIndex=self.getCircularIndex(contents,index+1)
	  $(element).data('currentContent',cIndex);
	  $(contents[cIndex]).show();
	});
	
	$(content).find('.js_previous_case').click(function(){
	  cIndex=self.getCircularIndex(contents,index-1)
	  $(element).data('currentContent',cIndex);
	  $(contents[cIndex]).show();
	});
	
	$(contents).hide();
	$(contents[0]).show(); 
      });   
    }
  },
  
  getCircularIndex:function(array,index){
    var cIndex=(index>=0)?index%array.length:array.length-(index%array.length);
    return cIndex;
  }
});


UIObserver.attachEnhancedTooltip = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.createTooltip();
    this.findElements('js_tooltip');
  },
  createTooltip:function() {
    var element = document.createElement('div');
    element.setAttribute('id', 'tooltip');
    $('body').append(element);
    $(element).html(
        '<div class="header"></div>' +
        '<div class="content"></div>' +
        '<div class="footer"></div>'
        );
  },
  attachBehavior:function(element) {
    new EnhancedTooltip(element);
  }
});

UIObserver.attachBannerAnimation = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_banner_animation');
  },
  attachBehavior:function(element) {
    new BannerAnimation(element);
  }
});

UIObserver.attachShowMessage = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_show_message');
  },
  attachBehavior:function(element) {
    var showMessage = new ShowMessage(element);
  }
});

UIObserver.attachTabs = Class.create(JSClassObserver.prototype, {
	init: function() {
		this.findElements('js_tabs');
	},
	attachBehavior: function(element){
		$(element).tabs({
			show: function(event, ui){
				$(ui.panel).trigger('visible');
        OmnitureCall.reportHITabsDisplay($(ui.tab).text());
      },
			select:function(event,ui){
				//replace by the omniture line
				//the value inside 'trace' function is the id of the current tab
				//trace('tab to omniturd:'+$(ui.tab).text());
			}
		});
		if(isIE6){
			$('ul.ui-tabs-nav').find('li.ui-state-active > a').trigger('click');
		}
	}
});

UIObserver.attachLightbox = Class.create(JSClassObserver.prototype, {
  init: function() {
  	this.lightbox=new Lightbox();
    this.findElements('js_lightbox');
  },
  attachBehavior:function(element) {
    this.lightbox.attachOpener(element);
  }
});

UIObserver.attachShortenLinksForIE = Class.create(JSClassObserver.prototype, {
	init: function() { 
		this.findElements('js_shorten_links'); 
	},
	attachBehavior: function(element) {
		if (isIE) { 
			$(element).find("td.description a").each(function(e,i) {
			
				var hrefTxt = $(this).text();
				var hrefTxtLength = $(this).text().length;
				var hrefBreaker = 40;
				
				if (hrefTxtLength > hrefBreaker) { 
					$(this).html(hrefTxt.substring(0,hrefBreaker)).append("<br />").append(hrefTxt.substring(hrefBreaker,hrefTxtLength));
				} 
			}); 
		}
	}
});

UIObserver.attachSpotlightGallery = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_spotlight_gallery');
  },
  attachBehavior:function(element) {
    new SpotlightGallery(element);
  }
});

UIObserver.attachSubmitOnEnterKey = Class.create(JSClassObserver.prototype, {
	init: function() {
		this.findElements('js_enter_submit');
	},
	attachBehavior: function(element) {
    $(element).keyup(function(event) {
      if (event.keyCode == 13) {
        $(element).parent().find(".js_enter_submit_link").click();
        event.preventDefault();
      }
    })
  }
});

UIObserver.attachToggleSimpleContainer = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_toggle_simple_container');
  },
  attachBehavior:function(element) {
    new ToggleSimpleContainer(element); 
  }
});

UIObserver.attachGeoLocation = Class.create(JSClassObserver.prototype, {
  init:function() {
    this.findElements('js_iplocation');
  },
  attachBehavior: function(element) {
    new GeoLocation(element);
  }
});

UIObserver.attachAllObservers = function() {
  new UIObserver.attachAccordion();
  new UIObserver.attachFlyover();
  new UIObserver.attachFlyoverOpener();
  new UIObserver.attachListToggler();
  new UIObserver.attachClickToCall();
  new UIObserver.attachClickToChatButton();
  new UIObserver.attachClickToChat();
  new UIObserver.attachToggleAjaxResponse();
  new UIObserver.attachPagination();
  new UIObserver.attachFilterSearchResults();
  new UIObserver.attachUpdateProductsList();
  new UIObserver.attachPersonalInformationForm();
  new UIObserver.attachChangePasswordForm();
  new UIObserver.attachContactPreferencesForm();
  new UIObserver.attachEnhancedTooltip();
  new UIObserver.attachSwitchableContent();
  new UIObserver.attachBannerAnimation();
  new UIObserver.attachShowMessage();
  new UIObserver.attachTabs();
  new UIObserver.attachLightbox();
  new UIObserver.attachSubmitOnEnterKey();
  new UIObserver.attachSpotlightGallery();
  new UIObserver.attachToggleSimpleContainer();
  new UIObserver.attachGeoLocation();
}
// Form observers

var FormObserver = {};

FormObserver.attachSubmitForm = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_submit_form');
  },
  attachBehavior: function(element) {
    var form = $(element).parents('form').get(0);
    var warning = $(form).find('.warning');

    if ($(warning).length != 0) {
      var errorHolder = new ErrorHolder(warning);
    }
    var self = this;
    $(element).click(function(event) {
      if ($(warning).length != 0) {
        formValidation = new FormValidation($(element).parents('form'), errorHolder);
      } else {
        formValidation = new FormValidation($(element).parents('form'));
      }

      var form = $($(element).parents('form'));
      var ajax_submit = $(form).hasClass('ajax');
      var dialog = $(form).parents('.ui-dialog-content');
      if (!formValidation.hasErrors) {
        self.submitRequest(form, dialog, ajax_submit, errorHolder);
      }
      event.preventDefault();
    });
    
    this.attachKeypressSubmit(form, element);
  },

  attachKeypressSubmit:function(form, submitTrigger) {
    $(form).find('.submit_trigger').keyup(function(event) {
      if(event.keyCode == 13) {
        $(submitTrigger).click();
        event.preventDefault();
      }
    })
  },

  submitRequest : function(form, dialog, ajax_submit, errorHolder) {
    if (ajax_submit) {
      this.submitAjaxRequest(form, dialog, errorHolder);
    } else {
      $(form).submit();
    }
  },

  submitAjaxRequest:function(form, dialog, errorHolder) {
    var onSuccess = function(redirectUrl) {
      if (dialog) {
        $(dialog).dialog('close');
      }
    }
    var onError = function(xmlHttpRequest) {
      errorHolder.clear();
      var errors = $.evalJSON(xmlHttpRequest.responseText);
      for (var error in errors) {
        if ((isIE() && (typeof errors[error] != 'function')) || (!isIE())) {
          //patch needed to fix an issue related to the IE ArrayIndexOf in browsers_functions.js
          errorHolder.add(errors[error]);
        }
      }

    }
    $.ajax({
      url:$(form).attr('action'),
      data:$(form).serialize(),
      type:"POST",
      success:onSuccess,
      error:onError,
      dataType :"json"
    });
  }
});

FormObserver.attachInfoBox = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_info_box');
  },
  attachBehavior: function(element) {
    new InfoBox(element);
  }
});

FormObserver.attachPromptText = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_prompt_text');
  },
  attachBehavior: function(element) {
    new PromptText(element);
  }
});

FormObserver.attachConstrainToNumbers = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_numbers_only');
  },
  attachBehavior: function(element) {
    new NumbersOnly(element);
  }
});

FormObserver.attachTextbox = Class.create(JSClassObserver.prototype, {
  init: function() {
    if (!isIE6()) {
      this.findTags('textarea, input[type=text], input[type=password]', 'js_textbox');
    }
  },
  attachBehavior: function(element) {
    var parents = $(element).parents('.custom');
    if (!$(element).hasClass('custom') && !$(parents).hasClass('custom')) {
      new Textbox(element);
    }
  }
});

FormObserver.attachCharacterCount = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_character_count');
  },
  attachBehavior: function(element) {
    new CharacterCount(element);
  }
});

FormObserver.attachAllObservers = function() {
  new FormObserver.attachSubmitForm();
  new FormObserver.attachPromptText();
	new FormObserver.attachInfoBox();
  new FormObserver.attachConstrainToNumbers();
  new FormObserver.attachTextbox();
  new FormObserver.attachCharacterCount();
}


// Scheduler observer

var SchedulerObserver = {};

SchedulerObserver.attachAccordion = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_scheduler');
  },
  attachBehavior: function(element) {
    SchedulerObserver.scheduler = new Scheduler(element);
  }
});

SchedulerObserver.attachStartButton = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_start');
  },

  attachBehavior: function(element) {
    $(element).click(function(event) {
      SchedulerObserver.scheduler.order.populate();

      var service = $('#service');
      if ($(service).val() != $(service).attr('title')) {
        $(service).trigger('change');
      }
    });
  }
});

SchedulerObserver.attachNextButton = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_next');
  },

  attachBehavior: function(element) {
    $(element).click(function(event) {
      if (!$(this).hasClass('disabled')) {
        SchedulerObserver.scheduler.next(element);
      }
      event.preventDefault();
    });
  }
});

SchedulerObserver.attachPreviousButton = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_previous');
  },
  attachBehavior: function(element) {
    $(element).click(function(event) {
      SchedulerObserver.scheduler.previous(element);
      event.preventDefault();
    });
  }
});

SchedulerObserver.attachExitButton = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_exit');
  },
  attachBehavior: function(element) {
    $(element).click(function(event) {

      if (!$(this).hasClass('disabled')) {
        SchedulerObserver.scheduler.resetToStart();
      }
      event.preventDefault();
    });
  }
});


SchedulerObserver.attachSchedulerOpenTracking = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_scheduler_open_tracking');
  },
  attachBehavior: function(element) {
    $(element).click(function() {
      SchedulerObserver.attachLinkForCancel = Class.create(JSClassObserver.prototype, {
        init: function() {
          this.findElements('js_cancel_order');
          this.cancelCalled = false;
        },
        attachBehavior: function(element) {
          var self = this;
          $(element).click(function(event) {
            if (!self.cancelCalled) {
              self.cancelCalled = true;
              $("#cancel_dialog").show();
              var cancelHandler = new CancelHandler($(this));
              cancelHandler.initialize(event);
              event.preventDefault();
            }
          });
        }
      });

      OmnitureCall.reportSchedulerOpen();
    });
  }
});

SchedulerObserver.attachSchedulerNextTracking = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_scheduler_next_tracking');
  },
  attachBehavior: function(element) {
    $(element).click(function() {
      var idStepHash = {go_to_step_two: 'Step 1', go_to_step_three: 'Step 2',
        schedule_service:'Schedule Confirmation'};
      var elementId = $(element).attr('id');
      var product_name = SchedulerService.productNameForService($("#service :selected").val());
      OmnitureCall.reportSchedulerMacroView(idStepHash[elementId], $("#zip_code").val(), $("#service").val(), product_name,
          $('#firstAvailableDate').val(), $('#selectedDate').text());
      if (Order.canBeAddedToCart($("#service").val()) && elementId == 'schedule_service') {
        OmnitureCallSearsVertical.reportAddToCart(";" + $("#service").val().toUpperCase() + " " + product_name);
      }
    });
  }
});

SchedulerObserver.attachZipTracking = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_scheduler_zip_tracking');
  },
  attachBehavior: function(element) {
    $(element).change(function() {
      if (Zipcode.isValid($(this).val())) {
        $.cookie('zipcode', $(this).val(), {path:"/"});
        SchedulerObserver.scheduler.order.populate();
      }
    });
  }
});

SchedulerObserver.attachFieldTracking = Class.create(JSClassTrackingObserver.prototype, {
  init: function() {
    this.findElements('js_field_tracking');
  },
  attachTrackingBehavior: function(element, field_name) {
    $(element).change(function() {
      var product_name = SchedulerService.productNameForService($("#service :selected").val());
      var state;
      if (field_name == "state") state = $("#state").val();
      OmnitureCall.reportSchedulerMicroView(field_name, $("#zip_code").val(), $("#service").val(), product_name, state);
    });
  }
});

SchedulerObserver.attachOpenSchedulerOnLoad = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_open_on_load');
  },

  attachBehavior: function(element) {
    SchedulerObserver.scheduler.openSchedulerOnLoad(element);
    OmnitureCall.reportChannelOnSchedulerOpen();
  }
});

SchedulerObserver.attachProactiveChat = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_proactive_chat');
  },

  attachBehavior: function(element) {
    var proactiveChat = null;

    $(element).click(function(event) {
      if ($('#scheduler').hasClass('repair')) {
        proactiveChat = 4;
      }
      event.preventDefault();
    });
  }

});

SchedulerObserver.attachOmnitureSchedulerStartEvent = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_omniture_event1');
  },

  attachBehavior: function(element) {
    $(element).click(function() {
      OmnitureCall.reportSchedulerStart();
    });
  }
});

SchedulerObserver.attachSelectFlyoutTrigger = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_select_flyout_trigger');
  },

  attachBehavior: function(element) {
    var scheduler = $('#scheduler');
    var inputs = $(scheduler).find('select, input[type=text]');
    var parent = $(element).parent('div');
    var newHeight = 500;
    var originalHeight = 250;

    $(element).click(function() {
      $(parent).addClass('pick_a_problem');
      $(scheduler).height(newHeight);
      if(isIE6()) {
        $(inputs).hide();
      }
    });
    $(element).mouseleave(function() {
      $(parent).removeClass('pick_a_problem');
      $(scheduler).height(originalHeight);
      if(isIE6()) {
        $(inputs).show();
      }
    });
  }
});

SchedulerObserver.attachSelectFlyoutLister = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_select_flyout_lister');
  },

  attachBehavior: function(element) {
    var scheduler = $('#scheduler');
    var parent = $(element).parent('div');
    var checkbox = $(element).find(':input');
    var list = $(element).find('ul');

    $(checkbox).each(function() {
      var label = $(this).siblings('label');
      $(this).toggle(
        function() {
          $(label).addClass('checked');
        },
        function() {
          $(label).removeClass('checked');
        }
      );
    });
  }
});

 SchedulerObserver.attachAllResetObservers = function(){
     new SchedulerObserver.attachAccordion();
     new SchedulerObserver.attachNextButton();
     new SchedulerObserver.attachStartButton();
     new SchedulerObserver.attachPreviousButton();
     new SchedulerObserver.attachExitButton();
     new SchedulerObserver.attachSchedulerOpenTracking();
     new SchedulerObserver.attachSchedulerNextTracking();
     new SchedulerObserver.attachZipTracking();
     new SchedulerObserver.attachFieldTracking();
     new SchedulerObserver.attachOmnitureSchedulerStartEvent();
     new SchedulerObserver.attachProactiveChat();
     new SchedulerObserver.attachSelectFlyoutTrigger();

}
SchedulerObserver.attachAllObservers = function() {
  new SchedulerObserver.attachAllResetObservers();
  new SchedulerObserver.attachOpenSchedulerOnLoad(); // Imp: attachOpenSchedulerOnLoad should always be the last observer
}

var CarouselObserver = {};

CarouselObserver.attachProductGalleryCarousel = Class.create(JSClassObserver.prototype, {
  init: function() {
    CarouselObserver.carousels = [];
    this.itemsNumber = 6;
    this.findElements('js_product_gallery_carousel');
  },

  attachBehavior: function(element) {
    var originalElement = $(element).children('li:first-child');
    var dataSource = originalElement.text();
    $(originalElement).remove();
    CarouselObserver.carousels.push(new Carousel(element, this.itemsNumber, dataSource));
  }
});


CarouselObserver.attachHIProductGalleryCarousel = Class.create(JSClassObserver.prototype, {
  init: function() {
    CarouselObserver.carousels = [];
    this.findElements('js_gallery_carousel');
  },

  attachBehavior: function(element) {
    CarouselObserver.carousels.push(new CarouselGallery(element));
  }
});

CarouselObserver.attachAllObservers = function() {
    new CarouselObserver.attachProductGalleryCarousel();
    new CarouselObserver.attachHIProductGalleryCarousel();
}
var ReCaptchaCreator = {};

ReCaptchaCreator.createCaptcha = function(captchaContainerId) {
  Recaptcha.create($("#recaptchaPublicKey").val(), captchaContainerId, {
        theme: "red",
        tabindex: 0,
        callback: Recaptcha.focus_response_field
    });
}
var ReCaptchaObserver = {};

ReCaptchaObserver.attachReCaptcha = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_recaptcha');
  },
  attachBehavior: function(element) {
    ReCaptchaCreator.createCaptcha(element);
  }
});

ReCaptchaObserver.attachAllObservers = function() {
  new ReCaptchaObserver.attachReCaptcha();
}
/******************* Fieldset observers

 Secuential attachment of events to create flows...
 a future refactor is needed to create the Class "flow"
 and model all this stuff?
 */

// TODO: clean me up!!

var SchedulerValidationObserver = {};

SchedulerValidationObserver.steps = [];

SchedulerValidationObserver.attachValidateZipAndService = Class.create(JSClassObserver.prototype, {
  fieldset:{},

  init: function() {
    if($('#scheduler').length == 1) {
      //$('#scheduler').parents('form')[0].reset();
      this.findElements('js_validate_zip_and_service');
    }
  },

  attachBehavior: function(element) {
    var self = this;
    $('#add_service').hide();
    $('.product.fieldset_wrap').parents('fieldset').hide();
    $('.product_group.fieldset_wrap').parents('fieldset').hide();
    $('.install_product_category.fieldset_wrap').parents('fieldset').hide();
    $('.install_product_options.fieldset_wrap').parents('fieldset').hide();

    //$('#go_to_step_two').addClass('blocked');
    //$('#go_to_step_three').addClass('blocked');
    // $('#schedule_service').addClass('blocked');

    $('#add_service').click(function(event) {
      event.preventDefault();
    });

    this.fieldset = new SchedulerValidation(element, {
      onComplete:function() {
        $('#add_service').hide();
        $('#county').removeClass('js_required');
        $('#go_to_step_two').addClass('disabled');

        if($('#service').val() != 'cleaning'){
           $('#add_service').hide();
        }

        if($('#service').val() != 'home_improvement'){
          SchedulerObserver.scheduler.resetHeight($('#step_two'),35);
          $('.home_improvement_only').hide();
        } else {
           SchedulerObserver.scheduler.resetHeight($('#step_two'),50);
            $('.home_improvement_only').show();
        }

        if($('#service').val() == 'repair' && ($("#warranty").find(':selected').attr("phonesupport") == "true") ){
          SchedulerObserver.scheduler.resetHeight($('#step_two'));
        }

        if ($('#service').val() == 'repair') {
          SchedulerValidationObserver.steps[1] = new SchedulerValidationObserver.attachValidateProductGroup();

        } else if ($('#service').val() == 'installation') {
          SchedulerValidationObserver.steps[1] = new SchedulerValidationObserver.attachValidateInstallationProductCategory();
          $('#county').addClass('js_required');

        } else {
          SchedulerValidationObserver.steps[1] = new SchedulerValidationObserver.attachValidateProduct();
          $('.product.fieldset_wrap').parents('fieldset').show();
          $('.product_group.fieldset_wrap').parents('fieldset').hide();
        }
      },
      onError:function() {
        $('.product.fieldset_wrap').parents('fieldset').hide();
        $('.product_group.fieldset_wrap').parents('fieldset').hide();
        $('.install_product_category.fieldset_wrap').parents('fieldset').hide();
        $('#go_to_step_two').addClass('disabled');
        $('#dynamicDescription').html('Tell us where you live<br/> and what you need.');
        SchedulerObserver.scheduler.resetHeight($('#step_two'));
      }
    }, schedulerStep1ErrorHolder);
  }
});

SchedulerValidationObserver.attachValidateProduct = Class.create(JSClassObserver.prototype, {
  fieldset:{},

  init: function() {
    this.findElements('js_validate_product');
  },

  attachBehavior: function(element) {

    $('#product').change(function() {
      $('p.price').html('<em>$</em>0');
    });

    $(element).show('fast');

		// IE Has this weird bug where it doesn't want to move forward, so we must force it
   /* if(isIE()) {
      if($(element).find('option').length <= 1) {
        SchedulerObserver.scheduler.next($('#go_to_step_two'));
      }
    }*/

    this.fieldset = new SchedulerValidation(element, {
      onError:function(){},
      onComplete:function() {

        delete SchedulerValidationObserver.steps[2];

        if ($('#product:visible')) {
          if($('#product').val() == $('#product').attr('title')) {
            $('#go_to_step_two').addClass('disabled');
          } else if($('#scheduler').hasClass('carry_in')) {
            $('#go_to_step_two').removeClass('disabled').removeClass('blocked');
          } else {
            $('#go_to_step_two').removeClass('disabled');
          }
          $(element).find('option[value=]').remove();


          // the handle being passed is #go_to_step_two, which adds css to the element and breaks the style of the button 
          // see scheduler.js lines 117-125
          if (($(element).parents('.container').hasClass('short_step'))&&($('#store_locator:visible').length == 0)){
            SchedulerObserver.scheduler.next($('#go_to_step_two'));
          }


          if ($('#scheduler').hasClass('cleaning')) {
            SchedulerValidationObserver.steps[2] = new SchedulerValidationObserver.attachValidateCleaningInfo();
          }

          if ($('#scheduler').hasClass('home_improvement')) {

            SchedulerValidationObserver.steps[2] = new SchedulerValidationObserver.attachValidateShippingInfo();
          }

          if ($('#scheduler').hasClass('repair')) {
            SchedulerValidationObserver.steps[2] = new SchedulerValidationObserver.attachValidateRepairInfo();
          }

          if ($('#scheduler').hasClass('installation')) {
            SchedulerValidationObserver.steps[2] = new SchedulerValidationObserver.attachValidateInstallationProductOption();
          }
        }
      }
    },schedulerStep1ErrorHolder);
  }
});


SchedulerValidationObserver.attachValidateCleaningInfo = Class.create(JSClassObserver.prototype, {
  fieldset:{},

  init: function() {
    this.findElements('js_validate_cleaning_info');
  },
  attachBehavior: function(element) {
    this.fieldset = new SchedulerValidation(element, {
      onComplete:function() {
        $(element).find('option[value=]').remove();

        if($('#scheduler').hasClass('cleaning')){
          $('#add_service').show('fast');
        }
      },
      onError:function() {
         $('#add_service').hide();
      }
    }, schedulerStep1ErrorHolder);
  }
});


SchedulerValidationObserver.attachValidateAdditionalService = Class.create(JSClassObserver.prototype, {
  fieldset:{},

  init: function() {
    this.findElements('js_validate_additional_service');
  },

  attachBehavior: function(element) {
    var self=this;
    $('#add_service').hide();

    this.fieldset = new SchedulerValidation(element, {
      onComplete:function() {
        $(element).find('option[value=]').remove();
        if($('#scheduler').hasClass('cleaning')){
          $('#add_service').show('fast');
        }
      },
      onError:function(){
        $('#add_service').hide();
      }
    }, schedulerStep1ErrorHolder);

  }
});



SchedulerValidationObserver.attachValidateShippingInfo = Class.create(JSClassObserver.prototype, {
  fieldset:{},

  init: function() {
    this.findElements('js_validate_shipping_info');
  },
  attachBehavior: function(element) {
    this.fieldset = new SchedulerValidation(element, {
        onComplete:function() {
          $(element).find('option[value=]').remove();
          // Copy address info in last stop
          $('#address').val($('#address_line_1').val());
          $('#city').val($('#ship_city').val());
          $('#state').val($('#ship_state').val());
        }
      }, schedulerStep1ErrorHolder);

    this.fieldset.validate();
  }
});

SchedulerValidationObserver.attachValidateProductGroup = Class.create(JSClassObserver.prototype, {
  fieldset:{},

  init: function() {
    this.findElements('js_validate_product_group');
  },
  attachBehavior: function(element) {
    var self = this;
    $(element).show('fast');
    this.fieldset = new SchedulerValidation(element, {
      onComplete:function() {
        $('#go_to_step_two').addClass('disabled');
        SchedulerValidationObserver.steps[3]=new SchedulerValidationObserver.attachValidateProduct();
        $(element).find('option[value=]').remove();
        $('.product.fieldset_wrap').parents('fieldset').show();
      }
    }, schedulerStep1ErrorHolder);
  }
});

SchedulerValidationObserver.attachValidateInstallationProductCategory = Class.create(JSClassObserver.prototype, {
  fieldset:{},

  init: function() {
    this.findElements('js_validate_install_product_category');
  },
  attachBehavior: function(element) {
    var self = this;
    $(element).show('fast');
    this.fieldset = new SchedulerValidation(element, {
      onComplete:function() {
        $('#go_to_step_two').addClass('disabled');
        SchedulerValidationObserver.steps[3]=new SchedulerValidationObserver.attachValidateProduct();
        if(isIE()) {
          new SchedulerValidationObserver.attachValidateInstallationProductOption();
        }
        $(element).find('option[value=]').remove();
        $('.product.fieldset_wrap').parents('fieldset').show();
      },
      onError:function(){
          //To-do attach some error
      }
    }, schedulerStep1ErrorHolder);
  }
});

SchedulerValidationObserver.attachValidateInstallationProductOption = Class.create(JSClassObserver.prototype, {
  fieldset:{},

  init: function() {
    this.findElements('js_validate_install_product_options');
  },
  attachBehavior: function(element) {
    this.fieldset = new SchedulerValidation(element, {}, schedulerStep1ErrorHolder);
  }
});

SchedulerValidationObserver.attachValidateRepairInfo = Class.create(JSClassObserver.prototype, {
  fieldset:{},

  init: function() {
    this.findElements('js_validate_repair_info');
  },
  attachBehavior: function(element) {
    this.fieldset = new SchedulerValidation(element, {}, schedulerStep1ErrorHolder);
  }
});

SchedulerValidationObserver.attachContactInfo = Class.create(JSClassObserver.prototype, {
  fieldset:{},

  init: function() {
    this.findElements('js_validate_contact_info');
  },
  attachBehavior: function(element) {
    var validation = new SchedulerValidation(element, {});
    $('#scheduler').data('infoValidation',validation);
  }
});

SchedulerValidationObserver.attachTimeInfo = Class.create(JSClassObserver.prototype, {
  fieldset:{},

  init: function() {
    this.findElements('js_time_info');
  },
  attachBehavior: function(element) {
    this.fieldset = new SchedulerValidation(element, {}, schedulerStep2ErrorHolder);
  }
});

SchedulerValidationObserver.attachAllObservers = function() {
  //Check out why is the undefined evaluation

  //if(typeof schedulerStep1ErrorHolder == 'undefined') {
    schedulerStep1ErrorHolder = new ErrorHolder($('#scheduler #step_one .warning'));
  //}

  schedulerStep2ErrorHolder = new ErrorHolder($('#scheduler #step_two .warning'));

  //if(typeof schedulerStep3ErrorHolder == 'undefined') {
    schedulerStep3ErrorHolder = new ErrorHolder($('#scheduler #step_three .warning'));
  //}

  SchedulerValidationObserver.steps[0] = new SchedulerValidationObserver.attachValidateZipAndService();
  new SchedulerValidationObserver.attachContactInfo();

  //following the way of Pune mods for validation
  new SchedulerValidationObserver.attachTimeInfo();
}
var OmnitureObserver = {};


OmnitureObserver.attachAnswersSearch = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_omniture_answers');
  },
  attachBehavior: function(element) {
    $(element).click(function() {
      var searchTerm = $('#blue_crew_question_term').val();
      OmnitureCall.reportBlueCrewAnswersSearch(searchTerm);
    });
  }
});

OmnitureObserver.attachViewAllAnswers = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_omniture_view_all_answers');
  },
  attachBehavior: function(element) {
    $(element).click(function() {
      var searchTerm = $('#blue_crew_question_term').val();
      OmnitureCall.reportBlueCrewViewAllAnswers(searchTerm);
    });
  }
});

OmnitureObserver.attachFindAPart = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_omniture_find_a_part');
  },
  attachBehavior: function(element) {
    $(element).click(function() {
      OmnitureCall.reportPartsDirect(element);
    });
  }
});

OmnitureObserver.attachClickToChatReporting = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_omniture_click_to_chat');
  },
  attachBehavior: function(element) {
    $(element).click(function() {
      OmnitureCall.reportClickToChatUsage();
    });
  }
});

OmnitureObserver.attachFindAManual = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_omniture_find_a_manual');
  },
  attachBehavior: function(element) {
    $(element).click(function() {
      OmnitureCall.reportManageMyHome(element);
    });
  }
});

OmnitureObserver.attachToolUsage = Class.create(JSClassTrackingObserver.prototype, {
  init: function() {
    this.findElements('js_omniture_tool_usage');
  },
  attachTrackingBehavior: function(element,tracking_name) {
    $(element).click(function() {
      OmnitureCall.reportToolUsage(tracking_name);
    });
  }
});

OmnitureObserver.attachAjaxToolUsage = Class.create(JSClassTrackingObserver.prototype, {
  init: function() {
    this.findElements('js_ajax_omniture_tool_usage');
  },
  attachTrackingBehavior: function(element,tracking_name) {
    $(element).click(function() {
      OmnitureCall.reportAjaxToolUsage(tracking_name);
    });
  }
});

OmnitureObserver.attachBrowseByService = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_browse_by_service');
  },
  attachBehavior: function(element) {
    $(element).click(function() {
      OmnitureCall.reportServiceFinding("Browse by service");
    });
  }
});

OmnitureObserver.attachBrowseByRoom = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_browse_by_room');
  },
  attachBehavior: function(element) {
    $(element).click(function() {
      OmnitureCall.reportServiceFinding("Browse by room");
    });
  }
});
OmnitureObserver.attachBrowse = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_browse');
  },
  attachBehavior: function(element) {
    $(element).click(function() {
      OmnitureCall.reportServiceFinding("Browse");
    });
  }
});

OmnitureObserver.attachEmail = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_omniture_email');
  },
  attachBehavior: function(element) {
    $(element).click(function() {
      OmnitureCall.reportToolUsage("Help");
    });
  }
});

OmnitureObserver.attachReadAnswer = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_omniture_read_answer');
  },
  attachBehavior: function(element) {
    $(element).click(function() {
      OmnitureCall.reportAnswerShowMore($(element).siblings(".question_title").text());
    });
  }
});


OmnitureObserver.attachExpertAnswers = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_omniture_view_all_answers_tools_usage');
  },
  attachBehavior: function(element) {
    $(element).click(function() {
      OmnitureCall.reportToolUsage("Expert Answers");
    });
  }
});

OmnitureObserver.attachBrowseBySeviceCategory = Class.create(JSClassTrackingObserver.prototype, {
  init: function() {
    this.findElements('js_omniture_service_categories');
  },
  attachTrackingBehavior: function(element,tracking_name) {
    $(element).click(function() {
      OmnitureCall.reportServiceFinding(tracking_name);
    });
  }
});

OmnitureObserver.attachCancelEvents = Class.create(JSClassTrackingObserver.prototype, {
  init: function() {
    this.findElements('js_omniture_cancel');
  },
  attachTrackingBehavior: function(element, tracking_name) {
    var eventsHash = {'yes':'event27', 'no':'event28'};
    $(element).click(function() {
      var cancellation_message = ($("#cancel_dialog_product_message").text() == '')? "repair: default message":"repair: product message";
      OmnitureCall.reportCancelEvent(eventsHash[tracking_name], cancellation_message);
    });
  }
});

OmnitureObserver.attachLeadStepEvents = Class.create(JSClassTrackingObserver.prototype, {
  init: function() {
    this.findElements('js_lead_step_tracking');
  },
  attachTrackingBehavior: function(element, tracking_name) {
    $(element).click(function() {
      setTimeout(function() {
        OmnitureCall.reportLeadStep(tracking_name);
      }, 1000);
    });
  }
});

OmnitureObserver.attachFirstLoginReporting = Class.create({
  init: function() {
    var firstTimeLogin = $.cookie("firstlogin");
    if (firstTimeLogin) {
      $.cookie('firstlogin', null, {path:"/"});
      OmnitureCall.reportLoginSuccess();
    }
  }
});

OmnitureObserver.attachRegisterReporting = Class.create({
  init: function() {
    var registerSuccess = $.cookie("register_success");
    if (registerSuccess) {
      $.cookie('register_success', null, {path:"/"});
      OmnitureCall.reportRegisterSuccess();
    }
  }
});

OmnitureObserver.attachCIRViewMoreLocations = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_omniture_cir_view_more_locations');
  },
  attachBehavior: function(element) {
    $(element).click(function() {
      OmnitureCall.reportCIRViewMoreLocations();
    });
  }
});

OmnitureObserver.attachCIRPrintForm = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_omniture_cir_print');
  },
  attachBehavior: function(element) {
    $(element).click(function() {
      OmnitureCall.reportCIRPrintForm();
    });
  }
});

OmnitureObserver.attachCouponLinkTracking = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_omniture_print_coupon');
  },
  attachBehavior: function(element) {
    $(element).click(function() {
      OmnitureCall.reportCIRCouponPrintForm();
    });
  }
});

OmnitureObserver.attachAllObservers = function() {
  new OmnitureObserver.attachAnswersSearch();
  new OmnitureObserver.attachViewAllAnswers();
  new OmnitureObserver.attachFindAPart();
  new OmnitureObserver.attachFindAManual();
  new OmnitureObserver.attachToolUsage();
  new OmnitureObserver.attachAjaxToolUsage();
  new OmnitureObserver.attachBrowseByService();
  new OmnitureObserver.attachBrowseByRoom();
  new OmnitureObserver.attachBrowse();
  new OmnitureObserver.attachBrowseBySeviceCategory();
  new OmnitureObserver.attachEmail();
  new OmnitureObserver.attachExpertAnswers();
  new OmnitureObserver.attachCancelEvents();
  new OmnitureObserver.attachClickToChatReporting();
  new OmnitureObserver.attachFirstLoginReporting();
  new OmnitureObserver.attachRegisterReporting();
  new OmnitureObserver.attachLeadStepEvents();
  new OmnitureObserver.attachCIRViewMoreLocations();
  new OmnitureObserver.attachCIRPrintForm();
  new OmnitureObserver.attachCouponLinkTracking();
};
var SearsVerticalObserver = {};

SearsVerticalObserver.attachJumpToProduct = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_jump_to_product');
  },
  attachBehavior: function(element) {
    $(element).change(function() {
      location.href=$(element).attr("value");
    });
  }
});

SearsVerticalObserver.attachAllObservers = function() {
  new SearsVerticalObserver.attachJumpToProduct();
};
var LoginObserver = {};

LoginObserver.attachForgotPasswordSubmit = Class.create(FormObserver.attachSubmitForm.prototype, {
   init:function() {
     this.findElements('js_forgot_password_submit');
    },
   submitRequest:function(form, dialog, ajax_submit, errorHolder) {
      var onSuccess = function(){
         $('#forgot_password_form').hide();
		 $('#forgot_password p.js_forgot_password_action').hide();
         $("#display_forgot_email_id").html($("#forgot_email").val());
         $('#change_password_confirmation').show();
         $('#forgot_password_message').hide();
       }
      var onError = function(xmlHttpRequest) {
        errorHolder.clear();
        errorHolder.addHtml($.evalJSON(xmlHttpRequest.responseText).toString());
    }

    $.ajax({
      url:$(form).attr('action'),
      data:$(form).serialize(),
      type:"POST",
      success:onSuccess,
      error:onError,
      dataType :"json"
    });
   }
});

LoginObserver.loginFormVisible = true;
LoginObserver.attachToggleForgotPassword = Class.create(JSClassObserver.prototype, {
  init:function() {
    this.findElements('js_toggle_forgot_password');
  },
  attachBehavior:function(element) {
    $(element).each(function() {
      $(this).click(function(event) {
        $('#forgot_password').toggle();
        $('#login_form').toggle();
        $('.login_header').toggle();
        $('.forgot_password_header').toggle();
        LoginObserver.loginFormVisible = !LoginObserver.loginFormVisible;

        if(LoginObserver.loginFormVisible)
          document.title = "Sign in for Sears Home Services";  
        else
          document.title = "Forgot your password?";

        event.preventDefault();
      });
    });
  }
});

LoginObserver.loginStatusUrl = "/shs/login-status";
LoginObserver.attachLoginStatus = Class.create(JSClassObserver.prototype, {
  init:function() {
    this.findElements('js_replace_login_status');
  },

  attachBehavior:function(element) {
    $.get(LoginObserver.loginStatusUrl, {}, function(html, textStatus) {
      $(element).replaceWith(html);
      var link =  $('#loginLink').attr('href');
      var path =(window.location.pathname === '') ?'products':
    		  window.location.pathname.substr(5,window.location.pathname.length);
      var newLink = path == 'login' ? path + window.location.search : link + path + window.location.search.replace('&','%26');
      $('#loginLink').attr('href', newLink );
    });
  }
});

LoginObserver.attachLoginUrlOnConfirmationPage = Class.create(JSClassObserver.prototype, {
  init:function() {
    this.findElements('js_build_login_url');
  },

  attachBehavior:function(element) {
    var newLink = "/shs/login?sourceUrl=" + "profile";

    $(element).attr('href', newLink);
  }
});

LoginObserver.attachRememberMe = Class.create(FormObserver.attachSubmitForm.prototype, {
  init:function() {
    this.findElements('js_remember_me');
   },
  attachBehavior: function(element) {
    var userIdCookie = $.cookie("userid");
    if(userIdCookie) {
      $("#inp_email").val($.cookie("userid"));
    }
    this.sup(element);
  },
  submitRequest: function(form, dialog, ajax_submit, errorHolder) {
    if($("#inp_remember").is(":checked")) {
      $("#sourceUrl").val($("#sourceUrl").val() + "&" + $("#inp_remember").serialize())
    }
    this.sup(form, dialog, ajax_submit, errorHolder);
  }
});


LoginObserver.attachAllObservers = function() {
  new LoginObserver.attachForgotPasswordSubmit();
  new LoginObserver.attachToggleForgotPassword();
  new LoginObserver.attachLoginStatus();
  new LoginObserver.attachRememberMe();
  new LoginObserver.attachLoginUrlOnConfirmationPage();
};
var LeadObserver = {};

LeadObserver.attachLeadSheetForm = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_user_form');
  },
  attachBehavior: function(element) {
    $.get(LeadObserver.userFormUrl, {}, function(html, textStatus) {
      $(element).replaceWith(html);
      new DialogObserver.attachLoginDialog();
    });
  }
});

LeadObserver.attachLeadAvailability = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_lead_aggregator_check_availability');
  },
  attachBehavior: function(element) {
    $(element).click(function(event) {
      var form = $(element).parents('form');
      var zip_code = $(form).find('#lead_zipcode');
      var warning = $(form).find('.warning');
      
      if($(zip_code).val() == '') {
        var errorHolder = new ErrorHolder(warning);
        new FormValidation(form, errorHolder);     
      } else {
        new LeadAvailability(element);
      }
      event.preventDefault();
    });
  }
});

LeadObserver.attachDisableLeadAggregatorFields = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_lead_aggregator_form_fields');
  },
  attachBehavior: function(element) {
    $("#lead_aggregator_form_fields").addClass('disabled');
    $("#lead_aggregator_form_fields :input").addClass('disabled');
  }
});

LeadObserver.attachLeadAggregatorDisplayCalendar = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_lead_aggregator_display_calendar');
  },
  attachBehavior: function(element) {
      var leadShipAppointment = new LeadShipAppointment();
      leadShipAppointment.initialize();
  }
});

LeadObserver.attachLeadTimeSlotChange = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_lead_time_slot_change');
  },
  attachBehavior: function(element) {
    $(element).change(function() {
      var selectedTimeslot = $("#time_slots option:selected");
      $("#salesRepId").val(selectedTimeslot.attr("salesRepId"));
      $("#overnightAreaId").val(selectedTimeslot.attr("overnightAreaId"));
    });
  }
});

LeadObserver.attachIndicateScheduling = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_indicate_scheduling');
  },
  attachBehavior: function(element) {
    $(element).click(function(event) {
      $("#userSchedulingAnOrder").val("true");
      event.preventDefault();
    });
  }
});

LeadObserver.attachLeadAbandonment = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_lead_abandonment');
  },
  attachBehavior: function(element){
    var self = this;
    $('#lead_sheet_form, #lead_aggregator_form, #lead_aggregator_schedule, #lead_aggregator_call_me, #lead_appointment_submit').submit(function(event){
      $(window).unbind('unload');
    });
    $(window).unload(function(){
      this.opener.location.href = '/shs/lead-abandonment';
    });
  }
});


LeadObserver.attachAllObservers = function() {
  new LeadObserver.attachLeadSheetForm();
  new LeadObserver.attachLeadAvailability();
  new LeadObserver.attachLeadAggregatorDisplayCalendar();
  new LeadObserver.attachLeadTimeSlotChange();
  new LeadObserver.attachIndicateScheduling();
  new LeadObserver.attachLeadAbandonment();
  new LeadObserver.attachDisableLeadAggregatorFields();
}

LeadObserver.userFormUrl = "/shs/lead-sheet-form";
var ProtectionAgreementInvoiceObserver = {};

ProtectionAgreementInvoiceObserver.attachAddressChange = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_address_change');
  },
  attachBehavior: function(element) {
    $(element).change(function(){
      $('#addressChanged').attr("value", true);
    })
  }
});

ProtectionAgreementInvoiceObserver.attachAllObservers = function () {
  new ProtectionAgreementInvoiceObserver.attachAddressChange();
}
var OrderConfirmationObserver = {};

OrderConfirmationObserver.attachLinkForReschedule = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_reschedule_order');
  },
  attachBehavior: function(element) {
    $(element).click(function(event) {
      OmnitureCall.reportRescheduleAttempt();
      $('.reschedule').removeClass('hide').addClass('show');
      var rescheduleDateHandler = new RescheduleDateHandler($(this));
      rescheduleDateHandler.initialize();
      event.preventDefault();
    });
  }
});

OrderConfirmationObserver.attachLinkForCancel = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_cancel_order');
    this.cancelCalled = false;
  },
  attachBehavior: function(element) {
    var self = this;
    $(element).click(function(event) {
      if (!self.cancelCalled) {
        self.cancelCalled = true;
        $("#cancel_dialog").show();
        var cancelHandler = new CancelHandler($(this));
        cancelHandler.initialize(event);
        event.preventDefault();
      }
    });
  }
});


OrderConfirmationObserver.attachPresetRescheduleLinks = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_preset_reschedule');
  },
  attachBehavior: function(element) {
    $("#reschedule_link").trigger('click');
  }
});


OrderConfirmationObserver.attachPresetCancelLinks = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_preset_cancel');
  },
  attachBehavior: function(element) {
    $("#cancel_link").trigger('click');
  }
});

OrderConfirmationObserver.attachShowDialogOnCancel = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_cancel_link');
    this.cancelCalled = false;
  },
  attachBehavior: function(element) {
    var self = this;
    $(element).click(function(event) {
      if (!self.cancelCalled) {
        var cancelDialog = new CancelDialog();
        cancelDialog.show();
      }
      event.preventDefault();
    });
  }
});

OrderConfirmationObserver.closeCancel = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_close_cancel');
  },
  attachBehavior: function(element) {
    $(element).click(function() {
      $("#cancel_dialog").dialog('close');
    });
  }
});

OrderConfirmationObserver.attachSubmitCancelReason = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_cancel_reason');
  },
  attachBehavior: function(element) {
    var self = this;
    $(element).click(function(event) {
      new CancelReason(true).send();
    });
  }
});

OrderConfirmationObserver.attachDeclineCancelReason = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_decline_cancel_reason');
  },
  attachBehavior: function(element) {
    var self = this;
    $(element).click(function(event) {
      new CancelReason(false).send();
    });
  }
});

OrderConfirmationObserver.attachReasonSelectedObserver = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_reason_select');
  },
  attachBehavior: function(element) {
    var self = this;
    $(element).click(function(event) {
      new CancelReason(false).updateSubmitStatus();
    });
  }
});

OrderConfirmationObserver.attachReasonEnteredObserver = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_reason_enter');
  },
  attachBehavior: function(element) {
    var self = this;
    $(element).focus(function(event) {
      new CancelReason(false).updateSubmitStatus();
    });
    $(element).blur(function(event) {
      new CancelReason(false).updateSubmitStatus();
    });
  }
});


OrderConfirmationObserver.attachAllObservers = function() {
  new OrderConfirmationObserver.attachLinkForReschedule();
  new OrderConfirmationObserver.attachLinkForCancel()
  new OrderConfirmationObserver.attachShowDialogOnCancel();
  new OrderConfirmationObserver.closeCancel();
  new OrderConfirmationObserver.attachPresetRescheduleLinks();
  new OrderConfirmationObserver.attachPresetCancelLinks();
  new OrderConfirmationObserver.attachSubmitCancelReason();
  new OrderConfirmationObserver.attachDeclineCancelReason();
  new OrderConfirmationObserver.attachReasonSelectedObserver();
  new OrderConfirmationObserver.attachReasonEnteredObserver();
}
var ElementObserver = {};

ElementObserver.attachPseudoClass = Class.create(JSClassObserver.prototype, {
  init: function() {
    if ($.browser.msie) {
      this.findElements('js_pseudo_class');
    }
  },
  attachBehavior: function(element) {
    var pseudoClass = new PseudoClass();
    pseudoClass.byTarget(element);
  }
});

ElementObserver.attachAllObservers = function() {
  if(isIE()) {
    new ElementObserver.attachPseudoClass();
  }
}
var CarryInObserver = {};

CarryInObserver.attachStoreLocatorLink = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_store_locator');
  },
  attachBehavior: function(element) {
    $(element).click(function(event) {
      var storeIndex = $(element).attr('index');
      var storeDetails = new StoreDetailsDialog(new StoreDetails(storeIndex));
      storeDetails.displayDialog();
      event.preventDefault();
    });
  }
});

CarryInObserver.attachAllStoreLocatorLink = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_all_store_locator');
  },
  attachBehavior: function(element) {
    $(element).click(function(event) {
      $("#store_list").show();
      $("#store_list").dialog({width:1080, modal:true});
      var map = new GoogleMaps($("#store_list_latitude_0").val(), $("#store_list_longitude_0").val(), "store_list_map_canvas");
      map.displayMultipleMarkers(CarryInObserver.storeDetails());
      $("#store_list").dialog('open');
      event.preventDefault();
    });
  }
});

CarryInObserver.attachStoreSelectSaveEvent = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_store_radio');
  },

  attachBehavior: function(element) {
    $("#schedulerInformation_storeNumber").val($("#step2_storeNumber_0").val());
    $("#schedulerInformation_storeID").val($("#step2_storeID_0").val());
    $(element).click(function() {
      var index = $(element).val();
      $("#schedulerInformation_storeNumber").val($("#step2_storeNumber_" + index).val());
      $("#schedulerInformation_storeID").val($("#step2_storeID_" + index).val());
    });
  }
});

CarryInObserver.attachRadioButtonEvent = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_store_list_radio');
  },
  attachBehavior: function(element) {
    $(element).click(function(event) {
      var index = $(element).val();
      $("#schedulerInformation_storeNumber").val($("#storeNumber_" + index).val());
      $("#schedulerInformation_storeID").val($("#storeID_" + index).val());
      var map = new GoogleMaps($("#store_list_latitude_" + index).val(), $("#store_list_longitude_" + index).val(), "store_list_map_canvas");
      map.displayMultipleMarkersWithIndex(CarryInObserver.storeDetails(), index);
      $('#store_list .primary_button').removeClass('disabled');
    });
  }
});

CarryInObserver.addMapOnConfirmationPage = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_store_location_map');
  },
  attachBehavior: function(element) {
    var map = new GoogleMaps($(element).find('.latitude').val(), $(element).find('.longitude').val(), "confirmation_map_canvas");
    var info = $(".confirmation_store_info");
    map.display(info);
  }
});

CarryInObserver.storeDetails = function() {
  var gLatLngList = new Array();
  var infoList = new Array();
  var listSize = $("#store_list_size").val();
  for (i = 0; i < listSize; i++) {
    gLatLngList[i] = new GLatLng($("#store_list_latitude_" + i).val(), $("#store_list_longitude_" + i).val());
    infoList[i] = $("#store_info_" + i);
  }
  return{
    'location': gLatLngList,
    'info' : infoList
  };
}

CarryInObserver.attachSaveStoreLocation = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_save_store_location');
  },
  attachBehavior: function(element) {
    $(element).click(function(event) {
      $("#schedulerInformation_storeNumber").val($('#store_details #store_info_container [name=store_number]').val());
      $("#schedulerInformation_storeID").val($('#store_details #store_info_container [name=store_id]').val());
      var storeListDialogCloseButton = $('#store_list').parents('.ui-dialog').find('.ui-dialog-titlebar-close');
      storeListDialogCloseButton.trigger('click');
      var dialogCloseButton = $(this).parents('.ui-dialog').find('.ui-dialog-titlebar-close');
      $(dialogCloseButton).trigger('click');

      CarryInObserver.unSelectSchedulerStep2Stores();

      if(!$(this).hasClass('disabled')) {
        SchedulerObserver.scheduler.next('#go_to_step_three');
      }
      OmnitureCall.reportCIRSaveLocation($("#schedulerInformation_storeNumber").val());

      event.preventDefault();
    });
  }
});

CarryInObserver.attachSelectivePrint = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_print_selected');
  },
  attachBehavior: function(element) {
    $(element).click(function(event) {
      $('.js_print_div').jqprint();
      event.preventDefault();
    });
  }
});

CarryInObserver.attachSaveStoreLocationList = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_save_store_location_list');
  },
  attachBehavior: function(element) {
    $(element).click(function(event) {
      var selectedStoreIndex = $('#store_list [name=store_radio]:checked').val();
      if (selectedStoreIndex == null) {
        return;
      }
      $("#schedulerInformation_storeNumber").val($('#store_list #store_info_' + selectedStoreIndex + ' [name=store_number]').val());
      $("#schedulerInformation_storeID").val($('#store_list #store_info_' + selectedStoreIndex + ' [name=store_id]').val());

      var dialogCloseButton = $(this).parents('.ui-dialog').find('.ui-dialog-titlebar-close');
      $(dialogCloseButton).trigger('click');

      CarryInObserver.unSelectSchedulerStep2Stores();
      
      if(!$(this).hasClass('disabled')) {
        SchedulerObserver.scheduler.next('#go_to_step_three');
      }
      OmnitureCall.reportCIRSaveLocation($("#schedulerInformation_storeNumber").val());
      event.preventDefault();
    });
  }
});


CarryInObserver.unSelectSchedulerStep2Stores = function() {
  $('.carry_in_repair_select_store .store_list [name=store_radio]').removeAttr('checked');
}


CarryInObserver.attachSelectOtherNOP = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_select_other_nop');
  },
  attachBehavior: function(element) {
    $(element).focus(function(event) {
      var checkBoxElement = $(element).attr('id')+'CheckBox';
      $("#"+checkBoxElement).attr('checked',true);
      event.preventDefault();
    });
  }
});


CarryInObserver.attachAllObservers = function() {
  new CarryInObserver.attachStoreLocatorLink();
  new CarryInObserver.attachAllStoreLocatorLink();
  new CarryInObserver.attachRadioButtonEvent();
  new CarryInObserver.addMapOnConfirmationPage();
  new CarryInObserver.attachSaveStoreLocation();
  new CarryInObserver.attachStoreSelectSaveEvent();
  new CarryInObserver.attachSaveStoreLocationList();
  new CarryInObserver.attachSelectivePrint();
  new CarryInObserver.attachSelectOtherNOP();
};
var BlueCrewAnswersUrlBuilder = Class.create({
  build: function(term) {
    return "/shs/blue-crew-answers?question=" + encodeURIComponent(term);
  }
});
$(document).ready(function() {
  var buttonId = '#blue_crew_show_questions';
  var inputId = '#blue_crew_question_term';
  var resultsId = '#blue_crew_questions';
  var urlBuilder = new BlueCrewAnswersUrlBuilder();
  bindAjaxActionCall(buttonId, urlBuilder, inputId, resultsId, function(count) {
   OmnitureCall.reportBlueCrewNumberOfSearchResults(count);
  });
});
var kkeys = [], konami = "38,38,40,40,37,39,37,39,66,65";
$(document).keydown(function(e) {
  kkeys.push( e.keyCode );
  if ( kkeys.toString().indexOf( konami ) >= 0 ){
    $(document).unbind('keydown',arguments.callee);
    
    var egg = document.createElement('div');

    $(egg).html('<embed src="http://www.youtube.com/v/wJh7EN8vB48&hl=en&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed>');
    $(egg).dialog({
	    bgiframe:true,
	    resizable:false,
      modal:true, 
      close:true,
      width:455,
      minWidth:455,
      height:344
    });   
  }
});
