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

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

// ArrayIndesOf
// 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 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 = {

  // Page Reporting

  reportSearchPage: function(searchTerm, searchServiceCount, searchAnswerCount) {
    OmnitureReport.pageInformation = new OmniturePageInformation('Search', 'Search', 'Department');

    new OmnitureReport({
      pageName:"Search Results > Search Results",
      channel:"Search",
      prop9:searchTerm,
      prop10:searchServiceCount,
      prop11:searchAnswerCount
    });
  },

  reportHomePage: function() {
    OmnitureReport.pageInformation = new OmniturePageInformation('Home', 'Home', 'Department');

    new OmnitureReport({
      pageName:"Home",
      channel:"Home",
      prop1: "Home",
      prop2:"Home"
    });
  },

  reportAnswersPage: function() {
    new OmnitureReport({
      pageName:"Search Results > Expert answers",
      channel:"Answers search results"
    });
  },

  reportMarketingPage: function(promoHeading) {
    new OmnitureReport({
      pageName: promoHeading +  " Marketing Landing Page",
      channel: promoHeading +  " Marketing Landing Page"
    });
  },

  reportOrderCancelConfirmationPage: function(serviceName) {
    new OmnitureReport({
      pageName:serviceName + " order cancellation",
      channel:serviceName + " order cancellation"
    });
  },

  reportOrderSearchPage: function(serviceName) {
    new OmnitureReport({
      pageName:serviceName + " order search",
      channel:serviceName + " order search"
    });
  },

  reportOrderRescheduleConfirmationPage: function(serviceName) {
    new OmnitureReport({
      pageName:serviceName + " order reschedule",
      channel:serviceName + " order reschedule"
    });
  },

  reportOrderStatusPage: function(serviceName) {
    new OmnitureReport({
      pageName:serviceName + " order status",
      channel:serviceName + " order status"
    });
  },

  reportShipOrderConfirmationPage: function(serviceName) {
    new OmnitureReport({
      pageName:serviceName + " order confirmation",
      channel:serviceName + " order confirmation"
    });
  },

  reportProductPage: function(productName) {
    new OmnitureReport({
      pageName:productName + " Detail",
      channel:productName + " Detail Page"
    });
  },

  // Scheduler Reporting

  reportServiceFound: function() {
    new OmnitureReport({
      prop3: OmnitureReport.pageInformation.pageName,
      events:"event4"
    }, true);
  },

  reportServiceNotFound: function() {
    new OmnitureReport({
      prop3: OmnitureReport.pageInformation.pageName,
      events:"event5"
    }, true);
  },

  reportServiceSelected: function(service) {
    new OmnitureReport({
      prop3: OmnitureReport.pageInformation.pageName,
      eVar3:service
    }, true);
  },

  reportProductSelected: function(product) {
    if (product != '') {
      new OmnitureReport({
        prop3: OmnitureReport.pageInformation.pageName,
        eVar3:product
      }, true);
    }
  },

  reportSchedulerStart: function(zipCode) {
    new OmnitureReport({
      events:"event1",
      eVar5:zipCode,
      prop3: OmnitureReport.pageInformation.pageName
    }, true);
  },

  reportSchedulerOpen: function() {

    new OmnitureReport({
      events:"scOpen",
      prop3: OmnitureReport.pageInformation.pageName
    }, true);
  },

  reportSchedulerComplete: function() {
    new OmnitureReport({
      events:"event2"
    });
  },

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

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

  reportServiceLandingPage: function(category) {
    OmnitureReport.pageInformation = new OmniturePageInformation(category, category, 'Category');

    new OmnitureReport({
      pageName: category,
      channel: category,
      prop1:category,
      prop2:"Department"
    });
  },

  reportProductDetailPage: function(category, productname) {
    OmnitureReport.pageInformation = new OmniturePageInformation(category + " :" + productname, productname,'Product Detail');

    new OmnitureReport({
      pageName: category + " :" + productname + " :PDP",
      channel: category,
      prop1:productname,
      prop2:"Product Detail"
    });
  },

  reportPageNotFound: function(url) {
    new OmnitureReport({
      pageName: "404:" + url,
      pageType: "errorpage"
    });
  },

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

  reportSchedulerMacroView: function(step, zip, category, productname) {
    zip = zip || "BLANK";
    category = category || "BLANK";
    productname = productname || "BLANK";
    new OmnitureReport({
      prop3: OmnitureReport.pageInformation.pageName,
      prop4: step,
      prop6: zip,
      prop7: [category,productname].join(": "),
      prop8: [zip, category, productname].join(": ")
    }, true);
  },

  reportSchedulerMicroView: function(field, zip, category, productname) {
    zip = zip || "BLANK";
    category = category || "BLANK";
    productname = productname || "BLANK";
    new OmnitureReport({
      prop3: OmnitureReport.pageInformation.pageName,
      prop5: field,
      prop6: zip,
      prop7: [category,productname].join(": "),
      prop8: [zip, category, productname].join(": ")
    }, true);
  },

  reportAnswersSearch: function(searchTerm) {
    new OmnitureReport({
      prop13:searchTerm,
      prop3:OmnitureReport.pageInformation.pageName
    }, true);
  },

  reportNoSearchResults: function() {
    new OmnitureReport({
      prop14:"Zero",
      prop3:OmnitureReport.pageInformation.pageName
    }, true);
  },

  reportViewAllAnswers:function(searchTerm) {
    new OmnitureReport({
      prop16:searchTerm,
      prop3:OmnitureReport.pageInformation.pageName
    }, true);
  },

  reportPartsDirect:function() {
    new OmnitureReport({
      prop17:"Need a Part",
      prop3:OmnitureReport.pageInformation.pageName
    }, true);
  },

  reportManageMyHome:function() {
    new OmnitureReport({
      prop16:"Find a Manual",
      prop3:OmnitureReport.pageInformation.pageName
    }, true);
  },

  reportAjaxToolUsage:function(tool) {
    new OmnitureReport({
      prop3: OmnitureReport.pageInformation.pageName,
      prop12:tool
    }, true);
  },

  reportToolUsage:function(tool) {
    new OmnitureReport({
      pageName: OmnitureReport.pageInformation.pageName,
      prop12:tool
    });
  },

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

  reportSearchPages:function() {
    new OmnitureReport({
      pageName:OmnitureReport.pageInformation.getPageNameForSearch(),
      channel: "Search",
      prop1:OmnitureReport.pageInformation.getCategoryForSearchPages(),
      prop2: OmnitureReport.pageInformation.pageType
    });
  },

  reportAnswerShowMore:function(question) {
    new OmnitureReport({
      pageName:OmnitureReport.pageInformation.getPageNameForSearch(),
      prop15:question
    });
  }
};
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
};
var SelectDate = Class.create({
  init: function(dateSelectionCallback, container_id) {
    this.dateSelectionCallback = dateSelectionCallback;
    var self = this;
    $("#previousDate").click(function() {
      self.selectPreviousDate();
    });

    $("#nextDate").click(function() {
      self.selectNextDate();
    });

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

  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);
    var product_name = SchedulerService.productNameForService($("#service :selected").val());
    OmnitureCall.reportSchedulerMicroView("date", $("#zip_code").val(), $("#service").val(), product_name);
    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:'+1d',
      maxDate:'+60d',
      beforeShowDay: function(date) {
        return [self.isAvailable(date),'  '];
      },
      onSelect: function(date) {
        self.setSelectedDate(date);
      }
    });
    $(this.scheduler_calender_container).datepicker('option', 'defaultDate', null);
  },

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

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

});
var CleanType = Class.create({
  init: function(zipcode) {
    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();
  },
  
  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);
      //self.insertAddtionalServiceSection($('#additional_cleaning_services'), 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();
    });
  },
  
  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';
    $('#time_slots').html('');
    jQuery.each(['AM','PM'], function(index, timeslot) {
      var timeSlot = new TimeSlot(name, index, timeslot, function(input_value) {
        $('#go_to_step_three').removeClass('disabled');
        $('#go_to_step_three').removeClass('blocked');
        $('#schedule_service').addClass('blocked');
        self.dateContainer.setTimePreference(input_value);
      });

      //$(timeSlot.radioGroup).

      $(timeSlot.radioGroup).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) {
        subtotal = selectedPackage.subTotal();
      }
      totalCost = totalCost + subtotal;
    });
    $("#totalPrice").show();
    $("#totalPrice").html("Total cost <p class='price'><em>$</em>" + this.truncate(totalCost) + "</p>");
  },

  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"> ' +
                      '            <option value="">Select a product</option> ' +
                      '          </select> ' +
                      '      </div> ' +
                      '      <a href="javascript:;" id="${removeServiceId}" class="remove_service">Remove this service</a> ' +
                      '    </div> ' +
                      '    <div class="section"> ' +
                      '      <div class="package fieldset_wrap"> ' +
                      '        <label for="${package}">Package</label> ' +
                      '          <select id="${package}" class="js_required">' +
                      '            <option value="">Select a package</option> ' +
                      '          </select>' +
                      '      </div> ' +
                      '      <div class="quantity fieldset_wrap"> ' +
                      '        <label for="${quantity}">Quantity</label> ' +
                      '        <select id="${quantity}">' +
                      '          <option selected="true" value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option>' +
                      '        </select>' +
                      '      </div> ' +
                      '      <div class="subtotal fieldset_wrap"> ' +
                      '        <span id="${subtotal}"><em>$</em>0</span> ' +
                      '        <label>SubTotal</label> ' +
                      '      </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 successFunction = function(data) {
      self.successfullOrder(data);
    };

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

    var schedulerRequest = new SchedulerRequest();
    schedulerRequest.httpPost(this.createCleanOrderUrl, this.createOrderParams(), successFunction, errorFunction, $('#schedule_service'));

    return false;
  },

  successfullOrder: function(data) {
    $("#successfullOrderNumberFormField").val(data.orderId);
    $("#successfullPhoneNumberFormField").val(data.phoneNumber);
    $("#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(),
      '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();
    $("#initailHelp").show();
    $("#clean_services").hide();
   // alert($("#schedule_service").bind());
    $("#schedule_service").unbind("click.clean");
    this.showClickToCallInStepTwo();
    this.hideCleanQuestionInStepTwo();
    this.products[0].resetProductList();
    this.products[0].resetPackageList();
    new SchedulerRequest().cancelPriorRequest();
    this.destroyExistingCalendar();
  },

  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.selectDate.fillDates(dates);
      self.setDateContainer(self.selectDate);
    };

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

    var schedulerRequest = new SchedulerRequest();
    schedulerRequest.httpGetJSON(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;
    parameters[this.descriptionId()] = this.selectedPackage.description;
    parameters[this.expirationDateId()] = this.selectedPackage.expirationDate;
    parameters[this.extendedDescriptionId()] = this.selectedPackage.extendedDescription;
    parameters[this.salePriceId()] = this.selectedPackage.salePrice;
    parameters[this.priceId()] = this.selectedPackage.price;
    parameters[this.serviceCodeId()] = this.selectedPackage.serviceCode;
    return parameters;
  },

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

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

  descriptionId:function(){
    return "description" + this.index;
  },

   extendedDescriptionId: function() {
     return "extendedDescription" + this.index;
   },

   priceId:function() {
     return "price" + this.index;
   },

   salePriceId:function(){
     return "salePrice" + this.index;
   },

   expirationDateId:function() {
      return "expirationDate" + this.index;
   },

   serviceCodeId:function() {
    return "serviceCode" + 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() != '') {
      OmnitureCall.reportProductSelected(product.val());
      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", "", "Select a 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");
  },

  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"));
      OmnitureCall.reportServiceFound();
      
    } 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) {
         OmnitureCall.reportServiceNotFound();
         SchedulerObserver.scheduler.next("#error_message");
         new SchedulerServiceError($.evalJSON(cleanError)).display();
       };

    var self = this;
    if (this.isValid()) {
      var schedulerRequest = new SchedulerRequest();
      schedulerRequest.httpGetJSON(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;

    $('#contact_me_by_phone').change(function() {
      $('input[name=shipTimePreference]').parents('.radio_group').removeClass('selected');
    });

    $('#contact_me_by_phone').click(function(event) {
      $('#go_to_step_three').removeClass('disabled');
      $('#go_to_step_three').removeClass('blocked');
    });
    var self = this;
    this.selectDate = new SelectDate(function(selectedDate) {
      $('#go_to_step_three').addClass('disabled');
      $('#go_to_step_three').addClass('blocked');
      $('#schedule_service').removeClass('blocked');
      self.updateTimeSlots(selectedDate);
    });
  },

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

  updateTimeSlots: function(selectedDate) {
    var self = this;
    SchedulerObserver.scheduler.resetHeight($('#step_two'), 45);
    $('#time_slots').html('');
    $("#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(isIE6()) {
      if(timeSlots.length > 10) {
        SchedulerObserver.scheduler.growHeight(65, $('#step_two')); 
      } else if(timeSlots.length > 5) {
        SchedulerObserver.scheduler.growHeight(40, $('#step_two')); 
      } 
    } 
  },

  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) {
        $('#go_to_step_three').removeClass('disabled');
        $('#go_to_step_three').removeClass('blocked');
        $('#schedule_service').addClass('blocked');
        self.selectedTime = input_value;
      });


      if (index > self.minTriggerResize) {
        SchedulerObserver.scheduler.growHeight(self.timeSlotHeight, $('#step_two'));
      }

      $(timeSlot.radioGroup).appendTo($('#time_slots'));

      $(timeSlot.radioGroup).find('input').attr("salesRepId", timeslot.salesRepId)
      $(timeSlot.radioGroup).find('input').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);
    };

    var schedulerRequest = new SchedulerRequest();
    schedulerRequest.httpGetJSON(this.availableDatesUrl, this.params, successFunction, errorFunction, $(this.selectDate.scheduler_calender_container));
  },

  createParams: function() {
    var appointmentParams = {};
    var selectedTimeslot = $("input:radio[name=shipTimePreference]:checked");
    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 = selectedTimeslot.val();
    return appointmentParams;
  },

  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.email = $("#email").val();
    customerParams.address = $("#address").val();
    customerParams.city = $("#city").val();
    customerParams.state = $("#state").val();
    customerParams.notes = $("#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, headerDescription)
    html += this.populate(data, key, description);
    this.element.html(html);
    return this;
  },

  forceChangeEventForSingleOption: function() {
    if (this.element.children("option").size() == 1) {
      this.element.trigger('change');
    }
  },

  defaultOption: function(data, headerKey, headerDescription) {
    if (data.length != 1) {
      return this.buildOption(headerKey, headerDescription);
    }
    return "";
  },
  
  populate: function(data, key, description) {
    var self = this;
    var options = "";
    jQuery.each(data, function() {
      options += self.buildOption(this[key], this[description]);
    });
    return options;
  },

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

  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)) {

        OmnitureCall.reportServiceSelected($(this).val());

        self.addServiceClassNameToScheduler($(this).val());
        self.serviceDetails($(this).val());
      }
    });
  },

  observeZipCode: function() {
    var self = this;
    this.zipcode.change(function() {
      self.zipcode = $(this);

      OmnitureCall.reportSchedulerStart($(this).val());

      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) {
      this.serviceType.reset();
      this.serviceType = null;
      new Select($("#product")).removeAllElements("", "Select a 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();
      
    }
  },


  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.streetLine1);
    $("#address_line_1").val(customerInformation.streetLine1);
    $("#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);
  },

  populate: function() {
    var self = this;
    $.get(this.customerInformationUrl, {}, function(customerInformation) {
      self.populateCustomerInformation(customerInformation);
    }, "json");
  },
  customerInformationUrl: '/shs/customerInformationJSON'
});
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"]) {
        OmnitureCall.reportServiceNotFound();
        new SchedulerServiceError(data).display();
      } else {
        self.jsonForProducts(data);
        self.schedulerPrepopulator.selectElementAndTriggerChangeForService(self.products, $("#schedulerInformation_product"));
        OmnitureCall.reportServiceFound();
      }
    };
    var errorFunction = function(error) {
      OmnitureCall.reportServiceNotFound();
      SchedulerObserver.scheduler.next("#error_message");
      new SchedulerServiceError($.evalJSON(error)).display();
    };
    var schedulerRequest = new SchedulerRequest();
    schedulerRequest.httpGetJSON(this.serviceLocation, 
                                 this.createShipParams(), 
                                 successFunction, 
                                 errorFunction, $('#product'));
    this.showAddress();
  },

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

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

  showAddress : function() {
    this.address.show();
  },

  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");
    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) {
        var schedulerRequest = new SchedulerRequest();
        schedulerRequest.httpGetJSON(this.servicesForCleanURL, this.createPackageParams(), function(data) {
          self.populateProducts($(self.packageElementId), data);
        }, errorMessageHandler, $(this.packageElementId));
      }
    } else {
      this.handleData([]);
    }
  },

  servicesForCleanURL: '/shs/cleanPackagesJSON',
  cleanName : "cleaning"
});
var RepairType = Class.create({
  init: function(zipcode) {
    $("#scheduler .click_to_chat_optional").show();
    this.zipcode = zipcode;
    this.selectRepairProduct = new RepairSelectProduct("repair", this.zipcode);
    this.isRequestSubmitted = false;
    
    var self = this;
    $("#repair_contact_info").show();
    $("#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);
  },

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

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

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

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

  createOrder: function() {
    var self = this;
    var successResponseHandler = function(data) {
      self.processOrderResponse(data);
    };

    var errorFunction = function(repairError) {
      new RepairSchedulerServiceError($.evalJSON(repairError)).display();
    };
    var schedulerRequest = new SchedulerRequest();
    schedulerRequest.httpPost(this.createRepairOrderUrl, this.createOrderParams(), successResponseHandler, errorFunction, $('#schedule_service'));
    return false;
  },

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

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

  createOrderParams: function() {
    return jQuery.extend({'zipCode': this.zipcode.val(),
      'problemDescription': $("#problem_description").val(),
      'searsWarranty': $("#warranty").val(),
      '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(),
      'brand': $("#brand").val(),
      'notes' : $("#notes").val()
    }, this.selectRepairProduct.getOrderParams());
  },

  reset: function() {
    $("#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();
    $("#initailHelp").show();
    $("#repair_contact_info").hide();
    $("#schedule_service").unbind("click.repair");
    $("#product").unbind("change.repair")
    this.hideRepairQuestionInStepTwo();
    new SchedulerRequest().cancelPriorRequest();
    this.destroyExistingCalendar();
  },

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

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

});
var SHIPType = Class.create({
  init: function(zipcode) {
    this.params = {};
    this.zipcode = zipcode;
    this.isRequestSubmitted = false;
    this.shipAvailability = new ShipAvailability(this.zipcode, $("#product"), $("#ship_service_address"));
    $("#product").parent("div.product").show();
    
    this.showShipQuestionInStepTwo();
    this.dynamicDescription="What would you like to do?";
    $("#dynamicDescription").html(this.dynamicDescription);
  },

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

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

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

  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.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) {
      // console.log("Order placed successfully. Server said: " + msg);
      instance.reset();
      SchedulerObserver.scheduler.resetToStart();
      self.successfullOrder(msg);
    };

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

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

  },

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

  reset: function() {
    $("#shipTimePreference").hide();
    $("#ship_service_address").hide();
    this.hideShipQuestionInStepTwo();
    new SchedulerRequest().cancelPriorRequest();
    $("#schedule_service").unbind("click.ship");
    $("#go_to_step_two").unbind("click.ship");
    $("#go_to_step_three").unbind("click.ship");
    this.destroyExistingCalendar();
  },

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

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

});
var RepairSelectProduct = Class.create({
  init: function(selected_service, zipcode) {
    this.selected_service = selected_service;
    this.zipcode = zipcode;
    this.product = $("#product");
    this.productGroup = $("#productGroup");
    var self = this;

    this.product.unbind("change.repair").bind("change.repair", function() {
      new SchedulerRequest().cancelPriorRequest();
      self.processProductChange($(this));
    });

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

  },

  processProductGroupChange: function() {
    $('#product').parents('fieldset').show();
    $("#product").parent("div.product").show();
    
    if (!($('#step_one').hasClass('additional_height'))) {
      SchedulerObserver.scheduler.growHeight(50, $('#step_one'));
    }
    
    this.updateProducts();
  },

  processProductChange: function(product) {
    OmnitureCall.reportProductSelected(product.val());
    this.displayProductTypeInformation(product);
  },

  displayProductTypeInformation: function(product) {
    if (this.getProductData(product).carryIn) {
      this.showCarryInInformation();

    } else {
      this.selectedPackage = new RepairSelectPackage(this.zipcode, product);
      this.selectedPackage.update();
      this.showSiteInformation();
    }
  },

  showCarryInInformation: function() {
    $("#problem_description").parent("div.problem_description").hide();
    $("#brand").parent("div.brand").hide();
    $("#warranty").parent("div.warranty").hide();	  
    $("#repair_site_services").hide();
    $("#initailHelp").hide();
    this.showStoreLocator();
    new LinkObserver.attachExternalLink();
    
    $("#go_to_step_two").hide();
  },

  showStoreLocator: function() {
    SchedulerObserver.scheduler.animateToShortWidth();
    $("#dynamicDescription").hide();
    var locators = ["store_locator_link", "store_locator"];
    var self = this;
    jQuery.each(locators, function() {
      $("#" + this).show().attr("href", "/shs/displayStoreLocations?zipCode=" + self.zipcode.val());
    });
    $("#store_locator_description").show();
  },

  showSiteInformation: function() {
    $("#problem_description").parent("div.problem_description").show();
    $("#brand").parent("div.brand").show();
    $("#warranty").parent("div.warranty").show();
    $("#repair_site_services").show();
    $("#go_to_step_two").show();
    $("#initailHelp").show();
    //console.log("hiding store locator link");
    $("#store_locator").hide();
    $("#store_locator_description").hide();
  },

  showServiceDescription: function(description) {
	$("#store_locator_description").hide();
	$("#store_locator").addClass("hide");
    $("#dynamicDescription").html(description).show();
  },

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

  getOrderParams:function() {
    return jQuery.extend({'productId': this.product.val()}, this.selectedPackage.getOrderParams());
  },

  populateProducts: function(context, select_element, data) {
    if (data.length != 0) {
      OmnitureCall.reportServiceFound();
    }
    context.showServiceDescription(data.serviceDescription);
    context.data = data;
    var selectProductDropdown = new Select(select_element).populateWith(data.products, "id", "description", "", "Select a product");
    context.schedulerPrepopulator.selectElementAndTriggerChangeForService(select_element, $("#schedulerInformation_product"));
    selectProductDropdown.forceChangeEventForSingleOption();
  },

  populateProductGroups: function(context, select_element, data) {
    context.data = data;
    new Select(select_element).populateWith(data, "id", "description", "", "Select a product group").forceChangeEventForSingleOption();
     if(document.all)
       $("#productGroup option").each(function(){
            if($(this).text().length > 20)
              $(this).text($(this).text().substr(0, 20) + "...");
          });
      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() {
    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) {
        OmnitureCall.reportServiceNotFound();
        new RepairSchedulerServiceError($.evalJSON(errorMessage)).display();
      }
      var schedulerRequest = new SchedulerRequest();
      schedulerRequest.httpGetJSON(selectUrl, selectparams, successFunction, errorFunction, $('#product'));

    } else {
      populate(self, elementToPopulate, []);
    }
  },

  productGroupsForRepairURL: '/shs/repairProductGroupJSON',
  productForRepairURL: '/shs/repairServicesAvailabilityJSON'
});
var RepairSelectPackage = Class.create({
  init: function(zipcode, selected_product) {
    this.zipcode = zipcode;
    this.product = selected_product;
    var self = this;
    this.selectDate = new SelectDate(function(selectedDate) {
      $('#go_to_step_three').addClass('disabled');
      $('#go_to_step_three').addClass('blocked');
      $('#schedule_service').removeClass('blocked');
      self.updateTimeSlots(selectedDate);
    });
  },

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

  populateProblemDescription: function(select_element, problemDescriptionData) {
    new Select(select_element).populateWith(problemDescriptionData, "id", "description", "", "Select a problem");
  },

  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();
    $("#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();
  },

  observe: function() {
    var self = this;
    $("#warranty").unbind("change.repair").bind("change.repair", function() {
      if ($(this).find(':selected').attr("phonesupport") == "true") {
        self.displayPhoneInformation();
      } else {
        self.hidePhoneInformation();
      }
    });
  },

  update: function() {
    this.updateProductData();
    this.observe();
    this.getDates();
  },

  updateProductData: function() {
    var self = this;
    var successFunction = function(data) {
      self.populateProblemDescription($("#problem_description"), data["productProblems"]);
      self.populateProducts($("#brand"), data["brands"]);
      self.updateDescription(data["description"]);
      self.updateCTCTemplateId(data["ctcTemplateId"]);
      self.updateCallUsNumber(data["callUsNumber"]);
      self.attachRepairInfoValidation();
    };
    var errorMessageHandler = function(repairError) {
      new RepairSchedulerServiceError($.evalJSON(repairError)).display();
    };
    var schedulerRequest = new SchedulerRequest();
    schedulerRequest.httpGetJSON(this.productDetailsUrl,
        this.createPackageParams(),
        successFunction,
        errorMessageHandler,
        $('#problem_description'));
  },

  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();
  },

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

  updateCTCTemplateId: function(ctcTemplateId) {
    $("#ctc_template").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) {
    $('.radio_group').remove();
    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,
      'capacityArea'        : this.datesData.capacityArea,
      'capacityNeeded'      : this.datesData.capacityNeeded,
      'serviceUnitNum'      : this.datesData.serviceUnitNum,
      'workAreaCode'        : this.datesData.workAreaCode,
      'minimumServiceCharge': this.datesData.minimumServiceCharge};
  },

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

    jQuery.each(timeSlots, function(index, timeslot) {
      var timeSlot = new TimeSlot(name, index, timeslot, function(input_value) {
        $('#go_to_step_three').removeClass('disabled');
        $('#go_to_step_three').removeClass('blocked');
        $('#schedule_service').addClass('blocked');
        self.selectedTime = input_value;
      });
      $(timeSlot.radioGroup).appendTo($('#time_slots'));
    });
  },

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

    var successFunction = function(datesData) {
      if (datesData["serviceDates"] && datesData["serviceDates"].length == 0) {
        message = {
          message: "It doesn't look like we have service in your area, but we may still be able to help.",
          title: "No dates available",
          serviceType: "Repair",
          phoneNumber: "1-800-376-6956",
          clickToCallNumber: "493829"
        };
        new RepairSchedulerServiceError(message).display();
      } else {
        self.datesData = datesData;
        self.updateMinimumServiceCharge(datesData);
        self.populateWithDates(datesData["serviceDates"]);
      }
    };

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

    var schedulerRequest = new SchedulerRequest();
    schedulerRequest.httpGetJSON(this.getDatesUrl(), this.createPackageParams(), successFunction, errorFunction, $(this.selectDate.scheduler_calender_container));
  },

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

  updateMinimumServiceCharge : function(datesData) {
    var minimumChargeHtml = '<div id="service_date_desc">' +
                            '<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>' + datesData.minimumServiceCharge + '</p>' +
                            //'</div>' +
                            '</div>';
    $("#service_date_desc").html(minimumChargeHtml);
  },

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

  datesForRepairURL: '/shs/repairDateAvailabilityJSON',
  productDetailsUrl: '/shs/productDetailsJSON'
});
var RepairRescheduleDate = Class.create({
  init: function(element) {
    this.element = element;
    this.isRequestSubmitted = false;
    this.bindEvents()
  },

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

  bindEvents: function() {
    var self = this;
    $("#reschedule_service").unbind("click.repair").bind("click.repair", function(event) {
      if ($(this).hasClass("disabled")) {
        // alert("Select date and timeslot");
      } else {
        if (!self.isRequestSubmitted) {
          self.isRequestSubmitted = true;
          self.rescheduleOrder();
        }
      }
      event.preventDefault();
    });
  },

  updateTimeSlots: function(selectedDate) {
    var self = this;
    $("#reschedule_timeslots").html("");
    if (this.datesData["serviceDates"] && this.datesData["serviceDates"].length == 0) {
      message = {
        message: "It doesn't look like we have service in your area, but we may still be able to help.",
        title: "No dates available",
        serviceType: "Repair",
        phoneNumber: "1-800-376-6956",
        clickToCallNumber: "493829"
      };
      new SchedulerServiceError(message).display();
    } else {
      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.radioGroup).appendTo($('#reschedule_timeslots'));
    });
  },


  getDates: function() {
    var self = this;
    $("#reschedule_repair_time_preference").show();
    var successFunction = function(datesData) {
      if (!datesData["serviceDates"]) {
        //console.log("No dates found.");
      }
      self.datesData = datesData;
      self.selectDate.fillDates(datesData["serviceDates"]);
    }
    var errorFunction = function() {}
    var schedulerRequest = new SchedulerRequest();
    schedulerRequest.httpGetJSON(this.getDatesUrl(), this.createPackageParams(), successFunction, errorFunction, $(this.selectDate.scheduler_calender_container));
  },

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


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


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

  datesForRepairRescheduleURL: '/shs/repairRescheduleDateAvailabilityJSON',
  rescheduleRepairOrderUrl: '/shs/order/repair/reschedule'


});
var CleanRescheduleDate = Class.create({
  init: function(element) {
    this.element = element;
    this.isRequestSubmitted = false;
    this.bindEvents();
  },

  initialize: function() {
    this.selectDate = new SelectDate(function(selectedDate) {
      var self = this;
      $("#reschedule_timeslots").html("");
      var name = 'reschedule_clean_time_preference';
      $('#reschedule_timeslots').html('');
      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.radioGroup).appendTo($('#reschedule_timeslots'));
      })
      $("#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() {}
    var schedulerRequest = new SchedulerRequest();
    schedulerRequest.httpGetJSON(this.datesForCleanRescheduleURL, this.selectParams(), successFunction, errorFunction, $(this.selectDate.scheduler_calender_container));
  },

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

  bindEvents: function() {
    var self = this;
    $("#reschedule_service").unbind("click.clean").bind("click.clean", function(event) {
      if ($(this).hasClass("disabled")) {
      } else {
        if (!self.isRequestSubmitted) {
          self.isRequestSubmitted = true;
          self.rescheduleOrder();
        }
      }
      event.preventDefault();
    });
  },

  rescheduleOrder: function() {
    $("#orderIdFormField").val($("#orderId").val());
    $("#rescheduleDateFormField").val(this.selectDate.getSelectedDate());
    $("#selectedTimeFormField").val(this.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;
  },

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

    if (null != dateHandler) {
      dateHandler.initialize();
    } else {
      // console.log("unknown service type " + serviceType)
      // Figure out an action
    }

  },

  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);
    }
    return dateHandler;
  }
});
var RepairCancel = 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.cancelRepairOrderUrl);
    $("#accessOrderForm").submit();
    event.preventDefault();
  },

  cancelRepairOrderUrl:'/shs/order/repair/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 InstallationType = Class.create({
  init: function(zipcode, product, installBack) {
    this.zipcode = zipcode;
    this.productCategoriesElement = product;
    this.installBack = installBack;
    this.minTriggerResize = 3;
    this.addOnHeight = 100;
    this.heightIncresdForProductOption = false;
    $('#service_date_desc').hide();
    $('#service_install_question').show();
    $('#scheduler .radio_group_container').hide();
    this.dynamicDescription = "Which product do you need installed?";
    $("#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.selectedAddOns = new Array();
    this.schedulerPrepopulator = new SchedulerPrepopulator();
  },

  processProductCategoryChange: function() {
    $('#product').parents('fieldset').show();
    $("#product").parent("div.product").show();

    if (!($('#step_one').hasClass('additional_height'))) {
      SchedulerObserver.scheduler.growHeight(50, $('#step_one'));
    }

    this.populateProducts();

  },

  populateProducts: function() {
    var self = this;
    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();
      };

      var schedulerRequest = new SchedulerRequest();
      schedulerRequest.httpGetJSON(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;
    jQuery.each(this.selectedAddOns, function(index, optionId) {
      var addOnPrice = self.getPriceForAdOn(optionId);
      totalCost = totalCost + addOnPrice;
    });

    totalCost = totalCost + this.getPriceForOption($('#install_product_options').val());

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

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

  getPriceForOption: function(optionId) {
    var removeMatchingElement = false;
    var addOn = jQuery.grep(this.productOptions, function(addOn) {
      return addOn.itemNumber == optionId;
    }, removeMatchingElement);

    return addOn.length == 0 ? 0 : addOn[0].itemPrice;
  },

  removeSelectedAddOn:function(optionId) {
    var removeMatchingElement = true;
    this.selectedAddOns = jQuery.grep(this.selectedAddOns, function(addOnId) {
      return addOnId == optionId;
    }, removeMatchingElement);

  },

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

  showProductOptionsAndDescription: function(options, description) {
    new Select($("#install_product_options")).populateWith(options, 'itemNumber', 'shortDescription').forceChangeEventForSingleOption();
    $("#dynamicDescription").html(description);
    $('#installation_add_ons').html('');
  },

  showProductAddOns: function(addOns) {
    var self = this;
    jQuery.each(addOns, function(index, addOn) {
      var addOn = new AddOn(name, index, addOn, function(input_value, isSelected) {
        $('#go_to_step_three').removeClass('disabled');
        $('#go_to_step_three').removeClass('blocked');
        $('#schedule_service').addClass('blocked');
        if (isSelected) {
          self.selectedAddOns.push(input_value);

        } else {
          self.removeSelectedAddOn(input_value);
        }
        self.showTotalPrice();
      });
      $(addOn.checkBoxGroup).appendTo($('#installation_add_ons'));
    });
  },

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

  jsonForProducts: function(data) {
    if (data && data.length != 0) {
      OmnitureCall.reportServiceFound();
    }
    new Select($("#product")).populateWith(data, 'id', 'description').forceChangeEventForSingleOption();
    $("#dynamicDescription").html(this.dynamicDescription);
    //$("#dynamicDescription").html(data.serviceDescription);
  },

  jsonForProductCategories: function(data) {
    if (data && data.length != 0) {
      OmnitureCall.reportServiceFound();
    }
    new Select(this.productCategoriesElement).populateWith(data, 'id', 'description').forceChangeEventForSingleOption();
    $("#dynamicDescription").html(this.dynamicDescription);
    //$("#dynamicDescription").html(data.serviceDescription);
    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.productOptions, self.productAdOns, self.selectedAddOns, self.appointment.selectDate).createOrder();
      }
      return false;
    });
  },

  reset: function() {
    $('.install_product_category.fieldset_wrap').parents('fieldset').hide();
    $('.install_product_options.fieldset_wrap').parents('fieldset').hide();
    $('.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();
  },

  observe: function() {
    var self = this;
    this.productCategoriesElement.unbind('change.install').bind('change.install', function() {
      OmnitureCall.reportProductSelected($(this).val());
      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.selectedAddOns.length = 0;

    $('.install_product_options.fieldset_wrap').parents('fieldset').show();
    $('.addons_group_container').show();

    if (!self.heightIncresdForProductOption) {
      SchedulerObserver.scheduler.growHeight(50, $('#step_one'));
      self.heightIncresdForProductOption = true;
    }

    this.update(this.installationProductItemsUrl, this.getParamsForProductItems(), function(data) {
      self.jsonForProductItems(data);
      if (self.productAdOns.length > 6) {
        SchedulerObserver.scheduler.growHeight(self.productAdOns.length * 20, $('#step_one'));
      }
    });

  },

  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, productOptions, addOns, selectedAddOnIds, selectDate) {
    this.zipcode = zipcode;
    this.selectedAddOnIds = selectedAddOnIds;
    this.productOptions = productOptions;
    this.addOns = addOns;
    this.selectDate = selectDate;
  },

  createOrder: function() {
    var self = this;
    var successResponseHandler = function(data) {
      self.processOrderResponse(data);
    };

    var errorFunction = function(installationError) {
      new SchedulerServiceError($.evalJSON(installationError)).display();
    };
    var schedulerRequest = new SchedulerRequest();
    schedulerRequest.httpPost(this.createInstallOrderUrl, this.createOrderParams(), successResponseHandler, errorFunction, $('#schedule_service'));
    return false;
  },

  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(),
      'productOption': $.toJSON(this.selectedProductOption()),
      'productAddOns': $.toJSON(this.selectedAddOnOptions()),
      '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()
    };
  },



  selectedAddOnOptions: function() {
    var self = this;
    var selectedAddOns = new Array();
    jQuery.each(self.addOns, function() {
      var addOn = this;
      if (jQuery.inArray(addOn.itemNumber, self.selectedAddOnIds) > -1) {
        selectedAddOns.push(addOn);
      }
    })
    return selectedAddOns;
  },

  selectedProductOption: function() {
    var self = this;
    var selectedProductOption;
    var selectedOptionId = $("#install_product_options").val();
    jQuery.each(self.productOptions, function() {
      var productOption = this;
      if (productOption.itemNumber == selectedOptionId) {
          selectedProductOption = productOption;
      }
    })
    return selectedProductOption;
  },

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

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

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

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

    var errorFunction = function() {
    };
    var schedulerRequest = new SchedulerRequest();
    schedulerRequest.httpGetJSON(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) {
    var input = this.buildInput(name, index, timeslot);
    var label = this.buildLabel(index, timeslot);
    var radioGroup = this.buildRadioGroup(input, label);

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

    this.radioGroup = $(radioGroup);
  },

  buildInput: function(name, index, timeslot) {
    var timeSlotId = 'timeslot_' + index;

    var input = $('<input name="' + name + '" type="radio"/>');
    $(input).attr('id', timeSlotId);
    $(input).attr('value', timeslot);
    return $(input);
  },

  buildLabel: function(index, timeslot) {
    var timeSlotId = 'timeslot_' + index;

    var label = document.createElement('label');
    $(label).attr('for', timeSlotId);
    $(label).text(timeslot);

    return $(label);
  },

  buildRadioGroup: function(input, label) {
    var radioGroup = document.createElement('div');

    $(radioGroup).addClass('radio_group');
    $(input).appendTo(radioGroup);
    $(label).appendTo(radioGroup);

    return $(radioGroup);
  },

  attachSelectionObserver: function(input) {
    $(input).change(function() {
      var product_name = SchedulerService.productNameForService($("#service :selected").val());
      OmnitureCall.reportSchedulerMicroView("time", $("#zip_code").val(), $("#service").val(), product_name);
      $('.radio_group').removeClass('selected');
      $(this).parent('.radio_group').addClass('selected');
    });
  },

  attachCallbackObserver: function(input, callback) {
    $(input).click(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.clickToCallNumber);
    $("#click_to_call").attr('href', "#" + this.response.clickToCallNumber);
    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() {
    $("#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();
  }
});
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', "#" + RepairSelectPackage.ctcTemplateId);
      $("#click_to_call").attr('href', "#" + RepairSelectPackage.ctcTemplateId);
      $("#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;
}
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;
    $(element).click(function(event) {
      self.getAjaxResponse(element);
      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();
};
//carousel

var Carousel = Class.create({
	init: function(carousel,itemsNumber,isVertical) {
		this.dataSource=$(carousel).data('source');
		this.itemsNumber=itemsNumber;
		this.setupConstants(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(itemsNumber,isVertical){
    this.inlineDataIndicator = "inline:"; 
    this.visibleElements=itemsNumber;
 		this.elementsStep=itemsNumber;
 		this.elementWidth=75;
 		this.elementHeight=75;
 		this.isVertical=isVertical;
 		this.itemsInfo=[];
 		this.itemBorder=1;
 		this.emptyContainerContent="...";
 		this.parent={};
 		this.carousel={};
    this.detailDialog=document.createElement('div');
    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){
	       $('body').css('overflow','hidden');
	       $('.ui-dialog').css('visibility','hidden');
	    },
	    close: function(event, ui){
	       $('body').css('overflow',''); 
	    }
    };
 		//this.elementsStep=4;
 	},
 	
 	/************************************************************
 	  UI setup
 	************************************************************/
 	setupUI:function(carousel,vertical){
		var self=this;
		
    this.carousel=carousel;
    this.parent=carousel.parentNode;
    
    //  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.elementWidth);
		$('.jcarousel-list li,.jcarousel-item').css('width',this.elementWidth);
		
		$(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.emptyContainerContent)
    			{	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.emptyContainerContent;
			}
			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) {
    if(this.dataSource.indexOf(this.inlineDataIndicator) == 0) {
      this.createCarouselItems(carousel, carousel.first, carousel.last, this.dataSource.substring(this.inlineDataIndicator.length));
    }
    else {
      var self = this;
      $.get(this.dataSource, function(data) {
        self.createCarouselItems(carousel, carousel.first, carousel.last, data);
      });
    }
  },
	
  /************************************************************
	  Resize the carousel to display the selected number of items
	************************************************************/
	setContainer:function(){
		var targetProperty="";
		var targetValue=this.itemBorder;
		
    if($(this.carousel).parents('div.jcarousel-container').hasClass('jcarousel-container-horizontal')){
			targetProperty='width';
			targetValue+=
			this.elementWidth+this.getNumericValue($('.jcarousel-item-horizontal').css('margin-right'));
		
		}else{
			targetProperty='height';	
			targetValue+=
			this.elementHeight+this.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');
	},
	
	/************************************************************
	  ajax response parser function
	  
	//TODO: Refactor this function to the AJAX response used -see parseData
	************************************************************/
	parseData:function(data){ 
		//basic example where the data is just some urls joined by the '|' char
		return data.split('|');
	},
	
	/************************************************************
    inner HTML helper for the content of the items (writing in DOM)
	************************************************************/
	getItemHTML:function(url){
		var self=this;
		var element=document.createElement('a');
		var imgContainer=new Image();
		
		$(element).attr('href',url);
		$(element).html('<img src="' + url + '?hei=75&wid=75&op_sharpen=1&qlt=75" />')
		
		$(element).click(function(event) {
      event.preventDefault();
      
      $(self.detailDialog).html('');
      $(self.detailDialog).append(imgContainer);
      
      $(self.detailDialog).dialog('open');
      
      $(imgContainer).load(function () {    
        var position = $(self.detailDialog).dialog('option', 'position');
        var fixedTop=position[1]-($(this).height()/2);
        var fixedLeft=position[0]-($(this).width()/2);
        
        
        $(self.detailDialog).dialog('option', 'position', ['center','center']);
        $('.ui-dialog').css('visibility','visible');
        
      }).error(function(){
        $(self.detailDialog).html('Sorry, there is no detailed image for this selection.');
      }).attr('src', url);
      
    });
		return element;
	},
	
	/************************************************************
	  format helper ('#px'-> #)
	************************************************************/
	getNumericValue:function(strValue){
		return parseInt(strValue.replace('px',''));
	}
});
var OmniturePageInformation = Class.create({
  init: function(pageName, category, pageType) {
    this.pageName = pageName;
    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, ajaxSubmit) {

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

    if (ajaxSubmitProperty) {
      OmnitureReport.ajaxSubmit();
    } else {
      OmnitureReport.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) {
      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(ajaxSubmitProperty) {

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

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

OmnitureReport.allowedProperties = ['pageName', 'channel', "events", "eVar1", "eVar3", "eVar4", "eVar5", "eVar7",
  "eVar8", "state", "zip", "pageType", "prop1", "prop2", "prop3", "prop4", "prop5", "prop6", "prop7", "prop8", "prop9",
  "prop10", "prop11", "prop12", "prop13", "prop14", "prop15", "prop16", "prop17"];

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

OmnitureReport.ajaxSubmit = function() {
  var s_code = s.tl();
}

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 ajax_request = [];
var SchedulerRequest = Class.create({
  init: function() {

  },

  httpGetJSON:   function(resourceUrl, params, successFunction, errorCallBack, elementId) {
    ajax_request.push(httpGetJson(resourceUrl, params, successFunction, errorCallBack, elementId));
  },

  httpPost:  function(resourceUrl, params, sucessFunction, errorCallBack, elementId) {
    httpPost(resourceUrl, params, sucessFunction, errorCallBack, elementId);
  },

  cancelPriorRequest: function() {
    jQuery.each(ajax_request, function() {
      this.onreadystatechange = function() {
      }; // jquery triggers the error handler if the function is not overwritten.
      this.abort();
    });
    ajax_request = [];
  }
});

function httpGetJson(resourceUrl, params, successFunction, errorCallBack, elementId) {
  var errorFunction = function (XMLHttpRequest, textStatus, errorThrown) {
    errorCallBack(XMLHttpRequest.responseText);
  };

  if (typeof elementId == 'undefined') {
    var wrappedSuccessFunction = successFunction;
  } else {
    var spinner = new AjaxSpinner(elementId);
    var wrappedSuccessFunction = function(data) {
      spinner.hide();
      successFunction(data);
    }
  }

  return makeAjaxRequest("GET", resourceUrl, params, wrappedSuccessFunction, errorFunction);
}


function httpPost(resourceUrl, params, successFunction, errorCallBack, elementId) {
  var errorFunction = function (XMLHttpRequest, textStatus, errorThrown) {
    errorCallBack(XMLHttpRequest.responseText);
  };

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

function makeAjaxRequest(type, resourceUrl, params, sucessFunction, errorFunction) {
  return $.ajax({ type     : type,
    url      : resourceUrl,
    data     : params,
    success  : sucessFunction,
    error    : errorFunction,
    dataType : "json"});
}

function errorMessageHandler(errorMessage) {
  new SchedulerServiceError($.evalJSON(errorMessage)).display();
  // $("#message_text").text(errorMessage);
  // $("#error_message").show();
  // $("#scheduler_wrapper").hide();
}
var SchedulerPrepopulator = Class.create({

  selectElementAndTriggerChange: function(elementToSelect, elementToPickValueFrom) {
    var elementValue = elementToPickValueFrom.val();

    if (elementValue != '') {
      elementToSelect.val(elementValue);
      elementToSelect.trigger('change');
    }
  },

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

})

// 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) {
    if ($(field).is('input')) {
      $(field).parents('.input_container').addClass("field_error");
    }
    if ($(field).is('textarea')) {
      $(field).parents('.textarea_container').addClass("field_error");
    } else {
      $(field).addClass("field_error");
    }
  },

  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");
    }
  },

  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 '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);
        }
      }
    },
    phone: function(field, self) {
      var phoneRegEx = /(\D*\d\D*){10}/;
      if (field.val() != '') {
        if (field.hasClass('js_phone') && !field.val().match(phoneRegEx)) {
          self.addError(field, self.getLabel(field) + ' is invalid.', self);
        }
      }
      return true;
    },
    email: function(field, self) {
      var emailRegEx = /\b[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,4}\b/;
      if (field.val() != '') {
        if (field.hasClass('js_email') && !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) {
      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
      if (field.hasClass('js_password') && (field.val() == '' || !field.val().match(passwordRegEx))) {
        self.addError(field, 'Password can not be less than 6 characters. Password must contain one letter (a-z) and one number (0-9). Passwords are case sensitive.', self);
      }
      return true;
    },
    zipcode: function(field, self) {
      if (field.hasClass('js_zipcode') &&  field.val() != '' ) {
        if (!Zipcode.isValid(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;
    }   
    
    this.disableButton();
    $('#scheduler .warning').hide();
    this.storeCallbacks(callbackFunctions);
    this.attachChangeValidationActivition();
    this.attachClickValidationActivition();
  },
  
  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();
    }
  },
  
  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.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 jsOnBlurClass='js_onblur_trigger';
	var fields = this.getFields();  
    var self = this;
    var events = [			
      'change',
      'keyup'	
    ];
    
    $(fields).each(function(index,element){     
      if($(element).hasClass(jsOnBlurClass)){
	  	$(element).blur(function(event){
			$(element).removeClass(jsOnBlurClass);
			self.validate.call(self);
		});
	  }else{
		$.each(events,function(eventIndex,eventItem){
	        if((eventIndex==0)||($(element).is('input'))){
	          $(element).bind(eventItem,function(event){
	            if((isIE())&&((eventIndex==0)&&($(element).is('select')))){
	              if(typeof $(this).data('timeoutId')!='undefined'){
	                clearTimeout($(element).data('timeoutId'));
	              }
	              var timeoutId=setTimeout(function() {
	                self.validate.call(self);   
	              },self.IEtimeoutDuration);
	              
	              $(this).data('timeoutId',timeoutId)
	                
	            }else{
	              self.validate.call(self);
	            }
	          });
	        }
		});  
	  }   
    });    
  },

  attachClickValidationActivition: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);
        });
      }
    });
  },

  validate: function(forceValidate) {
    var fields = this.getFields();
      
    this.removeErrors();
    if((this.shouldValidate(fields))||(forceValidate)) {
      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);						
	          }
	        }
	      }
      });

      this.callCallback();
    }
  },

  shouldValidate: function(fields) {
    var shouldValidate = true;
    if(!this.validated){
      $(fields).each(function() {
        if($(this).val() == '') {
          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() {
    $(this.button).removeClass('disabled');
    $(this.button).removeClass('blocked');
  },
  
  disableButton: function() {
    $(this.button).each(function() {
      if($(this).attr('id') != 'store_locator') {
        $(this).addClass('disabled');
        $(this).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).find('div.content, a.handle, div.section').bgiframe();
    $(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));
   
    var self=this;
    
//    $('.remove_service').live('click',function(event){
//	    event.preventDefault();
//	    var parent=$(this).parents('.container');
//	    $(this).parents('.section_add_service').remove();
//	    self.growHeight(self.standardNewCleaningHeight*-1,parent);
//	  });
    
    $('.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", "");
        }
        
      /*
      */
      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) {
    if(direction < 0) {
      $(container).prev().children('.content').css('visibility', 'visible');
    } else {  
      $(container).children('.content').css('visibility', 'visible');    
    }
  },
  
  setPostAnimationVisibility: function(container, direction) {
    if(direction < 0) {
      $(container).children('.content').css('visibility', 'hidden');      
    } 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;
      }
      this.growHeight((additionalHeight-limit)*-1,container); 

      $(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', '254px');
      
      $(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) {
    $(containers).find('a.secondary_button, a.js_handle, a.exit').each(function(index,element){
      if($(element).attr('id') != 'store_locator'){
        $(element).addClass('disabled');
      } 
    });
  },
   
  enableControls: function(containers) {
    var selector='a.secondary_button, a.js_handle, a.exit';
    $(containers).find(selector).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');
      
    /*
    // TODO: extract this from function, doesn't belong here (commented out, not in use)
    var targetHeight=($(container).hasClass('additional_height'))?$(container).height():this.standardContainerHeight;
    $('#scheduler').animate({height:targetHeight},'slow','swing');
    */
  },
  
  //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;
  },
  
  /*
    Custom events refactor
  ----------------------------------------------------------------------------*/
  setCustomEventsBinding:function(){
    this.NEXT="doNext";
    this.BACK="doBack";
  },
  
  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.attachAllObservers();
    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
    $(handle).css('opacity',1);

	  $(handle).animate({ right:-originalWidth }, { duration:250,complete:function() {
  		$(handle).width(self.handlerWidth);
  		setTimeout( function(){
  			$(container).removeClass('starting_position');
  			$(handle).css('right',0);
  			self.animateTo(container, self);
  		}, pauseTime);
      }
    });
  },

  jumpFromStartingPosition: function(handle, self) {
    var container = $(handle).parents('.container');
    $(container).removeClass('starting_position');
    $(handle).css('width', this.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).css('height', 254); // for IE6, not sure why

    $(element).animate({width:this.standardStepWidth,right:rightTargetPosition}, { duration:"slow",complete:function() {
        $(element).removeClass('short_step');
        $('.step_1_5').fadeIn();
        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');
    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();
	
        if($('#scheduler').hasClass('home_improvement') == false && $(third_step).hasClass('additional_height') == false) {
          this.growHeight(70, this.containers[2]);
        }
      }
      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) {
    var serviceName = $('#schedulerInformation_serviceName');

    if (!serviceName.attr('schedulerOpenedOnLoad') && serviceName.val()!='') {
      $(element).trigger('click');
      serviceName.attr('schedulerOpenedOnLoad', true);
    }
  },

  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);
    $(listItem).appendTo(this.list);
    $(this.element).show();
  },
  clear: function() {
    $(this.element).hide();
    $(this.list).html('');
  }
});
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');
    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.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	= {
			autoOpen: false,
			open: function(event, ui){
				self.checkIfOutOfWindow();
			}
		};
	}	
  },
  
  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_container').height());
    var tmpOffset = 0;
    
    tmpOffset = (tmpElementTop + tmpElementHeight) - tmpDocHeight;
    //alert(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');
  },

  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]);
  }
});
var Button = Class.create({
  init: function(element) {
    this.element = this.buildButton(element);
    if(isIE6()) {
      this.addPngFixClass();
    }
  },
  
  buildButton: function(element) {
    var class_names = $(element).attr('class');
    var button_id = $(element).attr('id');
    var 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');
    $(anchor).attr('href', '#');
    if(button_id) {
      $(anchor).attr('id', button_id);
    }
    $(anchor).attr('class', class_names);
    $(anchor).html('<span>' + button_name + '</span>');
    
    $(element).replaceWith(anchor);
    $(anchor).removeClass('js_button');
    return anchor;
  },
  
  buildFromAnchorTag:function(element, button_name) {
    var span = document.createElement('span');
    $(span).html(button_name);
    $(element).html(span);
    return element;
  },
  
  addPngFixClass: function(element) {
    $(element).find('a').addClass('pngfix');
    $(element).find('span').addClass('pngfix');
    
    $('#scheduler').find('.pngfix').removeClass('pngfix');  
  }
});
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');
      }
    });
  }
});
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 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) {
    this.attachEdit(form);
    this.attachSave(form, objectCallback);
    this.attachCancel(form);
    this.errorHolder = new ErrorHolder($(form).find('.warning'));
  },

  attachEdit: function(form) {
    var self = this;
    $(form).find('.edit').click(function(event) {
      self.transformToEditing(form);
      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.cancelToViewing(form);
      event.preventDefault();
    });
  },

  transformToEditing: function(form) {
    var inputs = $(form).find('input, select, textarea');
    
    $(form).removeClass('viewing').addClass('editing');

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

  transformToViewing: function(form) {
    var ptags = $(form).find('p');
    $(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 {
      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);
    }
  },

  setTextForPrimaryToggle: function(p, input) {
    if($(input).attr('checked')) {
      $(p).text($(p).prev().text());
    } else {
      $(p).text('');
    }
  }
});

var PersonalInformation = Class.create({
  init: function(form) {
    this.editFormInPlace = new EditFormInPlace(form, this);
  },

  update : function(element) {
    var self = this;
    this.editFormInPlace.makeAjaxRequest(
      "POST",
      PersonalInformation.updateUrl,
      this.prepareParams(),
      function() {
        self.showSuccessMessage(element)
      },
      function(errorResponse) {
        self.showErrorMessage(errorResponse)
      }
    );
  },

  prepareParams: function() {
    //  Need to remove all this logic . This is a temporray thing till we finalize the creatives.
    var nameValue = $('#pr_name').val();
    var nameArray = jQuery.trim(nameValue).split(" ");
    var lastName = (nameArray.length == 1) ? "" : this.setEmptyStringOnUndefined(nameArray[nameArray.length - 1]);
    var firstName = this.setEmptyStringOnUndefined(nameValue.replace(lastName, ""));

    return {
      '_method': "PUT",
      'firstName': firstName,
      'lastName': lastName,
      'emailId': $('#pr_email_id').val(),
      'languagePref': $('#pr_language_pref').val(),
      'defaultAddress': $('#pr_profile [name=default_address]:checked').val(),
      'firstAddress.streetLine1': $('#pr_pri_address_line1').val(),
      'firstAddress.city': $('#pr_pri_city').val(),
      'firstAddress.state': $('#pr_pri_state').val(),
      'firstAddress.zipCode': $('#pr_pri_zip').val(),
      'firstAddress.defaultAddress': $('#primary_default').is(":checked"),
      'secondAddress.streetLine1': $('#pr_sec_address_line1').val(),
      'secondAddress.city': $('#pr_sec_city').val(),
      'secondAddress.state': $('#pr_sec_state').val(),
      'secondAddress.zipCode': $('#pr_sec_zip').val(),
      'secondAddress.defaultAddress': $('#secondary_default').is(":checked"),
      'homePhoneNumber':$('#pr_home_phone_number').val(),
      'mobilePhoneNumber':$('#pr_mobile_phone_number').val(),
      'defaultPhone':$('#pr_profile [name=primary_phone_number]:checked').val()
    };
  },

  setEmptyStringOnUndefined :function(value) {
    return value == null ? "" : jQuery.trim(value);
  },

  showSuccessMessage: function(element) {
    this.editFormInPlace.hideErrors();
    this.editFormInPlace.transformToViewing(element);
  },

  showErrorMessage: function(errorResponse) {
    this.editFormInPlace.showErrors(errorResponse.statusText);
  }
});
PersonalInformation.updateUrl = "/shs/update-personal-information!update";

var ContactPreferences = Class.create({
  init: function(form) {
    this.editFormInPlace = new EditFormInPlace(form, this);
  },

  update : function(element) {
    var self = this;
    this.editFormInPlace.makeAjaxRequest(
      "POST",
      ContactPreferences.updateUrl,
      this.prepareParams(),
      function() {
        self.showSuccessMessage(element)
      },
      function(errorResponse) {
        self.showErrorMessage(errorResponse)
      }
    );
  },
  prepareParams: function() {
    return {
      '_method': "PUT",
      'optForEmail': $("#email_communications").is(":checked")? "Y":"N"
    };
  },

  showSuccessMessage: function(element) {
    this.editFormInPlace.hideErrors();
    this.editFormInPlace.transformToViewing(element);
  },

  showErrorMessage: function(errorResponse) {
    this.editFormInPlace.showErrors(errorResponse.statusText);
  }

});

ContactPreferences.updateUrl = '/shs/update-contact-preferences!update'
var ChangePassword = Class.create({
  init: function(form) {
    this.editFormInPlace = new EditFormInPlace(form, this);
  },

  update : function(element) {
    var self = this;
    this.editFormInPlace.makeAjaxRequest(
      "POST",
      ChangePassword.updateUrl,
      this.prepareParams(),
      function() {
        self.showSuccessMessage(element)
      },
      function(errorResponse) {
        self.showErrorMessage(errorResponse)
      }
    );
  },

  prepareParams: function() {
    return {
      '_method': "PUT",
      'password': $("#pwd_current_password").val(),
      'newPassword': $("#pwd_new_password").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(errorResponse.statusText);
    $("#pwd_profile").removeClass("js_password_form");
  }
});

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;
		//getting title
		this.text=$(this.element).attr('title');
		$(this.element).removeAttr('title');
	},
	
  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);
		dialog.find('.content').text(self.text);

	    timeoutId = setTimeout(function(){
			$(self.dialog).show('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;
	//console.log(event.screenY+" vs "+event.clientY);
	return targetTop
  }
});
// 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.attachLoginDialog = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_login_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();
      // 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();
}
// 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');
      $(container).removeClass('show').addClass('hide');
      
      event.preventDefault();
    });
  }
});


LinkObserver.attachAllObservers = function() {
  new LinkObserver.attachExternalLink();
  new LinkObserver.attachHideContainer();
  new LinkObserver.attachShowContainer();
}
// 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) {
    var template = 'Template=' + $(element).attr('href').split('#')[1];

    $(element).click(function(event) {
      OmnitureCall.reportToolUsage("click to call");
      webVoicePop(template);
      event.preventDefault();
    });
  }
});

UIObserver.attachClickToChat = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.index = 0;
    this.findElements('js_click_to_chat', function() {
      if (typeof ii_247SBObj != 'undefined') {
        ii_247SB = new ii_247SBObj(26199, 26200);
      }
    });
  },
  attachBehavior: function(element) {
    // Click to chat ID's must be unique (third party code...)
    $(element).attr('id', 'id_SmartButton_' + this.index);
    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.attachAnswerPaginationAjax = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('answer_search.page_link');
  },
  attachBehavior:function(element) {
    new AnswerPaginationAjax(element);
  }
});

UIObserver.attachPersonalInformationForm = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_personal_information_form');
  },
  attachBehavior:function(element) {
    new PersonalInformation(element);
  }
});

UIObserver.attachAssignDefaultAddress = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('address_default');
    this.initializeDefault();
  },
  initializeDefault: function() {
    var defaultElement = $('#primary_default');
    if ($('#secondary_default').is(":checked")) {
      defaultElement = $('#secondary_default');
    }
    UIObserver.setDefaultAddressAsRequired(defaultElement);
  },
  attachBehavior: function(element) {
    $(element).click(function(event) {
      UIObserver.setDefaultAddressAsRequired($(element));
    });
  }
});

UIObserver.setDefaultAddressAsRequired = function(element) {
  var addClassElement = $('#pr_pri_zip');
  var removeClassElement = $('#pr_sec_zip');

  if (element.attr('id') == 'secondary_default') {
    addClassElement = $('#pr_sec_zip');
    removeClassElement = $('#pr_pri_zip');
  }

  addClassElement.addClass('js_required');
  removeClassElement.removeClass('js_required');
  removeClassElement.removeClass('field_error');
  removeClassElement.parents('.input_container').removeClass("field_error");
};


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.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.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.attachAnswerPaginationAjax();
  new UIObserver.attachPersonalInformationForm();
  new UIObserver.attachChangePasswordForm();
  new UIObserver.attachContactPreferencesForm();
  new UIObserver.attachEnhancedTooltip();
  new UIObserver.attachAssignDefaultAddress();
}
// 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('textarea.submit_trigger, input[type=text].submit_trigger, input[type=password].submit_trigger').keyup(function(event){
		if(event.keyCode==13){
			event.preventDefault();
			$(submitTrigger).click();
		}
	})
  },
  
  submitRequest : function(form, dialog, ajax_submit, errorHolder) {
    if(ajax_submit) {
      $.post($(form).attr('action'), $(form).serialize());
    } else {
      $(form).submit();
    }
    if(dialog) {
      $(dialog).dialog('close');
    }
  }
});


/*
	$(element).keyup(function(event){
      self.updateCount(counter, element, limit);
	});	
  });
 */

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.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();
    });
  }
});

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.attachLinkForReschedule = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_reschedule_order');
  },
  attachBehavior: function(element) {
    $(element).click(function(event) {
      $('.reschedule').removeClass('hide').addClass('show');
      var rescheduleDateHandler = new RescheduleDateHandler($(this));
      rescheduleDateHandler.initialize();
      event.preventDefault();
    });
  }
});

SchedulerObserver.attachLinkForCancel = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_cancel_order');
  },
  attachBehavior: function(element) {
    $(element).click(function(event) {
      var cancelHandler = new CancelHandler($(this));
      cancelHandler.initialize(event);
      event.preventDefault();
    });
  }
});

SchedulerObserver.attachPresetRescheduleLinks = Class.create(JSClassObserver.prototype, {
   init: function() {
     this.findElements('js_preset_reschedule');
   },
  attachBehavior: function(element) {
    $("#reschedule_link").trigger('click');
  }
});

SchedulerObserver.attachPresetCancelLinks = Class.create(JSClassObserver.prototype, {
   init: function() {
     this.findElements('js_preset_cancel');
   },
  attachBehavior: function(element) {
    $("#cancel_dialog").show();
    $("#cancel_dialog").dialog();
  }
});

SchedulerObserver.attachSchedulerOpenTracking = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_scheduler_open_tracking');
  },
  attachBehavior: function(element) {
    $(element).click(function() {
      OmnitureCall.reportSchedulerOpen();
      OmnitureCall.reportSchedulerMacroView('Start');
      OmnitureCall.reportAjaxToolUsage('Scheduler');
    });
  }
});

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:'Schdedule 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);
    });
  }
});

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.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());
      OmnitureCall.reportSchedulerMicroView(field_name, $("#zip_code").val(), $("#service").val(), product_name);
    });
  }
});

SchedulerObserver.attachOpenSchedulerOnLoad = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_open_on_load');
  },

  attachBehavior: function(element) {
    SchedulerObserver.scheduler.openSchedulerOnLoad(element);
  }
});

SchedulerObserver.attachAllObservers = function() {
  new SchedulerObserver.attachAccordion();
  new SchedulerObserver.attachNextButton();
  new SchedulerObserver.attachStartButton();
  new SchedulerObserver.attachPreviousButton();
  new SchedulerObserver.attachExitButton();
  new SchedulerObserver.attachLinkForReschedule();
  new SchedulerObserver.attachLinkForCancel();
  new SchedulerObserver.attachSchedulerOpenTracking();
  new SchedulerObserver.attachSchedulerNextTracking();
  new SchedulerObserver.attachZipTracking();
  new SchedulerObserver.attachFieldTracking();
  new SchedulerObserver.attachPresetRescheduleLinks();
  new SchedulerObserver.attachPresetCancelLinks();
  new SchedulerObserver.attachOpenSchedulerOnLoad(); // Imp: attachOpenSchedulerOnLoad should always be the last observer
}
CarouselObserver={};

CarouselObserver.attachProductGalleryCarousel = Class.create(JSClassObserver.prototype, {
  init: function() {
    CarouselObserver.carousels=[];
    this.itemsNumber=6;
    this.findElements('js_productGalleryCarousel');
     
  },
  attachBehavior: function(element) {
     CarouselObserver.carousels.push(new Carousel(element,this.itemsNumber));
  }
});

CarouselObserver.attachAllObservers = function() {
  new CarouselObserver.attachProductGalleryCarousel();
}
/******************* 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();
        }
        
        SchedulerObserver.scheduler.resetHeight($('#step_one'));
                
        if($('#service').val() != 'home_improvement'){
          SchedulerObserver.scheduler.resetHeight($('#step_two'),35);
          $('#contact_by_phone').hide();
        }
        
        if ($('#service').val() == 'repair') {
          SchedulerValidationObserver.steps[1] = new SchedulerValidationObserver.attachValidateProductGroup();
          $('.product.fieldset_wrap').parents('fieldset').hide();
          $('.product_group.fieldset_wrap').parents('fieldset').show();
          
        } else if ($('#service').val() == 'installation') {
          SchedulerValidationObserver.steps[1] = new SchedulerValidationObserver.attachValidateInstallationProductCategory();
          $('.product_group.fieldset_wrap').parents('fieldset').hide();
          $('.product.fieldset_wrap').parents('fieldset').hide();
          $('.install_product_category.fieldset_wrap').parents('fieldset').show();
          $('#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');
    });
    
    // 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'));
      }
    }     
    
    $(element).show('fast');
    
    this.fieldset = new SchedulerValidation(element, {
      
      onComplete:function() {
        
        delete SchedulerValidationObserver.steps[2];
        
        if ($('#product:visible')) {
          $('#go_to_step_two').addClass('disabled');
          $(element).find('option[value=]').remove();
          
          
          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) {
    
    $('#contact_by_phone').show('fast');
    this.additionalHeight = 45;
    
    SchedulerObserver.scheduler.growHeight(this.additionalHeight, $('#step_two'));
    
    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();
      }
    }, 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, {
      onComplete:function() {
        $(element).find('option[value=]').remove();
      }
    }, schedulerStep1ErrorHolder);
  }
});

SchedulerValidationObserver.attachValidateRepairInfo = Class.create(JSClassObserver.prototype, {
  fieldset:{},

  init: function() {
    this.findElements('js_validate_repair_info');
  },
  attachBehavior: function(element) {
    this.fieldset = new SchedulerValidation(element, {
      onComplete:function(){
        $(element).find('option[value=]').remove();
      }
    }, 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.attachAllObservers = function() {
  //Check out why is the undefined evaluation
  
  //if(typeof schedulerStep1ErrorHolder == 'undefined') {
    schedulerStep1ErrorHolder = new ErrorHolder($('#scheduler #step_one .warning'));
  //}
  //if(typeof schedulerStep3ErrorHolder == 'undefined') {
    schedulerStep3ErrorHolder = new ErrorHolder($('#scheduler #step_three .warning'));
  //}

  SchedulerValidationObserver.steps[0] = new SchedulerValidationObserver.attachValidateZipAndService();
  new SchedulerValidationObserver.attachContactInfo();
}
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.reportAnswersSearch(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.reportViewAllAnswers(searchTerm);
    });
  }
});

OmnitureObserver.attachFindAPart = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_omniture_find_a_part');
  },
  attachBehavior: function(element) {
    $(element).click(function() {
      OmnitureCall.reportPartsDirect();
    });
  }
});

OmnitureObserver.attachFindAManual = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_omniture_find_a_manual');
  },
  attachBehavior: function(element) {
    $(element).click(function() {
      OmnitureCall.reportManageMyHome();
    });
  }
});

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.reportAjaxToolUsage("Read Answer");
      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.attachSearchPages = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_omniture_search_pages');
  },
  attachBehavior: function(element) {
    $(element).click(function() {
      OmnitureCall.reportSearchPages();
    });
  }
});


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.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.attachSearchPages();
};
var LoginObserver = {};

LoginObserver.attachCancelRegister = Class.create(JSClassObserver.prototype, {
  init: function() {
    this.findElements('js_cancel_register');
  },
  attachBehavior: function(element) {
    $(element).click(function() {
      location.href = '/shs/products';
    });
  }
});

LoginObserver.attachSubmitLogin = Class.create(FormObserver.attachSubmitForm.prototype, {
  init: function() {
    this.findElements('js_login_form_button');
  },
  submitRequest: function(form, dialog, ajax_submit, errorHolder) {
    var onSuccess = function(location) {
      if (dialog) {
        $(dialog).dialog('close');
      }
      // if the user is on register page it should redirect to home page
      if (location.indexOf('register') != -1) {
        location = "products"
      }
      if(location.indexOf('blog/shs') != -1) {
        window.location.href = '/blog/shs';
        return;
      }
      window.location.href = '/shs/' + location;
    }
    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"
    });
  }
});

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);
      new DialogObserver.attachLoginDialog();
    });
  }
});

LoginObserver.attachAllObservers = function() {
  new LoginObserver.attachLoginStatus();
  new LoginObserver.attachCancelRegister();
  new LoginObserver.attachSubmitLogin();
};

LoginObserver.loginStatusUrl = "/shs/login-status";


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 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) {
    if (count == 0) {
      OmnitureCall.reportNoSearchResults();
    }
  });
});
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/yYAK17Uus-0&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
    });   
  }
});

