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

var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'themes': {}, 'locale': {} };

/**
 * Set the variable that indicates if JavaScript behaviors should be applied
 */
Drupal.jsEnabled = document.getElementsByTagName && document.createElement && document.createTextNode && document.documentElement && document.getElementById;

/**
 * Attach all registered behaviors to a page element.
 *
 * Behaviors are event-triggered actions that attach to page elements, enhancing
 * default non-Javascript UIs. Behaviors are registered in the Drupal.behaviors
 * object as follows:
 * @code
 *    Drupal.behaviors.behaviorName = function () {
 *      ...
 *    };
 * @endcode
 *
 * Drupal.attachBehaviors is added below to the jQuery ready event and so
 * runs on initial page load. Developers implementing AHAH/AJAX in their
 * solutions should also call this function after new page content has been
 * loaded, feeding in an element to be processed, in order to attach all
 * behaviors to the new content.
 *
 * Behaviors should use a class in the form behaviorName-processed to ensure
 * the behavior is attached only once to a given element. (Doing so enables
 * the reprocessing of given elements, which may be needed on occasion despite
 * the ability to limit behavior attachment to a particular element.)
 *
 * @param context
 *   An element to attach behaviors to. If none is given, the document element
 *   is used.
 */
Drupal.attachBehaviors = function(context) {
  context = context || document;
  if (Drupal.jsEnabled) {
    // Execute all of them.
    jQuery.each(Drupal.behaviors, function() {
      this(context);
    });
  }
};

/**
 * Encode special characters in a plain-text string for display as HTML.
 */
Drupal.checkPlain = function(str) {
  str = String(str);
  var replace = { '&': '&amp;', '"': '&quot;', '<': '&lt;', '>': '&gt;' };
  for (var character in replace) {
    var regex = new RegExp(character, 'g');
    str = str.replace(regex, replace[character]);
  }
  return str;
};

/**
 * Translate strings to the page language or a given language.
 *
 * See the documentation of the server-side t() function for further details.
 *
 * @param str
 *   A string containing the English string to translate.
 * @param args
 *   An object of replacements pairs to make after translation. Incidences
 *   of any key in this array are replaced with the corresponding value.
 *   Based on the first character of the key, the value is escaped and/or themed:
 *    - !variable: inserted as is
 *    - @variable: escape plain text to HTML (Drupal.checkPlain)
 *    - %variable: escape text and theme as a placeholder for user-submitted
 *      content (checkPlain + Drupal.theme('placeholder'))
 * @return
 *   The translated string.
 */
Drupal.t = function(str, args) {
  // Fetch the localized version of the string.
  if (Drupal.locale.strings && Drupal.locale.strings[str]) {
    str = Drupal.locale.strings[str];
  }

  if (args) {
    // Transform arguments before inserting them
    for (var key in args) {
      switch (key.charAt(0)) {
        // Escaped only
        case '@':
          args[key] = Drupal.checkPlain(args[key]);
        break;
        // Pass-through
        case '!':
          break;
        // Escaped and placeholder
        case '%':
        default:
          args[key] = Drupal.theme('placeholder', args[key]);
          break;
      }
      str = str.replace(key, args[key]);
    }
  }
  return str;
};

/**
 * Format a string containing a count of items.
 *
 * This function ensures that the string is pluralized correctly. Since Drupal.t() is
 * called by this function, make sure not to pass already-localized strings to it.
 *
 * See the documentation of the server-side format_plural() function for further details.
 *
 * @param count
 *   The item count to display.
 * @param singular
 *   The string for the singular case. Please make sure it is clear this is
 *   singular, to ease translation (e.g. use "1 new comment" instead of "1 new").
 *   Do not use @count in the singular string.
 * @param plural
 *   The string for the plural case. Please make sure it is clear this is plural,
 *   to ease translation. Use @count in place of the item count, as in "@count
 *   new comments".
 * @param args
 *   An object of replacements pairs to make after translation. Incidences
 *   of any key in this array are replaced with the corresponding value.
 *   Based on the first character of the key, the value is escaped and/or themed:
 *    - !variable: inserted as is
 *    - @variable: escape plain text to HTML (Drupal.checkPlain)
 *    - %variable: escape text and theme as a placeholder for user-submitted
 *      content (checkPlain + Drupal.theme('placeholder'))
 *   Note that you do not need to include @count in this array.
 *   This replacement is done automatically for the plural case.
 * @return
 *   A translated string.
 */
Drupal.formatPlural = function(count, singular, plural, args) {
  var args = args || {};
  args['@count'] = count;
  // Determine the index of the plural form.
  var index = Drupal.locale.pluralFormula ? Drupal.locale.pluralFormula(args['@count']) : ((args['@count'] == 1) ? 0 : 1);

  if (index == 0) {
    return Drupal.t(singular, args);
  }
  else if (index == 1) {
    return Drupal.t(plural, args);
  }
  else {
    args['@count['+ index +']'] = args['@count'];
    delete args['@count'];
    return Drupal.t(plural.replace('@count', '@count['+ index +']'));
  }
};

/**
 * Generate the themed representation of a Drupal object.
 *
 * All requests for themed output must go through this function. It examines
 * the request and routes it to the appropriate theme function. If the current
 * theme does not provide an override function, the generic theme function is
 * called.
 *
 * For example, to retrieve the HTML that is output by theme_placeholder(text),
 * call Drupal.theme('placeholder', text).
 *
 * @param func
 *   The name of the theme function to call.
 * @param ...
 *   Additional arguments to pass along to the theme function.
 * @return
 *   Any data the theme function returns. This could be a plain HTML string,
 *   but also a complex object.
 */
Drupal.theme = function(func) {
  for (var i = 1, args = []; i < arguments.length; i++) {
    args.push(arguments[i]);
  }

  return (Drupal.theme[func] || Drupal.theme.prototype[func]).apply(this, args);
};

/**
 * Parse a JSON response.
 *
 * The result is either the JSON object, or an object with 'status' 0 and 'data' an error message.
 */
Drupal.parseJson = function (data) {
  if ((data.substring(0, 1) != '{') && (data.substring(0, 1) != '[')) {
    return { status: 0, data: data.length ? data : Drupal.t('Unspecified error') };
  }
  return eval('(' + data + ');');
};

/**
 * Freeze the current body height (as minimum height). Used to prevent
 * unnecessary upwards scrolling when doing DOM manipulations.
 */
Drupal.freezeHeight = function () {
  Drupal.unfreezeHeight();
  var div = document.createElement('div');
  $(div).css({
    position: 'absolute',
    top: '0px',
    left: '0px',
    width: '1px',
    height: $('body').css('height')
  }).attr('id', 'freeze-height');
  $('body').append(div);
};

/**
 * Unfreeze the body height
 */
Drupal.unfreezeHeight = function () {
  $('#freeze-height').remove();
};

/**
 * Wrapper around encodeURIComponent() which avoids Apache quirks (equivalent of
 * drupal_urlencode() in PHP). This function should only be used on paths, not
 * on query string arguments.
 */
Drupal.encodeURIComponent = function (item, uri) {
  uri = uri || location.href;
  item = encodeURIComponent(item).replace(/%2F/g, '/');
  return (uri.indexOf('?q=') != -1) ? item : item.replace(/%26/g, '%2526').replace(/%23/g, '%2523').replace(/\/\//g, '/%252F');
};

/**
 * Get the text selection in a textarea.
 */
Drupal.getSelection = function (element) {
  if (typeof(element.selectionStart) != 'number' && document.selection) {
    // The current selection
    var range1 = document.selection.createRange();
    var range2 = range1.duplicate();
    // Select all text.
    range2.moveToElementText(element);
    // Now move 'dummy' end point to end point of original range.
    range2.setEndPoint('EndToEnd', range1);
    // Now we can calculate start and end points.
    var start = range2.text.length - range1.text.length;
    var end = start + range1.text.length;
    return { 'start': start, 'end': end };
  }
  return { 'start': element.selectionStart, 'end': element.selectionEnd };
};

/**
 * Build an error message from ahah response.
 */
Drupal.ahahError = function(xmlhttp, uri) {
  if (xmlhttp.status == 200) {
    if (jQuery.trim($(xmlhttp.responseText).text())) {
      var message = Drupal.t("An error occurred. \n@uri\n@text", {'@uri': uri, '@text': xmlhttp.responseText });
    }
    else {
      var message = Drupal.t("An error occurred. \n@uri\n(no information available).", {'@uri': uri, '@text': xmlhttp.responseText });
    }
  }
  else {
    var message = Drupal.t("An HTTP error @status occurred. \n@uri", {'@uri': uri, '@status': xmlhttp.status });
  }
  return message;
}

// Global Killswitch on the <html> element
if (Drupal.jsEnabled) {
  // Global Killswitch on the <html> element
  $(document.documentElement).addClass('js');
  // 'js enabled' cookie
  document.cookie = 'has_js=1; path=/';
  // Attach all behaviors.
  $(document).ready(function() {
    Drupal.attachBehaviors(this);
  });
}

/**
 * The default themes.
 */
Drupal.theme.prototype = {

  /**
   * Formats text for emphasized display in a placeholder inside a sentence.
   *
   * @param str
   *   The text to format (plain-text).
   * @return
   *   The formatted text (html).
   */
  placeholder: function(str) {
    return '<em>' + Drupal.checkPlain(str) + '</em>';
  }
};
;
/* ========================================================================
   << Library for cross browser >>

   JavaScript Library for Netscape Navigator 4.0+
                       and Internet Explorer 4.0+

   Author : Shinichi Hagiwara
   Type   : library - free software
   History:
   1.0   : 10/18/1998 original
   1.1   : 08/15/2000 remake for my book
   2.0   : 05/13/2001 add procedure for NN6
   2.1   : 05/20/2001 add the functions getLeftFromEvent,getTopFromEvent
   2.2   : 05/27/2001 update the functions getLeftFromEvent,getTopFromEvent
   2.3   : 06/03/2001 update the functions initDivPos,initDivSize
   2.4   : 07/08/2001 update the functions external sourced layer for NN6( buggy :-D )
                      update the function createLayer,
                      add the function getDivForm
   2.5   : 07/15/2001 add the function setDivVisibilities
   2.6   : 08/26/2001 add the function setDivStyleAttribute
   2.7   : 10/21/2001 update the functions. setDivBackgroundColor,setDivBackgroundImage
   2.8   : 03/24/2002 support IE5.12(on mac OSX. but, buggy)

   Copyright(C) 1998 - 2002 ShinSoft. All rights reserved.
________________________________________________________________________ */

/* =====================================================================
 * ˆÈ‰º‚Ì•Ï”‚Íƒuƒ‰ƒEƒU‚ÌŽ¯•Ê‹y‚ÑŠÖ”‚ÌŒÝŠ·‚ð‚Æ‚é‚½‚ß‚Ì‚à‚Ì‚Å‚·B
 * ‚à‚µA‚±‚Ìƒtƒ@ƒCƒ‹‚ðŠO•”ƒ\[ƒX( SCRIPT ƒ^ƒO“à‚Ì src‘®« )‚ÅŽg—p‚·‚é
 * ê‡‚ÍAˆÈ‰º‚Ì•Ï”‚ð HTML –{‘Ì‚Ì SCRIPT ƒ^ƒO“à‚ÉˆÚ“®‚µ‚ÄŽg—p‚µ‚Ä‚­‚¾‚³‚¢B
 * ( ŠO•”ƒ\[ƒX“à‚Å’¼Ú’è‹`‚µ‚½•Ï”’l‚Í NN4 ‚Å‚ÍŽÀs‚³‚ê‚È‚¢ê‡‚ª‚ ‚è‚Ü‚· )
________________________________________________________________________ */
// variables
// version of library
LCB_version = 2.8;
// _mac : true = macintosh, false = other os
_mac=navigator.userAgent.indexOf('Mac')!=-1;
// _ie512 : true = MSIE 5.12(mac), false = others
_ie512=navigator.userAgent.indexOf('MSIE 5.12')!=-1;
// _dom : kind of DOM.
//        IE4 = 1, IE5+ = 2, NN4 = 3, NN6+ = 4, others = 0
_dom = document.all?(document.getElementById?2:1)
                   :(document.getElementById?4:(document.layers?3:0));
_createLayerNo = 0;                    // layer no.
/* ======================================================================
 *‚±‚ÌƒXƒNƒŠƒvƒg‚ðŠO•”ƒ\[ƒX‚Æ‚µ‚ÄŽg—p‚·‚éê‡‚ÍˆÈ‰º‚ÌŠÖ”‚ð—LŒø‚É‚µ‚Ä
 * Žg—p‚·‚éÅ‰‚É onLoad ƒCƒxƒ“ƒg‚Å‚±‚ÌŠÖ”‚ðŒÄ‚Ño‚µ‚Ä‰Šú‰»‚µ‚Ä‰º‚³‚¢ */
function initCrossBrowserLib(){
  _mac=navigator.userAgent.indexOf('Mac')!=-1;
  _ie512=navigator.userAgent.indexOf('MSIE 5.12')!=-1;
  _dom=document.all?(document.getElementById?2:1)
                     :(document.getElementById?4:(document.layers?3:0));
  _createLayerNo=0;
}
initCrossBrowserLib();


/* _____________________________________________________________________ */
function getWindowWidth (){
  if(_dom==4 || _dom==3) return window.innerWidth;
  if(_dom==2 || _dom==1) return document.body.clientWidth;
  return 0;
}

function getWindowHeight(){
  if(_dom==4 || _dom==3) return window.innerHeight;
  if(_dom==2 || _dom==1) return document.body.clientHeight;
  return 0;
}

function getWinXOffset(){
  if(_dom==4)            return window.scrollX;
  if(_dom==2 || _dom==1) return document.body.scrollLeft;
  if(_dom==3)            return window.pageXOffset;
  return 0;
}

function getWinYOffset(){
  if(_dom==4)            return window.scrollY;
  if(_dom==2 || _dom==1) return document.body.scrollTop;
  if(_dom==3)            return window.pageYOffset;
  return 0;
}

function getDivFromName(nm){
  if(_dom==4 || _dom==2) return document.getElementById(nm);
  if(_dom==1)            return document.all(nm);
  if(_dom==3){
    var s='';
    for(var i=1; i<arguments.length; i++) s+='document.layers.'+arguments[i]+'.';
    return eval(s+'document.layers.'+nm);
  }
  return null;
}

function getDivName(div){
  if(_dom==4 || _dom==2 || _dom==1) return div.id;
  if(_dom==3)                       return div.name;
  return '';
}

function createLayer(left,top,width,height,parentDiv){
  var s='';
  if(arguments.length>5){
    for(var i=5; i<arguments.length; i++) s+=arguments[i];
  }
  if(_dom==4){
    var divName= '_js_layer_'+_createLayerNo; _createLayerNo++;
    var pDiv   =parentDiv?parentDiv:document.body;
    var div    =document.createElement('DIV');
    div.id=divName;
    div.setAttribute('style',
       'position:absolute;left:'+left+';top:'+top
      +(width >0?(';width:' +width ):'')
      +(height>0?(';height:'+height):'')
      +';visibility:hidden');
    var range=document.createRange();
    range.selectNodeContents(div);
    range.collapse(true);
    var cf=range.createContextualFragment(s);
    div.appendChild(cf);
    pDiv.appendChild(div);
    return div;
  }
  if(_dom==2 || _dom==1){
    var adj    =(_mac&&!_ie512)?' ':'';
    var divName= '_js_layer_'+_createLayerNo; _createLayerNo++;
    var ha     =(height>0)?(';height:'+height):'';
    var pDiv   =parentDiv?parentDiv:document.body;
    pDiv.insertAdjacentHTML('BeforeEnd',
       '<div id="'+divName
      +'" style="position:absolute;left:'+left+';top:'+top
      +(width >0?(';width:' +width ):';width:1')
      +(height>0?(';height:'+height):'')
      +';visibility:hidden;">'+s+'<\/div>'+adj);
    return document.all(divName);
  }
  if(_dom==3){
    var div=parentDiv?(new Layer(width,parentDiv)):(new Layer(width));
    if(height>0) div.resizeTo(width,height);
    div.moveTo(left,top);
    if(s!=''){
      div.document.open('text/html','replace');
      div.document.write(s);
      div.document.close();
    }
    return div;
  }
  return null;
}

function createExLayer(url,left,top,width,height,parentDiv){
  if(_dom==4){
    var divName= '_js_layer_'+_createLayerNo; _createLayerNo++;
    var pDiv   =parentDiv?parentDiv:document.body;
    var div    =document.createElement('IFRAME');
    div.id=divName;
    div.name=divName;
    div.setAttribute('style',
       'position:absolute;left:'+left+';top:'+top
      +';width:'+width+(height>0?(';height:'+height):'')
      +';visibility:hidden');
    div.setAttribute('src',url);
    div.setAttribute('frameborder',0);
    div.setAttribute('scrolling','no');
    pDiv.appendChild(div);
    return div;
  }
  if(_dom==2 || _dom==1){
    var adj=(_mac&&_ie512)?' ':'';
    var bd, divName='_js_layer_'+_createLayerNo;
    _createLayerNo++;
    var ha=(height>0)?(';height:'+height):'';
    if(arguments.length>5 && parentDiv)
         bd=parentDiv;
    else bd=document.body;
    bd.insertAdjacentHTML('BeforeEnd',
       '<div id="'+divName
      +'" style="position:absolute;left:'+left+';top:'+top
      +';width:'+width+ha+';visibility:hidden;">'
      +'<iframe src="'+url+'" name="'+divName+'_if" '
      +'width='+width+' height='+height
      +'marginwidth=0 marginheight=0 '
      +'scrolling="no" frameborder="no">'
      +'<\/iframe>'
      +'<\/div>'+adj);
    return document.all(divName);
  }
  if(_dom==3){
    var div=parentDiv?(new Layer(width,parentDiv)):(new Layer(width));
    if(height>0) div.resizeTo(width,height);
    div.moveTo(left,top);
    div.load(url,width);
    return div;
  }
  return null;
}

function getDivImage(div,imgName){
  if(_dom==4)            return document.images[imgName];
  if(_dom==2 || _dom==1) return document.images(imgName);
  if(_dom==3)            return div.document.images[imgName];
  return null;
}

function getDivForm(div,frmName){
  if(_dom==4)            return document.forms[frmName];
  if(_dom==2 || _dom==1) return document.forms(frmName);
  if(_dom==3)            return div.document.forms[frmName];
  return null;
}

function initDivPos(div){
  if(_dom==4){
    div.style.left=div.offsetLeft+'px';
    div.style.top =div.offsetTop +'px';
  }
  else if(_dom==2 || _dom==1){
    div.style.pixelLeft=div.offsetLeft;
    div.style.pixelTop =div.offsetTop;
  }
  return div;
}

function getDivLeft(div){
  if(_dom==4 || _dom==2) return div.offsetLeft;
  if(_dom==1)            return div.style.pixelLeft;
  if(_dom==3)            return div.left;
  return 0;
}

function getDivTop(div){
  if(_dom==4 || _dom==2) return div.offsetTop;
  if(_dom==1)            return div.style.pixelTop;
  if(_dom==3)            return div.top;
  return 0;
}

function moveDivTo(div,left,top){
  if(_dom==4){
    div.style.left=left+'px';
    div.style.top =top +'px';
    return;
  }
  if(_dom==2 || _dom==1){
    div.style.pixelLeft=left;
    div.style.pixelTop =top;
    return;
  }
  if(_dom==3){
    div.moveTo(left,top);
    return;
  }
}

function moveDivBy(div,left,top){
  if(_dom==4){
    div.style.left=div.offsetLeft+left;
    div.style.top =div.offsetTop +top;
    return;
  }
  if(_dom==2){
    div.style.pixelLeft=div.offsetLeft+left;
    div.style.pixelTop =div.offsetTop +top;
    return;
  }
  if(_dom==1){
    div.style.pixelLeft+=left;
    div.style.pixelTop +=top;
    return;
  }
  if(_dom==3){
    div.moveBy(left,top);
    return;
  }
}

function scrollExlHItTo(exdiv,x){
  if(_dom==4){
    frames[exdiv.id].scrollTo(x,frames[exdiv.id].scrollY);
    return;
  }
  if(_dom==2 || _dom==1){
    frames(exdiv.id+'_if').scrollTo(x,frames(exdiv.id+'_if').document.body.scrollTop);
    return;
  }
  if(_dom==3){
    var dx=x-exdiv.clip.left, ch=exdiv.clip.width;
    exdiv.left-=dx;
    exdiv.clip.left=x; exdiv.clip.width=ch;
    return;
  }
  return;
}

function scrollExlVItTo(exdiv,y){
  if(_dom==4){
    frames[exdiv.id].scrollTo(frames[exdiv.id].scrollX,y);
    return;
  }
  if(_dom==2 || _dom==1){
    frames(exdiv.id+'_if').scrollTo(frames(exdiv.id+'_if').document.body.scrollLeft,y);
    return;
  }
  if(_dom==3){
    var dy=y-exdiv.clip.top, ch=exdiv.clip.height;
    exdiv.top-=dy;
    exdiv.clip.top=y; exdiv.clip.height=ch;
    return;
  }
  return;
}

function initDivSize(div){
  if(_dom==4){
    // getComputedStyle is buggy in NN6, and wrong in Mozilla 0.8/9
    //
    // var style=document.defaultView.getComputedStyle(div,null);
    // div.style.width =style.getPropertyValue('width' );
    // div.style.height=style.getPropertyValue('height');
    //
    div.style.width =div.offsetWidth +'px';
    div.style.height=div.offsetHeight+'px';
    //
    // need border-width=0px, margin-width:0px
  }
  else if(_dom==2 || _dom==1){
    div.style.pixelWidth =div.offsetWidth;
    div.style.pixelHeight=div.offsetHeight;
  }
  return div;
}

function getDivWidth (div){
  if(_dom==4 || _dom==2) return div.offsetWidth;
  if(_dom==1)            return div.style.pixelWidth;
  if(_dom==3)            return div.clip.width;
  return 0;
}

function getDivHeight(div){
  if(_dom==4 || _dom==2) return div.offsetHeight;
  if(_dom==1)            return div.style.pixelHeight;
  if(_dom==3)            return div.clip.height;
  return 0;
}

function resizeDivTo(div,width,height){
  if(_dom==4){
    div.style.width =width +'px';
    div.style.height=height+'px';
    return;
  }
  if(_dom==2 || _dom==1){
    div.style.pixelWidth =width;
    div.style.pixelHeight=height;
    return;
  }
  if(_dom==3){
    div.resizeTo(width,height);
    return;
  }
}

function resizeDivBy(div,width,height){
  if(_dom==4){
    div.style.width =(div.offsetWidth +width )+'px';
    div.style.height=(div.offsetHeight+height)+'px';
    return;
  }
  if(_dom==2){
    div.style.pixelWidth =div.offsetWidth +width;
    div.style.pixelHeight=div.offsetHeight+height;
    return;
  }
  if(_dom==1){
    div.style.pixelWidth +=width;
    div.style.pixelHeight+=height;
    return;
  }
  if(_dom==3){
    div.resizeBy(width,height);
    return;
  }
}

function getExlWidth (exdiv){
  if(_dom==4)
    // NN6 is buggy( same exdiv.offsetWidth )
    return exdiv.contentDocument.body.offsetWidth;
  if(_dom==2 || _dom==1)
    return _mac?frames(exdiv.id+'_if').document.body.offsetWidth
               :frames(exdiv.id+'_if').document.body.scrollWidth;
  if(_dom==3)
    return exdiv.document.width;
  return 0;
}

function getExlHeight(exdiv){
  if(_dom==4)
    return exdiv.contentDocument.body.offsetHeight;
  if(_dom==2 || _dom==1)
    return _mac?frames(exdiv.id+'_if').document.body.offsetHeight
               :frames(exdiv.id+'_if').document.body.scrollHeight;
  if(_dom==3)
    return exdiv.document.height;
  return 0;
}

function setDivVisibility(div,visible){
  if(_dom==4 || _dom==2 || _dom==1){
    div.style.visibility=(visible)?'inherit':'hidden';
    return;
  }
  if(_dom==3){
    div.visibility      =(visible)?'inherit':'hide';
    return;
  }
}

function setDivVisibilities(divs,visible){
  if(_dom==4 || _dom==2 || _dom==1){
    for(var i=0; i<divs.length; i++)
      divs[i].style.visibility=(visible)?'inherit':'hidden';
  }
  if(_dom==3){
    for(var i=0; i<divs.length; i++)
      divs[i].visibility      =(visible)?'inherit':'hide';
  }
  return divs;
}

function setDivClip(div,top,right,bottom,left){
  if(_dom==4 || _dom==2 || _dom==1){
    div.style.clip='rect('+top+'px '+right+'px '+bottom+'px '+left+'px)';
    return;
  }
  if(_dom==3){
    div.clip.top   =top;   div.clip.right=right;
    div.clip.bottom=bottom;div.clip.left =left;
    return;
  }
}

function writeDivHTML(div,op,cl){
  var s='';
  for(var i=3; i<arguments.length; i++) s+=arguments[i];
  if(_dom==4){
    if(op){ while(div.hasChildNodes()) div.removeChild(div.lastChild); }
    var range=document.createRange();
    range.selectNodeContents(div);
    range.collapse(true);
    var cf=range.createContextualFragment(s);
    div.appendChild(cf);
    return;
  }
  if(_dom==2 || _dom==1){
    if(op)   div.innerHTML='';
    if(_mac&&!_ie512) div.innerHTML+=s;
    else     div.insertAdjacentHTML('BeforeEnd',s);
    return;
  }
  if(_dom==3){
    if(op) div.document.open('text/html','replace');
    div.document.write(s);
    if(cl) div.document.close();
    return;
  }
}

function setDivBackgroundColor(div,color){
  if(color==null) color='transparent';
  if(_dom==3) div.bgColor=color;
  else        div.style.backgroundColor=color;
}

function setDivBackgroundImage(div,url){
  if(_dom==3) div.background.src=url?url:null;
  else        div.style.backgroundImage=url?('url('+url+')'):'none';
}

function setDivZIndex(div,order){
  if(_dom==4 || _dom==2 || _dom==1){
    div.style.zIndex=order;
    return;
  }
  if(_dom==3){
    div.zIndex      =order;
    return;
  }
}

function setDivStyleAttribute(div,nm,value){
  if(_dom!=0 && _dom!=3) eval('div.style.'+nm+'=value');
  return div;
}

function changeExlURL(exdiv,url){
  if(_dom==4){
    exdiv.setAttribute('src',url);
    return;
  }
  if(_dom==2 || _dom==1){
    frames(exdiv.id+'_if').location.replace(url);
    return;
  }
  if(_dom==3){
    exdiv.load(url,exdiv.clip.width);
    return;
  }
  return;
}

function getLeftFromEvent(e){
  if(_dom==4)          return e.clientX+window.scrollX;
  if(_dom==2||_dom==1) return document.body.scrollLeft+window.event.clientX;
  if(_dom==3)          return e.pageX;
  return 0;
}
function getTopFromEvent(e){
  if(_dom==4)          return e.clientY+window.scrollY;
  if(_dom==2||_dom==1) return document.body.scrollTop+window.event.clientY;
  if(_dom==3)          return e.pageY;
  return 0;
}
;
/* ==============================================================
   << event handler service object >>
              for Netscape Navigator 4.0
              and Internet Explorer  4.0+

   Author : Shinichi Hagiwara
   Type   : library - free software

   history:
     09/17/2000 remake for my book
     06/24/2001 support Mozilla( NN6 )

   Require JS Lib
          : LibCrossBrowser.js  - Common functions for cross browser

   Copyright(C) 2000 ShinSoft. All rights reserved.
 ================================================================ */
_grabObj = null;                  // è—L’†‚ÌƒIƒuƒWƒFƒNƒg

// ƒCƒxƒ“ƒg§ŒäƒIƒuƒWƒFƒNƒg
function EventCtrl(div){
  this.div   = div;
  this.type  = ''; this.mask  = 0;
  this.pageX = 0;  this.pageY = 0;
}

// ƒCƒxƒ“ƒg§ŒäƒIƒuƒWƒFƒNƒg‚Ì‹¤—p‰»ƒƒ\ƒbƒh
EventCtrl.prototype.linkCtrl = function(obj){
  if(obj && !obj.eventCtrl) obj.eventCtrl=this;
  return this;
}
// è‡’l‚ÌÝ’èƒƒ\ƒbƒh
EventCtrl.prototype.setThreshold = function(threshold){
  this.threshold = threshold;
  return this;
}

// —v‘f–¼‚©‚çè—L’†‚ÌƒCƒxƒ“ƒg§ŒäƒIƒuƒWƒFƒNƒg‚ð“¾‚é IE—pŠÖ”
function getCtrlFromElementIE(el,tagName){
  for(;el;el=el.parentElement)
    if((tagName==null || el.tagName==tagName) && el.eventCtrl)
      return el.eventCtrl;
  return null;
}

// ƒCƒxƒ“ƒg‚©‚çƒCƒxƒ“ƒg§ŒäƒIƒuƒWƒFƒNƒg‚ð“¾‚éŠÖ”
function getCtrlFromEventIE(e,tagName){     // IE—p
  var ctrl=_grabObj;
  var event=window.event;
  var fromCtrl, toCtrl;
  if (ctrl==null){
    var mask=0, type=event.type;
    switch(type){
    case 'mouseover':
      fromCtrl = getCtrlFromElementIE(event.fromElement,tagName);
      toCtrl   = getCtrlFromElementIE(event.toElement,  tagName);
      if(fromCtrl!=toCtrl) ctrl=toCtrl;
      if(!ctrl || (ctrl.mask&1)==0) ctrl=null;
      break;
    case 'mouseout':
      fromCtrl = getCtrlFromElementIE(event.fromElement,tagName);
      toCtrl   = getCtrlFromElementIE(event.toElement,  tagName);
      if(fromCtrl!=toCtrl) ctrl=fromCtrl;
      if(!ctrl || (ctrl.mask&1)==0) ctrl=null;
      break;
    case 'mousedown': 
    case 'mousemove': 
    case 'mouseup':
      ctrl = getCtrlFromElementIE(event.srcElement,tagName);
      if(ctrl && (ctrl.mask&2)!=0) break;
    default: ctrl=null; break;
    }
  }
  if(ctrl){
    ctrl.pageX = document.body.scrollLeft+event.clientX;
    ctrl.pageY = document.body.scrollTop +event.clientY;
    ctrl.type  = event.type;
  }
  return ctrl;
}
function getCtrlFromEventNN4(e,tagName){    // NN4—p
  var ctrl=_grabObj;
  if(ctrl==null) ctrl=e.target.eventCtrl;
  if(ctrl){
    var mask=0;
    switch(e.type){
    case 'mouseover': case 'mouseout':
      mask|=1; break;
    case 'mousedown': case 'mousemove': case 'mouseup':
      mask|=2; break;
    }
    if((ctrl.mask&mask)!=0){
      ctrl.pageX = e.pageX; ctrl.pageY = e.pageY;
      ctrl.type  = e.type;
    } else ctrl=null;
  }
  return ctrl;
}
function getCtrlFromEventMz(e,tagName){     // Mozilla—p
  var ctrl=_grabObj;
  if(ctrl==null){
    for(var t=e.target; t!=null; t=t.parentNode){
      if((  tagName==null
         ||(t.nodeType==Node.ELEMENT_NODE && t.tagName==tagName))
         && ('undefined' != typeof(t.eventCtrl)) ){
        ctrl=t.eventCtrl;
        break;
      }
    }
  }
  if(ctrl){
    ctrl.pageX = e.clientX+window.scrollX;
    ctrl.pageY = e.clientY+window.scrollY;
    ctrl.type  = e.type;
  }
  return ctrl;
}
function getCtrlFromEventNop(e,tagName){ return null; } // Dummy
getCtrlFromEvent=(_dom==1||_dom==2)?getCtrlFromEventIE:
                   (_dom==3?getCtrlFromEventNN4:
                    (_dom==4?getCtrlFromEventMz:
                     getCtrlFromEventNop));

// mouseover ƒnƒ“ƒhƒ‰
function ech_mouseover(e){
  var ctrl = getCtrlFromEvent(e,null);
  if(ctrl && ctrl.mouseover && !ctrl.mouseoverState){
    ctrl.mouseoverState = true;
    if(ctrl.mouseover) ctrl.mouseover(ctrl,ctrl.mouseoverClient);
  }
}

// mouseout ƒnƒ“ƒhƒ‰
function ech_mouseout(e){
  var ctrl = getCtrlFromEvent(e,null);
  if(ctrl && ctrl.mouseover && ctrl.mouseoverState){
    ctrl.mouseoverState = false;
    if(ctrl.mouseout) ctrl.mouseout(ctrl,ctrl.mouseoutClient);
  }
}

// mousedown ƒnƒ“ƒhƒ‰
function ech_mousedown(e){
  var ctrl = getCtrlFromEvent(e,null);
  if(ctrl && !ctrl.dragging){
    _grabObj = ctrl; ctrl.dragging=true; ctrl.dragged = false;
    ctrl.startX = ctrl.curX = ctrl.pageX;
    ctrl.startY = ctrl.curY = ctrl.pageY;
    if(ctrl.mousedown) ctrl.mousedown(ctrl,ctrl.mousedownClient);
    return false;
  }
  return true;
}

// mousemove ƒnƒ“ƒhƒ‰
function ech_mousemove(e){
  var ctrl = getCtrlFromEvent(e,null);
  if(ctrl && ctrl.dragging){
    if(ctrl.curX!=ctrl.pageX || ctrl.curY!=ctrl.pageY){
      if(Math.abs(ctrl.pageX-ctrl.startX)>ctrl.threshold || Math.abs(ctrl.pageY-ctrl.startY)>ctrl.threshold)
        ctrl.dragged = true;
      if(ctrl.mousemove) ctrl.mousemove(ctrl,ctrl.mousemoveClient);
      ctrl.curX = ctrl.pageX; ctrl.curY = ctrl.pageY;
    }
    return false;
  }
  return true;
}

// mouseup ƒnƒ“ƒhƒ‰
function ech_mouseup(e){
  var ctrl = getCtrlFromEvent(e,null);
  if(ctrl && ctrl.dragging){
    _grabObj = null; ctrl.dragging = false;
    if(ctrl.mouseup) ctrl.mouseup(ctrl,ctrl.mouseupClient);
    if(!ctrl.dragged && ctrl.mouseclick)
      ctrl.mouseclick(ctrl,ctrl.mouseclickClient);
    ctrl.curX = ctrl.pageX; ctrl.curY = ctrl.pageY;
    return false;
  }
  return true;
}

/**
* Set the drag object and the methods to call on the events 
*  - mouseover
*  - mouseout
* The method you pass should expect to get 2 params 
*  a) A ctrl-object holding all event info
*  b) A pass-through parameter that *you* may set.
*  
* @param div   is the object you intend to move (a div-object)
* @param ovrf  function to call on the onmousedown event 
* @param ovrc  pass-through parameter that you *may* set
* @param outf  function to call on the onmousemove event
* @param outc  pass-through parameter that you *may* set
*/
function ech_attachMouseOverOut(div,ovrf,ovrc,outf,outc){
  if(!div.eventCtrl) div.eventCtrl = new EventCtrl(div);
  var ctrl = div.eventCtrl;
  ctrl.mouseoverState = false;
  ctrl.mouseover  = ovrf; ctrl.mouseoverClient = ovrc;
  ctrl.mouseout   = outf; ctrl.mouseoutClient  = outc;
  div.onmouseover = ech_mouseover;
  div.onmouseout  = ech_mouseout;
  ctrl.mask|=1;
  return ctrl;
}

// mouseover/mouseout ƒnƒ“ƒhƒ‰“o˜^íœŠÖ”
function ech_detachMouseOverOut(div){
  var ctrl = div.eventCtrl;
  if(ctrl){
    ctrl.div.onmouseover = null;
    ctrl.div.onmouseout  = null;
    ctrl.mask=~1;
  }
}

/**
* Set the drag object and the methods to call on the events 
*  - onmousedown
*  - onmousemove
*  - onmouseup
*  - onmouseclick
* The method you pass should expect to get 2 params 
*  a) A ctrl-object holding all event info
*  b) A pass-through parameter that *you* may set.
*  
* @param div   is the object you intend to move (a div-object)
* @param dwnf  function to call on the onmousedown event 
* @param dwnc  pass-through parameter that you *may* set
* @param movf  function to call on the onmousemove event
* @param movc  pass-through parameter that you *may* set
* @param upf   function to call on the onmouseup event
* @param upc   pass-through parameter that you *may* set
* @param clkf  function to call on the mouseclick event
* @param clkc  pass-through parameter that you *may* set
*/
function ech_attachMouseDrag(div,dwnf,dwnc,movf,movc,upf,upc,clkf,clkc){
  var doc;
  
  if(_dom==1||_dom==2){
    doc = div;
    doc.onmousedown      = ech_mousedown;
    document.onmousemove = ech_mousemove;
    document.onmouseup   = ech_mouseup;
  } else if(_dom==3){
    doc = div.document;
    doc.onmousedown = ech_mousedown;
    doc.onmousemove = ech_mousemove;
    doc.onmouseup   = ech_mouseup;
    doc.captureEvents(Event.MOUSEDOWN|Event.MOUSEMOVE|Event.MOUSEUP);
  } else if(_dom==4){
    doc = div;
    div.onmousedown           = ech_mousedown;
    document.body.onmousemove = ech_mousemove;
    document.body.onmouseup   = ech_mouseup;
  } else return null;
  if(!doc.eventCtrl) doc.eventCtrl = new EventCtrl(div);
  var ctrl=doc.eventCtrl;
  ctrl.dragging  = false; ctrl.dragged   = false;
  ctrl.startX    = 0;     ctrl.startY    = 0;
  ctrl.curX      = 0;     ctrl.curY      = 0;
  ctrl.mousedown = dwnf; ctrl.mousedownClient = dwnc;
  ctrl.mousemove = movf; ctrl.mousemoveClient = movc;
  ctrl.mouseup   = upf;  ctrl.mouseupClient   = upc;
  ctrl.mouseclick= clkf; ctrl.mouseclickClient= clkc;
  ctrl.threshold = 5;
  ctrl.mask|=2;
  return ctrl;
}

// ƒhƒ‰ƒbƒOƒnƒ“ƒhƒ‰“o˜^íœŠÖ”
function ech_detachMouseDrag(div){
  var ctrl = null;
  if(_dom==1||_dom==2){
    ctrl=div.eventCtrl;
    if(ctrl) ctrl.div.onmousedown=null;
  } else if(_dom==3){
    ctrl = div.document.eventCtrl;
    if(ctrl){
      var doc = ctrl.div.document;
      doc.releaseEvents(Event.MOUSEDOWN|Event.MOUSEMOVE|Event.MOUSEUP);
      doc.onmousedown = null;
      doc.onmousemove = null;
      doc.onmouseup   = null;
    }
  } else if(_dom==4){
    ctrl = div.eventCtrl;
    if(ctrl) ctrl.div.onmousedown=null;
  }
  if(ctrl) ctrl.mask&=~2;
}
;
// The global array of objects that have been instanciated
if (!Bs_Objects) {var Bs_Objects = [];};


/**
* A Slider Component.
* 
* <b>Features:</b> 
* - IE6 and NS(Mozilla7) compliant.
* - Lets you add a slider to your page. It simulates a HTML-form text field; so your form-handling will not change.
* - You may use your customized images.
* - Able to attach onClick- and onChange-events to execute your JS-code when checked/changed.
* 
* <b>Includes (+Dependencies):</b>
* <code>
*   <script type="text/javascript" src="/_bsJavascript/lib/LibCrossBrowser.js"></script>
*   <script type="text/javascript" src="/_bsJavascript/lib/EventHandler.js"></script>
*   <script type="text/javascript" src="/_bsJavascript/core/form/Bs_FormUtil.lib.js"></script>
*   <script type="text/javascript" src="/_bsJavascript/components/slider/Bs_Slider.class.js"></script>
* </code>
* 
* <b>How to use:</b>
* 1. Have a look at the example (see example link below)
* 2. Create a function in the HTML-header called init(). Place the javascript code 
*    that instanciates and inits this component into init().
* 3. Place an 'onLoad' in your body-tag: e.g. <body onLoad="init();">
* 4. In the HTML body: Place a div- or span-tag with an unique ID where you want the component to be.
* 
* <b>How it works:</b>
* - [After instanciating and initializing the object]. Call the drawInto([tag id]) method.
*   This will search the HTML code for a tag with the given id and insert HTML- and JS- code
*   dynamically (using DOM) to display the component and handle it.
* 
* <b>What is returned to the server:</b>
*<pre>
*  +------------------------+------------------------------------------------+
*  | [tag id] +"_value"     | int, The slider value                          |
*  +------------------------+------------------------------------------------+
* In versions 4.4 and before  
*  +--------------------------------------------+----------------------------+
*  | [varible name of the object] +"_value"     | int, The slider value      |
*  +--------------------------------------------+----------------------------+
*</pre>
*  This class generates a normal HTML text field and saves it's state in there.
*  It's not visible because it is set to display:none (invisible) but (when used in a form),
*  it will be submitted like any other HTML-form-field. To override this name see {@link fieldname}.
* 
* <b>Event-Handling</b>: (see {@link attachOnClick()}, {@link attachOnChange()})
* - You can a callback function for certain events onto this component
*   (events are things like onClick, onChange ... aso) 
* 
* Snippet 1) Attaching a callback function:
* <code>
*     var mySlider = new Bs_Slider();
*     mySlider.attachOnChange(yourCallbackFunctionName);
* </code>
* The function you pass should be able to receive 3 parameters.
* - The componentObj is an instance of this class and allows you to access it the 
*   component that triggered the event.
* - newValue is the new value that was set, new position is the new position in pixels.
* <code>
*     function yourCallbackFunctionName(componentObj, newValue, newPosition) {
*       // do some stuff.
*     }
*     if you're using the 2-knob slider then there is a 4th param: knobNumber.
* </code>
* 
* <b>Customized images:</b>
* - Set the path to your image-dir {@link imgDir}
* - Then use following methods setup the colorbar and to place the images you intend to use:
* {@link colorbar} 
* {@link setBackgroundImage()} 
* {@link setSliderIcon()}
* {@link setArrowIconLeft()}, {@link setArrowIconRight()}
* 
* @example example1.html
* @example example2.html
* 
* @author     andrej arn <andrej-at-blueshoes-dot-org>, sam blum <sam-at-blueshoes-dot-org>
* @package    javascript_components
* @subpackage slider
* @copyright  blueshoes.org
*/
function Bs_Slider(theFieldnamePrefix) {
  
	/**
  * Unique Object/Tag ID is initialized in the constuctor.
  * Based on this._id. Can be used in genarated JS-code as ID. Is set together 
  * from the  classname + this._id (see _constructor() code ).
  *
  * @access private
  * @var  string 
  */
  this._objectId;
	
  /**
  * When submitting the form, you'll receive the value under this name.
	* In other words you'll receive the data back to the server as if you had placed <br>
  * <code><input type=text name="[the fieldName]" id="[the fieldName]"  value="[the value]"></code><br>
	* into your HTML-form.
  *
  * Note:
  * - If not set the field name will be genarated as instanceName +"_value"  
  * 
	* @access public
	* @var    string
	*/
	this.fieldName;
	this.fieldName2;
	
	/**
	* If the whole slider is disabled or not.
	* @access private
	* @var    bool
	* @see    setDisabled()
	*/
	this._disabled = false;	
	
	/**
	* The slider direction (horizontal/vertical)
  *<pre>
	*   0 = horizontally (default)
	*   1 = vertically (currently not implemented)
  *</pre>
	* @access public
	* @var    int direction
	* @todo   implement vertically
	*/
  this.direction       = 0;
	
	/**
	* The width of the sliding part in pixel.
  * Note: This is not the full width. It excludes the input field and the push buttons.
	* @access public
	* @var    int (default is 100 pixel)
	*/
  this.width           = 100;
	
	/**
	* The height of the sliding part in pixel. 
	* This is not the full height. it excludes the input field and the push buttons.
	* @access public
	* @var    int (default is 20 pixel)
	*/
  this.height          = 20;
	
	/**
	* The lowest possible value. It may be lower than 0 afaik :-)
	* @access public
	* @var    int (default is 0)
	*/
  this.minVal          = 0;
	
	/**
	* The highest possible value.
	* @access public
	* @var    int  (default is 100)
	*/
  this.maxVal          = 100;
	
	/**
	* The default value (when the slider gets initialized).
	* Note:
  * - Can initially have alower or higher value than minVal/maxVal.
  *   This is a feature. You can detect if the used has set any value this way.
  *   Only  values in the range of minVal - maxVal can be set and are displayed.
	* @access public
	* @var    int 
	*/
  this.valueDefault      = 0;
	
	/**
	* How much units to slide on an arrow click. 
	* If set to 0 then the arrows won't be displayed.
	* Something like 0.5 is possible as well.
	* @access public
	* @var    int  (default is 1)
	* @see    this.wheelAmount
	*/
  this.arrowAmount     = 1;
	
	/**
	* if activated then a mouseover is already enough for the arrow to fire. it then 
	* does not need a click. it continues to fire until onmouseout.
	* @access public
	* @var    bool arrowMouseOver
	* @since  bs-4.6
	* @see    var this.arrowKeepFiringTimeout
	*/
	this.arrowMouseOver = false;
	
	/**
	* every this milliseconds the onChangeByArrow() events keep firing.
	* set to 0 if you don't want that.
	* @access public
	* @var    int arrowKeepFiringTimeout
	*/
	this.arrowKeepFiringTimeout = 10;
	
	/**
	* @access private
	* @var    bool _stopFireArrowFlag
	* @see    this.stopFireArrow()
	*/
	this._stopFireArrowFlag = false;
  
	/**
	* how much to scroll when the mouse wheel is used.
	* note: the mouse wheel is supported by ie only (as of 2004/03). 
	* @access public
	* @var    int wheelAmount
	* @see    this.arrowAmount
	* @since  bs-4.6
	*/
	this.wheelAmount = 5;
	
	
  this.colorbar;
  this.colorbar2;
  
	/**
	* The z-index the slider will use. you may want to change this if you have 
	* elements on your page that overlap this slider (floating stuff or so).
	* @access public
	* @var int  (default is 1000)
	*/
  this.baseZindex      = 1000;
	
	/**
	* If you want to move the whole slider object with everything on the x-axis 
	* then set a value here. 
	* - example: -5 means move the whole thing  5 pixel to the left.
	* - example: 10 means move the whole thing 10 pixel to the right.
	* @access public
	* @var    int 
	* @see    moveY
	* @since  bs4.3
	*/
	this.moveX = 0;
	
	/**
	* If you want to move the whole slider object with everything on the y-axis 
	* then set a value here. 
	* - example: -5 means move the whole thing  5 pixel up the page.
	* - example: 10 means move the whole thing 10 pixel down the page.
	* @access public
	* @var    int 
	* @see    moveX
	* @since  bs4.3
	*/
	this.moveY = 0;
  
	/**
	* The base path for the image folder.
  * @deprecated use imgDir
  * @access private
  */
  this.imgBasePath;

	/**
	* The base path for the image folder.
	* 
	* Examples: (NOTE: The path has to end with a slash.)
  * - 'http://www.domain.com/foo/'  <= with domain
	* - '/my/image/path/'             <= absolute path without domain
	* - '../some/path/'               <= relative path
	* 
	* 
	* Default is: '/_bsJavascript/components/slider/img/'
	* Check this folder and the other folders around there for other styles.
	* 
	* @access public
	* @var    string
	*/
  this.imgDir  = '/_bsJavascript/components/slider/img/';
	
	/**
	* The name of the background image in the imgDir.
	* Set this using setBackgroundImage(), so look there.
	* @access private
	* @var    string 
	* @see    setBackgroundImage()
	*/
  this._bgImgSrc;
		
	/**
	* How a background-image should be repeated. it's a css property.
	* - example: 'no-repeat'
	* set this using setBackgroundImage(), so look there.
	* @access private
	* @var    string 
	* @see    setBackgroundImage()
	*/
  this._bgImgRepeat;
  
	/**
	* Additional css style string for the background image.
	* set this using setBackgroundImage(), so look there.
	* @access private
	* @var    string 
	* @see    setBackgroundImage()
	*/
	this._bgImgCssStyle;
	
	
	/**
	* @access private
	* @var    string 
	* @see    setBackgroundImageLeft()
	*/
  this._bgImgLeftSrc;
	
	/**
	* @access private
	* @var    int 
	* @see    setBackgroundImageLeft()
	*/
  this._bgImgLeftWidth;
	
	/**
	* @access private
	* @var    int 
	* @see    setBackgroundImageLeft()
	*/
  this._bgImgLeftHeight;
	
	/**
	* @access private
	* @var    string 
	* @see    setBackgroundImageRight()
	*/
  this._bgImgRightSrc;
	
	/**
	* @access private
	* @var    int 
	* @see    setBackgroundImageRight()
	*/
  this._bgImgRightWidth;
	
	/**
	* @access private
	* @var    int 
	* @see    setBackgroundImageRight()
	*/
  this._bgImgRightHeight;
	
	
	/**
	* The slider handle image name. (knob)
	* Set this using setSliderIcon().
	* @access private 
	* @var    int 
	* @see    setSliderIcon(), _sliderImgWidth, _sliderImgHeight
	*/
  this._sliderImgSrc;
	
	/**
	* The width of the slider handle image.
	* Set this using setSliderIcon().
	* @access private
	* @var    int 
	* @see    setSliderIcon(), _sliderImgSrc, _sliderImgHeight
	*/
  this._sliderImgWidth;
	
	/**
	* The height of the slider handle image.
	* Set this using setSliderIcon().
	* @access private
	* @var    int _sliderImgHeight
	* @see    setSliderIcon(), _sliderImgSrc, _sliderImgWidth
	*/
  this._sliderImgHeight;
    
	/**
	* Used to set a CSS class name for the slider container.
	* @access public
	* @var    string
	*/
  this.styleContainerClass;
	
	/**
	* Used to set a CSS class name for the value input field.
	* @access public
	* @var    string 
	*/
  this.styleValueFieldClass  = 'smalltxt spanSliderField';
  this.styleValueFieldClass2 = 'smalltxt spanSliderField';
	
	/**
	* Used to set a CSS class name for the value text span.
	* @access public
	* @var    string 
	*/
  this.styleValueTextClass  = 'smalltxt spanSliderText';
  this.styleValueTextClass2 = 'smalltxt spanSliderText';
  
	/**
	* The background color. hex code or named color.
	* examples: 'blue', 'green', '#000000'
	* @access public
	* @var    string 
	*/
  this.bgColor;	
	
	/**
	* The name of the left arrow icon.
	* @access private
	* @var    string 
	* @see    setArrowIconLeft()
	*/
  this._arrowIconLeftSrc;
  
	/**
	* The width of the left arrow icon.
	* @access private
	* @var    string  
	* @see    setArrowIconLeft()
	*/
  this._arrowIconLeftWidth   = 0;
  
	/**
	* The height of the left arrow icon.
	* @access private
	* @var    string  
	* @see    setArrowIconLeft()
	*/
  this._arrowIconLeftHeight  = 0;
  
	/**
	* A CSS style string to use in the image tag.
	* @access private
	* @var    string arrowIconLeftCssStyle
	* @see    setArrowIconLeft()
	* @todo   all
	*/
  this._arrowIconLeftCssStyle  = 0;

	/**
	* The name of the right arrow icon.
	* @access private
	* @var    string
	* @see    setArrowIconRight()
	*/
  this._arrowIconRightSrc;
  
	/**
	* The width of the right arrow icon.
	* @access private
	* @var    int 
	* @see    setArrowIconRight()
	*/
  this._arrowIconRightWidth  = 0;
  
	/**
	* The height of the right arrow icon.
	* @access private
	* @var    int 
	* @see    setArrowIconRight()
	*/
  this._arrowIconRightHeight = 0;
    
	/**
	* A CSS style string to use in the image tag.
	* @access private
	* @var    string
	* @see    setArrowIconRight()
	* @todo   all
	*/
  this._arrowIconRightCssStyle  = 0;
	
  /**
  * The step (interval) of the values. 
  * <pre>
  * Examples: 0, 1, 2, 3 ...     has an interval of 1
  *           0, 0.5, 1, 1.5 ... has an interval of 0.5
  * </pre>
  * 
  * @access public
  * @var    number  (int or real, whatever)
  */
  this.valueInterval   = 1;
  this.valueInterval2  = 1;
  
  /**
  * Should we display the input field (with value) to the right? 
  * 
  * <pre>
  * 0 = no
  * 1 = show as text (not implemented yet, will be shown as #2)
  * 2 = show as input field (changable). this is the default.
  * 3 = show as text, onmouseover becomes an input field. 
  * </pre>
  * 
  * The trick is to keep it invisible if set to false. we need it because it's 
  * the holder of the internal value. could be recoded, if you want to...
  * 
  * @access public
  * @var int useInputField
  * @see inputTextFieldEvent
  */
  this.useInputField  = 2;
  this.useInputField2 = 2;
  




  /**
  * If {@link useInputField} is set to 3 we toggle. but when?
  * default is onMouseOver (over) but it can be set to 'click' 
  * (onClick). 
  * @access public
  * @var    string ('over' or 'click')
  * @see    useInputField
  */
  this.inputTextFieldEvent = 'over';
  
	
	/**
	* if a second knob should be used.
	* default is false.
	* @access public
	* @since  bs-4.6
	* @status experimental
	*/
	this.useSecondKnob;
	/**
	* if the 2nd value can be lower than the 1st, and vice versa.
	* per default value crossing is blocked.
	* @access public
	* @since  bs-4.6
	* @status experimental
	* @see    useSecondKnob
	*/
	this.preventValueCrossing;
	
  /**
	* ?
  * @access private
	*/
  this.ctrl;
  this.ctrl2;
  
  /**
  * The real value we have. 
  * in the beginning it will be set to this.valueDefault.
  * <b>WARNING:</b> 
  * - don't mix this._valueInternal and this.valueInterval. 
  *   it's not only that one is private and the other is not, 
  *   it's that one is the internal value, the other is the STEP.
  *   maybe step would have been a better name. got that?
  * @access private
  * @var    double 
  * @see    getValue()
  */
  this._valueInternal;
	this._valueInternal2;
	
  /**
  * How the slider should be seen in the browser
  * @access private
  * @var    int
  * @see    setDisplay()
  */
  this._display         = 2;
	
  /**#@+
  * Ids and objects
  * @access private
  */
	
  this._arrowLeftContainerId;
  this._arrowLeftContainerObj;
  this._arrowLeftIconId;
  this._arrowLeftIconObj;
  
  this._arrowRightContainerId;
  this._arrowRightContainerObj;
  this._arrowRightIconId;
  this._arrowRightIconObj;
	
  this._valueContainerId;
	this._valueContainerObj;

  this._handleId;
  this._handleObj;
  this._valueFieldId;
  this._valueFieldObj;
  this._valueFieldObj2;
  this._valueTextId;
  this._valueTextObj;
  this._valueTextObj2;
  this._slideBarId;
  this._slideBarObj;
  this._colorbarId;
  this._colorbarObj;
  this._colorbarObj2;
  /**#@-*/
  
  /**#@+
  * positions and measurements in pixels
  * @access private
  */
  this._posUpperLeftX;
  this._posUpperLeftY;
  this._posSlideStart;
  this._posSlideEnd;
  /**#@-*/
  
  /**
  * That's this.width - this._sliderImgWidth. Slide area without the handle.
  * If you don't get this, draw a slider yourself. maybe you'll 
  * figure it out then. :-)
  * @access private
  * @var int
  */
  this._slideWidth;
  
  
  //attached (assigned) event functions (that exist in the global scope):
  
  /**
  * Array holding all the information about attached events. 
  * The structure can be like these:
  * <pre>
  * 1. attach a function directly
  *    syntax:  _attachedEvents['eventName'] = yourFunctionName;
  * 2. attach some javascript code
  *    syntax:  _attachedEvents['eventName'] = "yourCode();";
  *    example: _attachedEvents['eventName'] = "alert('hi'); callSomething('foo');";
  *    just keep in mind that you cannot use vars in that code, because when it 
  *    gets executed that will be another scope (unless the vars are global...)
  * 3. attach multiple things for the same event
  *    syntax:  _attachedEvents['eventName']    = new Array;
  *             _attachedEvents['eventName'][0] = yourFunctionName;
  *             _attachedEvents['eventName'][1] = "yourCode();";
  *    possible values for 'eventName' are:
  *     'onChange'
  * </pre>
  * 
  * @access private
  * @var    array  (hash, see above)
  * @see    attachEvent();
  */
  this._attachedEvents;
  
  /**
  * Fires whenever the value changes. that can happen by sliding, 
  * hitting arrow buttons or typing in values into the input field.
  * @access private
  * @var function
  * @see attachOnChange()
  */
  this.eventOnChange;
  
  /**#@+
  * Attached function for the slide start,  move and end event.
  * @access private
  * @var function  
  */
  this.slideStartCB;
  this.slideMoveCB;
  this.slideEndCB;
  /**#@-*/
  
	/**
	* the pseudo constructor.

	* @access private
	* @return void
	*/
	this._constructor = function(theFieldnamePrefix) {
  	// Put this instance into the global object instance list
    this._id = Bs_Objects.length;
    Bs_Objects[this._id] = this; 
    this._objectId = "Bs_Slider_"+this._id;
    // For copatibillity we still init "objectName"
    this.objectName = this._objectId;
    // In V4.4 the fieldname used to be given by the constuctor-parameter. So if
    // a paramter is passed in the constructor, we still use it as fieldname prefix
    if (typeof(theFieldnamePrefix) == 'string') {
      this.fieldName  = theFieldnamePrefix + '_value';  
      this.fieldName2 = theFieldnamePrefix + '2_value';  
      this.objectName = theFieldnamePrefix;
    }
  }
  
  /**
  * Makes sure everything is ready to use. sets some default values if needed.
	* @access private
	* @return void
  */
  this._checkup = function() {
    if (typeof(this.minVal)     == 'undefined') this.minVal     = 0;
    if (typeof(this.maxVal)     == 'undefined') this.maxVal     = 10;
    if (typeof(this.valueDefault) == 'undefined') this.valueDefault = this.minVal;
    this._valueInternal = this.valueDefault;
		
		if (this.useSecondKnob) {
	    if (typeof(this.minVal2)     == 'undefined') this.minVal2     = 0;
	    if (typeof(this.maxVal2)     == 'undefined') this.maxVal2     = 10;
	    if (typeof(this.valueDefault2) == 'undefined') this.valueDefault2 = this.maxVal2;
	    this._valueInternal2 = this.valueDefault2;
    }
		
    // This is for backward compatabillity only --sam 2003-06
    if (typeof(this.imgBasePath) == 'string')  this.imgDir = this.imgBasePath;
  }
  

	
	
	/**
	* Render function.
	* @access public
	* @param  string tagId (ID of the element in that we render the slider.)
	* @return void
	*/
  this.render = function(tagId) {
    this._checkup();
    
    this._containerId           = 'co'   + tagId;
    this._handleId              = 'po'   + tagId;
    this._arrowLeftContainerId  = 'alc'  + tagId;
    this._arrowLeftIconId       = 'ali'  + tagId;
    this._arrowRightContainerId = 'arc'  + tagId;
    this._arrowRightIconId      = 'ari'  + tagId;
    this._valueContainerId      = 'vc'   + tagId;
    this._valueFieldId          = 'vf'   + tagId;
		if (typeof(this.fieldName)  == 'undefined') this.fieldName  = tagId + '_value';
		if (typeof(this.fieldName2) == 'undefined') this.fieldName2 = tagId + '2_value';
    this._valueTextId           = 'vt'   + tagId;
    this._slideBarId            = 'bar'  + tagId;
    this._colorbarId            = 'cb'   + tagId;
    
    var divWidth      = this.width; // + this._sliderImgWidth;
    var divHeight     = this.height;
    //var completeWidth = this.width + this._arrowIconLeftWidth + this._arrowIconRightWidth + this._sliderImgWidth +15; //15 just to add some space.
    
    var out         = new Array();
    var outI        = 0;
    var localOffset = 0;
    
    //container begin
    out[outI++] = '<div id="' + this._containerId + '"';
    if (this.styleContainerClass) {
      out[outI++] = ' class="' + this.styleContainerClass + '"';
    }
    out[outI++] = ' style="position:relative;';
    if (this._display == 0) {
      out[outI++] = ' display:none;';
    } else if (this._display == 1) {
      out[outI++] = ' visibility:hidden;';
    }
    out[outI++] = ' onmousewheel="Bs_Objects['+this._id+'].onMouseWheel(); return false;"';
    out[outI++] = '">';
    
		out[outI++] = '<div';
    out[outI++] = ' onmousewheel="Bs_Objects['+this._id+'].onMouseWheel(); return false;"';
		out[outI++] = ' style="position:absolute; left:' + this.moveX + 'px; top:' + this.moveY + 'px;">';
		
		if (this.useSecondKnob) {
			out[outI++] = this._renderInputFieldAndText(localOffset, 1);
			if (this['useInputField'] != 0) {
				localOffset += 35;
			}
		}
		
		//knob
    out[outI++] = '<div style="position:absolute; display:none; z-index:' + (this.baseZindex + 10) + ';" id="' + this._handleId     + '">';
    out[outI++] = '<img name="poImg' + tagId + '" src="' + this.imgDir + this._sliderImgSrc + '" border=0 width=' + this._sliderImgWidth + ' height=' + this._sliderImgHeight + '>';
    out[outI++] = '</div>';
    
		//knob 2
		if (this.useSecondKnob) {
				 
	    out[outI++] = '<div style="position:absolute; display:none; z-index:' + (this.baseZindex + 9) + ';" id="' + this._handleId     + '2">';
  	  out[outI++] = '<img name="poImg' + tagId + '2" src="' + this.imgDir + this._sliderImgSrc2 + '" border=0 width=' + this._sliderImgWidth2 + ' height=' + this._sliderImgHeight2 + '>';
    	out[outI++] = '</div>';
		}
    
    //arrow left
    if ((this.arrowAmount > 0) && this._arrowIconLeftSrc) {
		
      out[outI++] = '<div id="' + this._arrowLeftContainerId + '" style="position:absolute; left:' + localOffset + 'px; top:0;">';
			out[outI++] = '<a href="javascript:void(false);"';
			if (this.arrowMouseOver) {
				out[outI++] = ' onMouseOver="Bs_Objects['+this._id+'].onChangeByArrow(false, true); return false;"';
				out[outI++] = ' onMouseOut="Bs_Objects['+this._id+'].stopFireArrow(); return false;"';
			} else {
				//old code:
				//out[outI++] = ' onClick="Bs_Objects['+this._id+'].onChangeByArrow(false); return false;"';
				//new code:
				out[outI++] = ' onMouseDown="Bs_Objects['+this._id+'].onChangeByArrow(false, true); return false;"';
				out[outI++] = ' onMouseUp="Bs_Objects['+this._id+'].stopFireArrow(); return false;"';
				out[outI++] = ' onMouseOut="Bs_Objects['+this._id+'].stopFireArrow(); return false;"';
			}
			out[outI++] = '>';
			out[outI++] = '<img id="' + this._arrowLeftIconId + '" src="' + this.imgDir + this._arrowIconLeftSrc + '" border="0" width="' + this._arrowIconLeftWidth + '" height="' + this._arrowIconLeftHeight + '"';
			if (typeof(this.arrowIconLeftCssStyle) != 'undefined') {
				out[outI++] = ' style="' + this.arrowIconLeftCssStyle + '"';
			}
			out[outI++] = '>';
			out[outI++] = '</a></div>';
      localOffset += this._arrowIconLeftWidth;
    }
    
		//left background image
		if (typeof(this._bgImgLeftSrc) != 'undefined') {
			var tmpLeft = (this.direction == 0) ? localOffset : 0;
			var tmpTop  = (this.direction == 0) ? 0           : localOffset;
			out[outI++] = '<div style="position:absolute; left:' + tmpLeft+ 'px; top:' + tmpTop + 'px;">';
			out[outI++] = '<img src="' + this.imgDir + this._bgImgLeftSrc + '" width="' + this._bgImgLeftWidth + '" height="' + this._bgImgLeftHeight + '" border="0">';
			out[outI++] = '</div>';
			localOffset += (this.direction == 0) ? this._bgImgLeftWidth : this._bgImgLeftHeight;
		}
		
    //colorbar
    if (this.colorbar) {
      out[outI++] = '<div id="' + this._colorbarId + '" onClick="Bs_Objects['+this._id+'].onChangeByClick(event);"';
      if (this.colorbar['cssClass']) {
        out[outI++] = ' class="' + this.colorbar['cssClass'] + '"';
      }
      out[outI++] = ' style="position:absolute; z-index:' + (this.baseZindex +5) + '; width:0;';
      if ('undefined' != typeof(this.colorbar['color'])) {
        out[outI++] = ' background-color:' + this.colorbar['color'] + ';';
      } else if ('undefined' == typeof(this.colorbar['cssClass'])) {
        out[outI++] = ' background-color:orange;';
      }
      if ('undefined' != typeof(this.colorbar['offsetLeft'])) {
        out[outI++] = ' left:' + (localOffset + this.colorbar['offsetLeft']) + 'px;';
      }
      if ('undefined' != typeof(this.colorbar['offsetTop'])) {
        out[outI++] = ' top:' + this.colorbar['offsetTop'] + 'px;';
      }
      if ('undefined' != typeof(this.colorbar['height'])) {
        out[outI++] = ' height:' + this.colorbar['height'] + 'px;';
      }
      out[outI++] = '">';
      //out[outI++] = '<img src="/_bsImages/spacer.gif" width="1" height="5"></div>';
      out[outI++] = '</div>';

    }
		if (this.colorbar2) {
      out[outI++] = '<div id="' + this._colorbarId + '2" onClick="Bs_Objects['+this._id+'].onChangeByClick(event);"';
      if (this.colorbar2['cssClass']) {
        out[outI++] = ' class="' + this.colorbar2['cssClass'] + '"';
      }
      out[outI++] = ' style="position:absolute; z-index:' + (this.baseZindex +5) + '; width:0;';
      if ('undefined' != typeof(this.colorbar2['color'])) {
        out[outI++] = ' background-color:' + this.colorbar2['color'] + ';';
      } else if ('undefined' == typeof(this.colorbar2['cssClass'])) {
        out[outI++] = ' background-color:orange;';
      }
			/*
      if ('undefined' != typeof(this.colorbar2['offsetRight'])) {
        out[outI++] = ' right:' + (localOffset + this.colorbar2['offsetRight']) + ';';
      }
			*/
      if ('undefined' != typeof(this.colorbar2['offsetLeft'])) {
        out[outI++] = ' left:' + (localOffset + this.colorbar2['offsetLeft']) + 'px;';
      }
      if ('undefined' != typeof(this.colorbar2['offsetTop'])) {
        out[outI++] = ' top:' + this.colorbar2['offsetTop'] + 'px;';
      }
      if ('undefined' != typeof(this.colorbar2['height'])) {
        out[outI++] = ' height:' + this.colorbar2['height'] + 'px;';
      }
      out[outI++] = '">';
      //out[outI++] = '<img src="/_bsImages/spacer.gif" width="1" height="5"></div>';
      out[outI++] = '</div>';

		}
    
		
    //main layer
    out[outI++] = '<div id="' + this._slideBarId + '" onClick="Bs_Objects['+this._id+'].onChangeByClick(event);"';
		
		var tmpLeft = (this.direction == 0) ? localOffset : 0;
		var tmpTop  = (this.direction == 0) ? 0           : localOffset;
		out[outI++] = ' style="position:absolute; left:' + tmpLeft + 'px; top:' + tmpTop + 'px; width:' + divWidth + 'px; height: ' + divHeight + 'px; clip:rect(0 ' + divWidth + 'px  ' + divHeight + 'px 0);';
		
    if (this.bgColor) {
      out[outI++] = 'background-color:' + this.bgColor + '; layer-background-color:' + this.bgColor + ';';
    }
    if (this._bgImgSrc) {
      out[outI++] = ' background-image: url(' + this.imgDir + this._bgImgSrc + '); background-repeat:' + this._bgImgRepeat + ';';
    }
		if (this._bgImgCssStyle) {
	    out[outI++] = this._bgImgCssStyle;
		}
    out[outI++] = '"></div>';
		
    localOffset += (this.direction == 0) ? this.width : this.height;
    
		
		//right background image
		if (typeof(this._bgImgRightSrc) != 'undefined') {
			var tmpLeft = (this.direction == 0) ? localOffset : 0;
			var tmpTop  = (this.direction == 0) ? 0           : localOffset;
			out[outI++] = '<div style="position:absolute; left:' + tmpLeft + 'px; top:' + tmpTop + 'px;">';
			out[outI++] = '<img src="' + this.imgDir + this._bgImgRightSrc + '" width="' + this._bgImgRightWidth + '" height="' + this._bgImgRightHeight + '" border="0">';
			out[outI++] = '</div>';
			localOffset += (this.direction == 0) ? this._bgImgRightWidth : this._bgImgRightHeight;
		}
		
    //arrow right
    if ((this.arrowAmount > 0) && this._arrowIconRightSrc) {
			var tmpLeft = (this.direction == 0) ? localOffset : 0;
			var tmpTop  = (this.direction == 0) ? 0           : localOffset;
      out[outI++] = '<div id="' + this._arrowRightContainerId + '" style="position:absolute; left:' + tmpLeft + 'px; top:' + tmpTop + 'px;">';
			out[outI++] = '<a href="javascript:void(false);"';
			if (this.arrowMouseOver) {
				out[outI++] = ' onMouseOver="Bs_Objects['+this._id+'].onChangeByArrow(true, true); return false;"';
				out[outI++] = ' onMouseOut="Bs_Objects['+this._id+'].stopFireArrow(); return false;"';
			} else {
				//old:
				//out[outI++] = ' onClick="Bs_Objects['+this._id+'].onChangeByArrow(true); return false;"';
				//new:
				out[outI++] = ' onMouseDown="Bs_Objects['+this._id+'].onChangeByArrow(true, true); return false;"';
				out[outI++] = ' onMouseUp="Bs_Objects['+this._id+'].stopFireArrow(); return false;"';
				out[outI++] = ' onMouseOut="Bs_Objects['+this._id+'].stopFireArrow(); return false;"';
			}
			out[outI++] = '>';
			out[outI++] = '<img id="' + this._arrowRightIconId + '" src="' + this.imgDir + this._arrowIconRightSrc + '" border="0" width="' + this._arrowIconRightWidth + '" height="' + this._arrowIconRightHeight + '"';
			if (typeof(this.arrowIconRightCssStyle) != 'undefined') {
				out[outI++] = ' style="' + this.arrowIconRightCssStyle + '"';
			}
			out[outI++] = '>';
			out[outI++] = '</a></div>';
      localOffset += this._arrowIconRightWidth;
    }
    
    //input field and text
		if (this.useSecondKnob) {
			out[outI++] = this._renderInputFieldAndText(localOffset, 2);
		} else {
			out[outI++] = this._renderInputFieldAndText(localOffset, 1);
		}
		
		out[outI++] = '</div>';
    
    //container end
    out[outI++] = '</div>';
    
    document.getElementById(tagId).innerHTML = out.join('');
		
    this._containerObj           = document.getElementById(this._containerId);
    this._arrowLeftContainerObj  = document.getElementById(this._arrowLeftContainerId);
    this._arrowLeftIconObj       = document.getElementById(this._arrowLeftIconId);
    this._arrowRightContainerObj = document.getElementById(this._arrowRightContainerId);
    this._arrowRightIconObj      = document.getElementById(this._arrowRightIconId);
    this._slideBarObj            = document.getElementById(this._slideBarId);
		
		
		
    this._handleObj              = document.getElementById(this._handleId);
    this._valueContainerObj      = document.getElementById(this._valueContainerId);
    this._valueFieldObj          = document.getElementById(this._valueFieldId);
    this._valueTextObj           = document.getElementById(this._valueTextId);
    this._colorbarObj            = document.getElementById(this._colorbarId);
		
    this._posSlideStart = (this.direction == 0) ? getDivLeft(this._slideBarObj) : getDivTop(this._slideBarObj);
    this._slideWidth    = (this.direction == 0) ? this.width - this._sliderImgWidth : this.height - this._sliderImgHeight;
    this._posSlideEnd   = this._posSlideStart + this._slideWidth;
    
    this._currentRelSliderPosX = this._posSlideStart;
    if (this.valueDefault > this.minVal) {
      //how many percent is valueDefault from maxVal-minVal?
      var hundertPercent = this.maxVal - this.minVal;
      var myPercent      = (this.valueDefault-this.minVal) * 100 / hundertPercent;
      //now how much is that from the given length?

      this._currentRelSliderPosX += (myPercent * this._slideWidth / 100);
    }
		if (this.direction == 0) {
	    this._handleObj.style.left = this._currentRelSliderPosX+'px';
		} else {
	    this._handleObj.style.top  = this._currentRelSliderPosX+'px';
		}
    this._handleObj.style.display = 'block';
    
    //handleObj = handlespan
    temp = ech_attachMouseDrag(this._handleObj,this.slideStart,null,this.slideMove,null,this.slideEnd,null,null,null);
    temp = temp.linkCtrl(getDivImage('', 'poImg' + tagId));
    this.ctrl           = temp;
    this.ctrl.sliderObj = this; //add back reference
		this.ctrl.knobId    = 1;
		
    var x = getDivLeft(this._handleObj);
    var y = getDivTop(this._handleObj);
    y = 0; //z3b
    
    if (this.direction == 0) {   // horizontal
      this.ctrl.minX = this._posSlideStart;
      this.ctrl.maxX = this._posSlideEnd;
      this.ctrl.minY = y;
			this.ctrl.maxY = y;
    } else {      // vertical
      this.ctrl.minX = x;
      this.ctrl.maxX = x;
      this.ctrl.minY = this._posSlideStart;
			this.ctrl.maxY = this._posSlideEnd;
    }
    
		
		
		if (this.useSecondKnob) {
	    this._handleObj2              = document.getElementById(this._handleId + '2');
	    this._valueContainerObj2      = document.getElementById(this._valueContainerId + '2');
	    this._valueFieldObj2          = document.getElementById(this._valueFieldId + '2'); //may fail if only 1 field used.
	    this._valueTextObj2           = document.getElementById(this._valueTextId + '2');
	    this._colorbarObj2            = document.getElementById(this._colorbarId + '2');
			
	    this._slideWidth2    = (this.direction == 0) ? this.width - this._sliderImgWidth2 : this.height - this._sliderImgHeight2;
	    this._posSlideEnd2   = this._posSlideStart + this._slideWidth2;
	    
	    this._currentRelSliderPosX2 = this._posSlideStart;
	    if (this.valueDefault2 > this.minVal2) {
	      //how many percent is valueDefault from maxVal-minVal?
	      var hundertPercent = this.maxVal2 - this.minVal2;
	      var myPercent      = (this.valueDefault2-this.minVal2) * 100 / hundertPercent;
	      //now how much is that from the given length?
	      this._currentRelSliderPosX2 += (myPercent * this._slideWidth2 / 100);
	    }
			if (this.direction == 0) {
		    this._handleObj2.style.left = this._currentRelSliderPosX2+'px';
			} else {
		    this._handleObj2.style.top  = this._currentRelSliderPosX2+'px';
			}
	    this._handleObj2.style.display = 'block';
	    
	    //handleObj = handlespan
	    temp2 = ech_attachMouseDrag(this._handleObj2,this.slideStart,null,this.slideMove,null,this.slideEnd,null,null,null);
	    temp2 = temp2.linkCtrl(getDivImage('', 'poImg' + tagId + '2'));
	    this.ctrl2           = temp2;
	    this.ctrl2.sliderObj = this; //add back reference
			this.ctrl2.knobId    = 2;
			
	    var x = getDivLeft(this._handleObj2);
	    var y = getDivTop(this._handleObj2);
	    y = 0; //z3b
	    
	    if (this.direction == 0) {   // horizontal
	      this.ctrl2.minX = this._posSlideStart;
	      this.ctrl2.maxX = this._posSlideEnd2;
	      this.ctrl2.minY = y;
				this.ctrl2.maxY = y;
	    } else {      // vertical
	      this.ctrl2.minX = x;
	      this.ctrl2.maxX = x;
	      this.ctrl2.minY = this._posSlideStart;
				this.ctrl2.maxY = this._posSlideEnd2;
	    }
			
		}
		
    this._updateColorbar(this._currentRelSliderPosX, 1);
    this._updateColorbar(this._currentRelSliderPosX2, 2);
  }
  
	
	/**
	* @access private
	* @param  ? localOffset
	* @param  int knobId (default is 1 can be 2.)
	* @return string
	*/
	this._renderInputFieldAndText = function(localOffset, knobId) {
		var k = ((typeof(knobId) == 'undefined') || (knobId == 1)) ? '' : '2';
		var out = new Array();
    var styleValueFieldClass = (this['styleValueFieldClass'+k]) ? ' class="' + this['styleValueFieldClass'+k] + '"' : '';
    var styleValueTextClass  = (this['styleValueTextClass'+k])  ? ' class="' + this['styleValueTextClass'+k]  + '"' : '';
		
		
		var cssAlign = (this.useSecondKnob && (knobId == 1)) ? 'align:right;' : '';
		
		//if (this['useInputField'+k] != 0) {
	    out[out.length] = '<div id="' + this._valueContainerId + k + '" style="position:absolute; left:' + localOffset + 'px; top:0px;">';
		//}
		
    if (this['useInputField'+k] == 1) {
      //view only
      out[out.length] = '<span' + styleValueTextClass + ' id="' + this._valueTextId + k + '">' + this['valueDefault'+k]  + '</span>';
      out[out.length] = '<input type="hidden" name="' + this['fieldName'+k] + '" id="' + this._valueFieldId + k + '" value="' + this['valueDefault'+k] + '">';
    } else if (this['useInputField'+k] == 2) {
      //edit
/*Begins - Modified by Emprise Star 2009-10-08*/	
	  var value=this['valueDefault'+k];
	  if(k=='' && value!='0'){
  		  //value='-' + value; 
		  value="<"+value; 
	  }
	  else if(k=='2'){
		  //value=value + '+' ;
		  value='>'+value ;
	  }
/*Ends - Modified by Emprise Star 2009-10-08*/	
/*      out[out.length] = '<input type="text"' + styleValueFieldClass + ' onMouseOver="bsFormFieldSetFocusAndSelect(this, false);" name="' + this['fieldName'+k] + '" id="' + this._valueFieldId + k + '" value="' + this['valueDefault'+k] + '" size="3"';
*/
	 out[out.length] = '<input type="text"' + styleValueFieldClass + ' name="' + this['fieldName'+k] + '" id="' + this._valueFieldId + k + '" value="' + value + '" size="3"';
      if (styleValueFieldClass == '') { //so it does not look *that* bad by default.
        out[out.length] = ' style="vertical-align:text-top; width:30px; height:' + this.height + 'px;"';
      }
	  
      out[out.length] = ' onKeyUp="Bs_Objects['+this._id+'].onChangeByInput(this.value, false, '+knobId+');" onBlur="Bs_Objects['+this._id+'].onChangeByInput(this.value, true, '+knobId+');">';
    } else if (this['useInputField'+k] == 3) {
      //view, start editmode on click
      out[out.length] = '<input type="text"' + styleValueFieldClass + ' onMouseOver="bsFormFieldSetFocusAndSelect(this, false);" name="' + this['fieldName'+k] + '" id="' + this._valueFieldId + k + '" value="' + this['valueDefault'+k] + '" size="3"';
      if (styleValueFieldClass == '') { //so it does not look *that* bad by default.
        out[out.length] = ' style="display:none; vertical-align:text-top; width:30px; height:' + this.height + 'px;"';
      } else {
        out[out.length] = ' style="display:none;"';
      }
      out[out.length] = ' onKeyUp="Bs_Objects['+this._id+'].onChangeByInput(this.value, false, '+knobId+');" onBlur="var _bss = Bs_Objects['+this._id+']; _bss.onChangeByInput(this.value, true, '+knobId+'); _bss.textboxEdit(false, '+knobId+')">';
      out[out.length] = '<span' + styleValueTextClass + ' style="' + cssAlign + '" id="' + this._valueTextId + k + '" ';
      if (this.inputTextFieldEvent == 'click') {
        out[out.length] = 'onClick="Bs_Objects['+this._id+'].textboxEdit(true, '+knobId+');"';
      } else {
        out[out.length] = 'onMouseOver="Bs_Objects['+this._id+'].textboxEdit(true, '+knobId+');"';
      }
      out[out.length] = '>' + this['valueDefault'+k]  + '</span>';
    } else { //0
      out[out.length] = '<input type="hidden" name="' + this['fieldName'+k] + '" id="' + this._valueFieldId + k + '" value="' + this['valueDefault'+k] + '">';
    }
		//if (this['useInputField'+k] != 0) {
	    out[out.length] = '</div>';
		//}
		return out.join('');
	}
  
	
  /**
  * Renders the checkbox component and places it into the page.
	* 
  * @access public
  * @param string tagId Id of the tag. (Use <div> or <span> to hold the ID)
	* @return void
  */
  this.drawInto = function(tagId) {
    this.render(tagId);
		if (this._disabled) this.setDisabled(true);
  }
  
  /**
  * DEPRECATED.
	* Use drawInto()
	* @deprecated use drawInto()
  * @param string tagId (id of the span tag.)
  * @see drawInto()
	* @return void
	*/
  this.draw = function(tagId) {
    this.render(tagId);
		if (this._disabled) this.setDisabled(true);    
  }

  /**
  * Attaches an event like onChange, onMouseOver, onClickCaption ... a.s.o.
  * Supported events are:
  * - 'onChange'
  *
  * @access public
  * @param  string trigger (for example 'onChange')
  * @param  function A globalFunctionName (No string)
  * @return void
  * @see    _attachedEvents
  */
  this.attachEvent = function(trigger, yourEvent) {
    if (typeof(this._attachedEvents) == 'undefined') {
      this._attachedEvents = new Array();
    }
    
    if (typeof(this._attachedEvents[trigger]) == 'undefined') {
      this._attachedEvents[trigger] = new Array(yourEvent);
    } else {
      this._attachedEvents[trigger][this._attachedEvents[trigger].length] = yourEvent;
    }
  }
  
  /**
  * Tells if an event is attached for the trigger specified. 
  * @access public
  * @param  string trigger
  * @return bool
  */
  this.hasEventAttached = function(trigger) {
    return (this._attachedEvents && this._attachedEvents[trigger]);
  }
  
  /**
  * Fires the events for the trigger specified.
  * (used internally, but feel free to trigger events yourself...)
  * @access public
  * @param  string trigger (for example 'onClickCaption')
  * @return void
  */
  this.fireEvent = function(trigger) {
    if (this._attachedEvents && this._attachedEvents[trigger]) {
      var e = this._attachedEvents[trigger];
      if ((typeof(e) == 'string') || (typeof(e) == 'function')) {
        e = new Array(e);
      }
      for (var i=0; i<e.length; i++) {
        if (typeof(e[i]) == 'function') {
          e[i](this);
        } else if (typeof(e[i]) == 'string') {
          eval(e[i]);
        } //else murphy
      }
    }
  }
  
  
  /**#@+
  * Attache a global JS-fuction that will be called.
  * @access public
  * @param  function functionName (not a string!)
  */
  this.attachOnChange = function(functionName) {
    this.eventOnChange = functionName;
  }

  this.attachOnSlideStart = function(functionName) {
    this.slideStartCB = functionName;
  }
  this.attachOnSlideMove = function(functionName) {
    this.slideMoveCB = functionName;
  }
  this.attachOnSlideEnd = function(functionName) {
    this.slideEndCB = functionName;
  }
  /**#@-*/
    
  /**#@+
  * Attache a global JS-fuction that will be called.
  * @access public
  * @param  function func (not a string!)
  */
  this.attachOnArrow = function(functionName) {
    this.eventOnArrow = functionName;
  }
  this.attachOnInputChange = function(functionName) {
    this.eventOnInputChange = functionName;
  }
  this.attachOnInputBlur = function(functionName) {
    this.eventOnInputBlur = functionName;
  }
  /**#@-*/
  
	
  /**
  * Sets the knob icon to be used by the slider.
  * @access public
  * @param  string imgName (on path)
  * @param  int  width if image in pixel
  * @param  int  height if image in pixel
  * @see imgDir
  * @return void
  */
  this.setSliderIcon = function(imgName, width, height) {
    this._sliderImgSrc    = imgName;
    this._sliderImgWidth  = width;
    this._sliderImgHeight = height;
  }
  this.setSliderIcon2 = function(imgName, width, height) {
    this._sliderImgSrc2    = imgName;
    this._sliderImgWidth2  = width;
    this._sliderImgHeight2 = height;
  }
  
	/**
	* sets the arrow icon left/top (depending on direction horizontal/vertical).
	* @access public
	* @param  string imgName
	* @param  int width
	* @param  int height
	* @return void
	*/
  this.setArrowIconLeft = function(imgName, width, height) {
    this._arrowIconLeftSrc    = imgName;
    this._arrowIconLeftWidth  = width;
    this._arrowIconLeftHeight = height;
  }
	
	/**
	* sets the arrow icon right/bottom (depending on direction horizontal/vertical).
	* @access public
	* @param  string imgName
	* @param  int width
	* @param  int height
	* @return void
	*/
  this.setArrowIconRight = function(imgName, width, height) {
    this._arrowIconRightSrc    = imgName;
    this._arrowIconRightWidth  = width;
    this._arrowIconRightHeight = height;
  }
  
  /**
  * Sets a background image.
	* 
	* possible values for the repeat css property: 
	*   repeat    => the background image repeats on both axis
	*   repeat-x  => the bg image repeats on the x-axis only. 
	*   repeat-y  => the bg image repeats on the y-axis only.
	*   no-repeat => the bg image does not repeat; it only shows once.
	* 
  * @access public
  * @param  string src
  * @param  string repeat (read above)
	* @param  string cssStyle (additional css style string, eg "left:4px;" to indent 4px from the left. since bs-4.6)
  * @return void
	* @see    setBackgroundImageLeft(), setBackgroundImageRight()
  */
  this.setBackgroundImage = function(src, repeat, cssStyle) {
    this._bgImgSrc        = src;
    this._bgImgRepeat     = repeat;
		this._bgImgCssStyle   = cssStyle;
  }
	
  /**
  * Sets a background image to use on the left side. see the examples.
  * @access public
	* @param  string imgName
	* @param  int width
	* @param  int height
  * @return void
	* @see    setBackgroundImage(), setBackgroundImageRight()
  */
  this.setBackgroundImageLeft = function(imgName, width, height) {
    this._bgImgLeftSrc    = imgName;
    this._bgImgLeftWidth  = width;
    this._bgImgLeftHeight = height;
  }
	
  /**
  * Sets a background image to use on the right side. see the examples.
  * @access public
	* @param  string imgName
	* @param  int width
	* @param  int height
  * @return void
	* @see    setBackgroundImage(), setBackgroundImageLeft()
  */
  this.setBackgroundImageRight = function(imgName, width, height) {
    this._bgImgRightSrc    = imgName;
    this._bgImgRightWidth  = width;
    this._bgImgRightHeight = height;
  }
	
  
  /**
  * How the slider should be seen in the browser. 
  * <pre>
  *   (rtfm about css)
  *   0 = display:none
  *   1 = visibility:hidden
  *   2 = display:block
  * </pre>
  * 
  * @access public
  * @param  int display
  * @see    _display
  */
  this.setDisplay = function(display) {
    this._display = display;
    if (this._containerObj) {
      switch (display) {
        case 0:
          this._containerObj.style.display = 'none';
          break;
        case 1:
          this._containerObj.style.visibility = 'hidden';
          break;
        case 2:
          //we need to activate both
          this._containerObj.style.visibility = 'visible';
          this._containerObj.style.display = 'block';
          break;
        default: 
          //user set an invalid value.
      }
    }
  }
  /**
	* Disables (or re-enables) the whole slider.
	* 
	* if the param b is not specified, the current disabled mode will be toggled (inverted).
	* 
	* @access public
	* @param  bool b (true=disabled, false=enabled, not set or null = toggle current state.)
	* @return void
	* @since  bs4.4
	*/
	this.setDisabled = function(b) {
		if (typeof(b) == 'undefined') b = !this._disabled;
		
		if (b) {
			//be aware that the filters don't work on all elements, in all cases. there's not much i can do.
			//it once didn't work in a div, but then it worked in a table at the same place.
			//now it does not work on a span. well... not a killer feature.
			var filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayScale=1); progid:DXImageTransform.Microsoft.BasicImage(opacity=.5)';
			var cursor = 'default';
		} else {
			var filter = null;
			var cursor = 'hand'; //moz == pointer
		}
		
		var t = new Array(
			this._containerId, this._arrowLeftContainerId, this._arrowRightContainerId, 
			this._valueFieldId, this._valueTextId, 
			this._slideBarId, this._colorbarId, this._handleId, 
			this._valueFieldId + '2', 
			this._valueTextId + '2', 
			this._colorbarId + '2', 
			this._handleId + '2'
		); //this._valueContainerId, 
		
		for (var i=0; i<t.length; i++) {
			var elm = document.getElementById(t[i]);
			if (elm != null) elm.style.filter = filter;
		}
		var elm = document.getElementById(this._arrowLeftIconId);
		if (elm != null) elm.style.cursor = cursor;
		
		var elm = document.getElementById(this._arrowRightIconId);
		if (elm != null) elm.style.cursor = cursor;
		
		var elm = document.getElementById(this._valueFieldId);
		if (elm != null) elm.disabled = b;
		
		this._disabled = b;
	}
  
  /**
  * Returns the current silder value.
  * @access public
	* @param  int knobId (default is 1 can be 2.)
  * @return double
	* @see    getValueInPercent()
  */
  this.getValue = function(knobId) {
		if ((typeof(knobId) == 'undefined') || (knobId == 1)) {
	    return this._valueInternal;
		} else {
	    return this._valueInternal2;
		}
  }
  
	/**
	* returns the current slider value in percent (compared to min/max value).
	* @access public
	* @param  int knobId (default is 1 can be 2.)
	* @return double (0 - 100)
	* @see    getValue()
	* @since  bs-4.6
	*/
	this.getValueInPercent = function(knobId) {
		//thanks to Carl Meisner <carlmeis@hotmail.com> for a bugfix 2005-06-29 --andrej
		if ((typeof(knobId) == 'undefined') || (knobId == 1)) {
			var range   = Math.abs(this.maxVal - this.minVal);
			var percent = Math.abs(this._valueInternal - this.minVal) / range * 100;
			return percent;
		} else {
			var range   = Math.abs(this.maxVal2 - this.minVal2);
			var percent = Math.abs(this._valueInternal2 - this.minVal2) / range * 100;
			return percent;
		}
	}
	
	
  /**
  * Returns the current slider relative position in pixel.
  * @access public
	* @param  int knobId (default is 1, can be 2)
  * @return int
  */
  this.getSliderPos = function(knobId) {
		if (typeof(knobId) == 'undefined') knobId = 1;
		if (knobId == 1) {
	    var absLeng = (this.direction==0) ? getDivLeft(this.ctrl.div) - this.ctrl.minX : getDivTop(this.ctrl.div) - this.ctrl.minY;
  	  var absRang = this.maxVal - this.minVal;
	    //alert("975: absLeng:" +absLeng+"  absRang:"+absRang+"  _slideWidth:"+this._slideWidth);
  	  return (absLeng * absRang/this._slideWidth) + this.minVal;
		} else {
	    var absLeng = (this.direction==0) ? getDivLeft(this.ctrl2.div) - this.ctrl2.minX : getDivTop(this.ctrl2.div) - this.ctrl2.minY;
  	  var absRang = this.maxVal2 - this.minVal2;
  	  return (absLeng * absRang/this._slideWidth) + this.minVal2;
		}
  }
	
  
  /**
  * Fires when the user slides.
  * @access private
	* @param  ? ctrl
  */
  this.onChangeBySlide = function(ctrl) {
	
    if (this._disabled) return;
    var newPos   = this._getNewLocationFromCursor(ctrl);
    var valByPos = this._getValueByPosition(newPos);
    var val      = this._roundToGrid(valByPos, ctrl.knobId);
		var valInternal = (ctrl.knobId == 1) ? this._valueInternal : this._valueInternal2;
			if (this['_valueFieldObj'] && this['_valueFieldObj2']) {

		  var left=this['_valueFieldObj'].value*1;
		  var right=this['_valueFieldObj2'].value*1;
		  if(left==right){
			  val=right-1;

		  }
	}
    if (val != valInternal) {
			newPos = this._getPositionByValue(val, ctrl.knobId); //fix it so it is nicely rounded and not over the edges (needed). 2006-07-24 --andrej
      if (ctrl.knobId == 1) {
				this._valueInternal = val;
			} else {
				this._valueInternal2 = val;
			}
      this.updateHandle(newPos, ctrl.knobId);	  
	  this.updateValueField(val, ctrl.knobId);
	  this.updateValueText(val, ctrl.knobId);
      this._updateColorbar(newPos, ctrl.knobId);
	  
      if ('undefined' != typeof(this.eventOnChange)) {
				if (this.useSecondKnob) {
					this.eventOnChange(this, val, newPos, ctrl.knobId);
				} else {
					this.eventOnChange(this, val, newPos);
				}
			}
      this.fireEvent('onChange');
    }
  }
  
  /**
  * If a browser does not support that way of changing the slider value, 
  * nothing gets done.
  * @access public
  * @param  object event (the event object)
  * @return void
  */
  this.onChangeByClick = function(event) {
    if (this._disabled) return;
    var newPos = 0;
    if ('undefined' != typeof(event.offsetX)) {
      newPos = (this.direction == 0) ? event.offsetX + this._posSlideStart : event.offsetY + this._posSlideStart;
    } else if ('undefined' != typeof(event.layerX)) {
      newPos = (this.direction == 0) ? event.layerX + this._posSlideStart  : event.layerY  + this._posSlideStart;
    } else {
      return; //not supported.
    }
    
    var val = this._getValueByPosition(newPos);
		
		if (this.useSecondKnob) {
			// this.preventValueCrossing
			if (val > this._valueInternal2) {
				var knobId = 2;
			} else if (val < this._valueInternal) {
				var knobId = 1;
			} else {
				//clicked somewhere in between.
				//cancel it for now.
				//we could see which is closer, but i doubt it would be more user-friendly.
				return;
			}
		} else {
			var knobId = 1;
		}
		
    val = this._roundToGrid(val, knobId);
		
    if (val != this._valueInternal) {
			newPos = this._getPositionByValue(val, knobId); //fix it so it is nicely rounded and not over the edges (needed). 2006-07-24 --andrej
      if (knobId == 1) {
				this._valueInternal = val;
			} else {
				this._valueInternal2 = val;
			}
      this.updateHandle(newPos, knobId);
      this.updateValueField(val, knobId);
      this.updateValueText(val, knobId);
      this._updateColorbar(newPos, knobId);
      if ('undefined' != typeof(this.eventOnChange)) {
				if (this.useSecondKnob) {
					this.eventOnChange(this, val, newPos, knobId);
				} else {
					this.eventOnChange(this, val, newPos);
				}
			}
      this.fireEvent('onChange');
    }
  }
  
  /**
  * Fires when the user inputs a new value into the input field.
  * @access public
  * @param  string val (new value)
  * @param  bool isBlur (if it's a onChange event set to false, on an onBlur event set to true.)
	* @param  int knobId (the default is 1 can also be 2.)
  * @return void
  */
  this.onChangeByInput = function(val, isBlur, knobId) {
		var k = ((typeof(knobId) == 'undefined') || (knobId == 1)) ? '' : '2';
    var gt = ">";
    if (this._disabled) return;
     if( val.charCodeAt('0') == gt.charCodeAt('0')  ) return;	
    if (val == '') {
      val = this['minVal'+k];
    }

    val = this._roundToGrid(val, knobId);
    var newPos = this._getPositionByValue(val, knobId);
    if (val != this['_valueInternal'+k]) {
      this['_valueInternal'+k] = val;
      this.updateHandle(newPos, knobId);
      this._updateColorbar(newPos, knobId);
      if ('undefined' != typeof(this.eventOnChange)) {
				if (this.useSecondKnob) {
					this.eventOnChange(this, val, newPos, knobId);
				} else {
					this.eventOnChange(this, val, newPos);
				}
			}
      this.fireEvent('onChange');
      if (isBlur) { //the user may still be typing. don't fuck his typing until he left the field.
        this.updateValueField(val, knobId);
        this.updateValueText(val, knobId);
      }
    } else if (isBlur) {
      //it's possible that the field val is "" (empty) and now the user left that field.
      //we it is still empty, we got the blur event, and need to update the field/text values:
      this.updateValueField(val, knobId);
      this.updateValueText(val, knobId);
    }
  }
  
  /**
  * @access public
  * @param  bool leftOrRight (false=left, true=right. as with politics. :)
	* @param  bool keepFiring  (if true then it sets a timeout to fire again, until this cycle is exited using stopFireArrow().)
	* @param  bool loopCall    (used internally only on calls from setTimeout().)
  */
  this.onChangeByArrow = function(leftOrRight, keepFiring, loopCall) {
		if (!loopCall) this._stopFireArrowFlag = false;
		
		if (this._stopFireArrowFlag) return;
    if (this._disabled) return;
		
    var val = parseFloat(this._valueInternal);
    if (leftOrRight) {
      val += this.arrowAmount; //right arrow
    } else {
      val -= this.arrowAmount; //left arrow
    }
    val = this._roundToGrid(val);
    if (val != this._valueInternal) {
      this._valueInternal = val;
      var newPos = this._getPositionByValue(val);
      this.updateHandle(newPos);
      this.updateValueField(val);
      this.updateValueText(val);
      this._updateColorbar(newPos);
      if ('undefined' != typeof(this.eventOnChange)) {
				if (this.useSecondKnob) {
					this.eventOnChange(this, val, newPos, 1);
				} else {
					this.eventOnChange(this, val, newPos);
				}
			}
      this.fireEvent('onChange');
    }
		//document.getElementById('debug').innerHTML = val + '<br>' + document.getElementById('debug').innerHTML;
		
		if (keepFiring) {
			if (!this._stopFireArrowFlag && (this.arrowKeepFiringTimeout > 0)) {
				setTimeout('Bs_Objects[' + this._id + '].onChangeByArrow(' + leftOrRight + ', ' + keepFiring + ', true);', this.arrowKeepFiringTimeout);
			}
		}
  }
  
	
	/**
	* is called when the mouse wheel is used over the slider.
	* @access public (used internally, you don't need that)
	* @return void
	*/
	this.onMouseWheel = function() {
    if (this._disabled) return;
		
    var val = parseFloat(this._valueInternal);

    if (event.wheelDelta > 0) {
      val -= this.wheelAmount;
    } else {
      val += this.wheelAmount;
    }
    val = this._roundToGrid(val);
    if (val != this._valueInternal) {
      this._valueInternal = val;
      var newPos = this._getPositionByValue(val);
      this.updateHandle(newPos);
      this.updateValueField(val);
      this.updateValueText(val);
      this._updateColorbar(newPos);
      if ('undefined' != typeof(this.eventOnChange)) {
				if (this.useSecondKnob) {
					this.eventOnChange(this, val, newPos, 1);
				} else {
					this.eventOnChange(this, val, newPos);
				}
			}
      this.fireEvent('onChange');
    }
	}
	
	
	/**
	* stops a loop of firing onChangeByArrow().
	* @access public
	* @return void
	* @since  bs-4.6
	*/
	this.stopFireArrow = function() {
		this._stopFireArrowFlag = true;
	}
	
  /**  
  * Sets a new value. even if the slider is disabled. this is allowed since it's an api method.
  * @access public
  * @param  string val (new value)
	* @param  int knobId (default is 1 can be 2.)
  * @return void
  */
  this.setValue = function(val, knobId) {
		if (typeof(knobId) == 'undefined') knobId = 1;
    val = this._roundToGrid(val, knobId);
    var newPos = this._getPositionByValue(val, knobId);
		var valInternal = (knobId == 1) ? this._valueInternal : this._valueInternal2;
    if (val != valInternal) {
      if (knobId == 1) {
				this._valueInternal = val;
			} else {
				this._valueInternal2 = val;
			}
      this.updateHandle(newPos, knobId);
      this._updateColorbar(newPos, knobId);
      if ('undefined' != typeof(this.eventOnChange)) {
				if (this.useSecondKnob) {
					this.eventOnChange(this, val, newPos, knobId);
				} else {
					this.eventOnChange(this, val, newPos);
				}
			}
      this.fireEvent('onChange');
      this.updateValueField(val, knobId);
      this.updateValueText(val, knobId);
    }
  }
	
  /**
	* DEPRECATED use setValue(), this method name was confusing.
	* 
  * Use this to set a new value.
	* 
  * --sam the name is confusing, it's a set-function
	* --andrej: yes, true. I have added setValue().
	* 
  * Note: The value you set is left "as is", thus it is *not* rounded to the next grid.
  *       "Grid rounding" will occur on change (see onChangeByArrow, onChangeByInput, ...). 
  * @access public
  * @param  string val (new value)
	* @param  int knobId (default is 1 can be 2)
  * @return void
	* @depreacted use setValue()
  */
  this.onChangeByApi = function(val, knobId) {
		this.setValue(val, knobId);
  }
	
  
  /**
  * Updates the colorbar visually.
  * @access private
  * @param  int newPos (at least i think it's an int.)
	* @param  int knobId (default is 1 can be 2.)
  * @return void
  */
  this._updateColorbar = function(newPos, knobId) {
	 
		var k = ((typeof(knobId) == 'undefined') || (knobId == 1) || ((typeof(this.colorbar) != 'undefined') && ((typeof(this.colorbar.type) != 'undefined') || (this.colorbar.type == 'between')))) ? '' : '2';
    if (this['_colorbarObj'+k]) {
			if ((typeof(this.colorbar.type) != 'undefined') && (this.colorbar.type == 'between')) {
				var left  = this._getPositionByValue(this._valueInternal,  1);
				var right = this._getPositionByValue(this._valueInternal2, 2);
	      this['_colorbarObj'+k].style.left  = left + this.colorbar.offsetLeft+'px';
	      this['_colorbarObj'+k].style.width = right - left+'px';
			} else {
	      var newWidth = newPos + this['colorbar'+k]['widthDifference'];
	      if (newWidth < 0) newWidth = 0;
				if (k == '2') {
					var invertedWidth = this.width - newWidth;
					if (invertedWidth < 0) invertedWidth = 0;
		      this['_colorbarObj'+k].style.width = invertedWidth+'px';
					if (typeof(this.colorbar2['offsetLeft']) != 'undefined') newWidth += this.colorbar2['offsetLeft'];
		      this['_colorbarObj'+k].style.left  = newWidth+'px';
		      this['_colorbarObj'+k].style.right = 0;
				} else {
		      this['_colorbarObj'+k].style.width = newWidth+'px';
				}
			}
			
			if (typeof(this['colorbar'+k]['color2']) != 'undefined') {
				//fading feature used.
				var percent  = this.getValueInPercent(knobId);
				var newColor = mixColor(this['colorbar'+k]['color'], this['colorbar'+k]['color2'], percent);
				document.getElementById(this._colorbarId+k).style.backgroundColor = newColor;
			}
    }
  }
  
  /**
  * Calculates the value based on the given position.
  * @access private
  * @param  int pos
  * @return double
  */
  this._getValueByPosition = function(pos) {
		if (this.direction == 0) {
	    pos -= this.ctrl.minX;
  	  var hundertPercent = this.ctrl.maxX - this.ctrl.minX;
		} else {
	    pos -= this.ctrl.minY;
  	  var hundertPercent = this.ctrl.maxY - this.ctrl.minY;
		}
    var myPercent      = pos / hundertPercent;
    var val            = this.minVal + ((this.maxVal - this.minVal) * myPercent);
    return val;
  }
  
  /**
  * Calculates the position based on the given value.
  * @access private
  * @param  double val
	* @param  int knobId (default is 1 can be 2.)
  * @return int
  */
  this._getPositionByValue = function(val, knobId) {
		var k = ((typeof(knobId) == 'undefined') || (knobId == 1)) ? '' : '2';
		
    val = val - this['minVal'+k]; //since 4.3, needed. was buggy before if minVal was not 0.
    var hundertPercent = this['maxVal'+k] - this['minVal'+k];
    var myPercent      = val / hundertPercent;
		if (this.direction == 0) {
	    var pos = this['ctrl'+k].minX + ((this['ctrl'+k].maxX - this['ctrl'+k].minX) * myPercent);
			if (pos < this['ctrl'+k].minX) {
				pos = this['ctrl'+k].minX;
			} else if (pos > this['ctrl'+k].maxX) {
				pos = this['ctrl'+k].maxX;
			}
		} else {
	    var pos = this['ctrl'+k].minY + ((this['ctrl'+k].maxY - this['ctrl'+k].minY) * myPercent);
			if (pos < this['ctrl'+k].minY) {
				pos = this['ctrl'+k].minY;
			} else if (pos > this['ctrl'+k].maxY) {
				pos = this['ctrl'+k].maxY;
			}
		}
		
    return pos;
  }
  
  /**
  * Parse and round value to next grid defined by this.valueInterval, 
	* and check lower/upper bounds.
  * @access private
  * @param  string val
	* @param  int knobId (default is 1 can be 2.)
  * @return float
  */
  this._roundToGrid = function(val, knobId) {

    val = parseFloat(val);
    if (isNaN(val)) return this.minVal;
    
    val = Math.round(val / this.valueInterval) * this.valueInterval;
    // Js has some odd rounding problems somewhere at 10^-8. To get rid of it we do: 
    val = Math.round(val*10000)/10000;
    
    //check upper/lower bounds
    if (val < this.minVal) val = this.minVal;
    if (val > this.maxVal) val = this.maxVal;
		
		if (this.useSecondKnob && this.preventValueCrossing) {
			if ((typeof(knobId) == 'undefined') || (knobId == 1)) {
				if (val >= this._valueInternal2) {
					val = this._valueInternal2 - this.valueInterval;
			    if (val < this.minVal) val = this.minVal;
				}
			} else {
				if (val <= this._valueInternal) {
					val = this._valueInternal + this.valueInterval2;
			    if (val > this.maxVal2) val = this.maxVal2;
				}
			}
		}
		
    return val;
  }
  
  /**
  * Returns the new handle pos.
  * @access private
	* @param  ? ctrl
  * @return int
  */
  this._getNewLocationFromCursor = function(ctrl) {
		/*
    var ox = this._posEventSlideStartX;
    var oy = this._posEventSlideStartY;
    switch (this.direction) {
      case 0: // horizontal
        var t = this.ctrl.pageX - ox;
        var x = parseInt(this._posObjSlideStartX) + t;
        if (x > this.ctrl.maxX) x = this.ctrl.maxX;
        if (x < this.ctrl.minX) x = this.ctrl.minX;
        return x;
      case 1: // vertical
        var t = this.ctrl.pageY - oy;
        var y = parseInt(this._posObjSlideStartY) + t;
        if (y > this.ctrl.maxY) y = this.ctrl.maxY;
        if (y < this.ctrl.minY) y = this.ctrl.minY;
        return y;
    }
		*/
		if (ctrl.knobId == 1) {
  	  var ox = this._posEventSlideStartX;
	    var oy = this._posEventSlideStartY;
			var posObjSlideStartX = this._posObjSlideStartX;
			var posObjSlideStartY = this._posObjSlideStartY;
		} else {
  	  var ox = this._posEventSlideStartX2;
	    var oy = this._posEventSlideStartY2;
			var posObjSlideStartX = this._posObjSlideStartX2;
			var posObjSlideStartY = this._posObjSlideStartY2;
		}
    switch (this.direction) {
      case 0: // horizontal
        var t = ctrl.pageX - ox;
        var x = parseInt(posObjSlideStartX) + t;
        if (x > ctrl.maxX) x = ctrl.maxX;
        if (x < ctrl.minX) x = ctrl.minX;
        return x;
      case 1: // vertical
        var t = ctrl.pageY - oy;
        var y = parseInt(posObjSlideStartY) + t;
        if (y > ctrl.maxY) y = ctrl.maxY;
        if (y < ctrl.minY) y = ctrl.minY;
        return y;
    }
  }
  
  /**
  * Slides, in other words "updates the handle/knob".
	* doesn't seem to be used. not used internally and is set to private.
  * @access private
  * @deprecated use updateHandle()
  * @param  int newPos
  * @return void
  */
  this.updatePointer = function(newPos) {
    this.updateHandle(newPos);
  }
  
  /**
  * Slides to new relative position, in other words "moves the handle/knob".
  * @access public
  * @param  int newPos in pixel
	* @param  int knobId (default is 1 can be 2.)
  * @return void
  */
  this.updateHandle = function(newPos, knobId) {
		if ((typeof(knobId) == 'undefined') || (knobId == 1)) {
			if (this.direction == 0) {
		    this._currentRelSliderPosX = newPos;
	  	  this.ctrl.div.style.left   = newPos+'px';
			} else {
		    this._currentRelSliderPosX = newPos;
	  	  this.ctrl.div.style.top    = newPos+'px';
			}
		} else { //2
			if (this.direction == 0) {
		    this._currentRelSliderPosX2 = newPos;

	  	  this.ctrl2.div.style.left   = newPos+'px';


			} else {
		    this._currentRelSliderPosX2 = newPos;
	  	  this.ctrl2.div.style.top    = newPos+'px';
			}
		}
    return;
  }
  
  /**
  * Updates the value of the input field.
  * @access public
  * @param  mixed val (string or number)
	* @param  int knobId (default is 1 can be 2.)
  * @return void
  * @see    updateValueText()
  */
  this.updateValueField = function(val, knobId) {
	var k = ((typeof(knobId) == 'undefined') || (knobId == 1)) ? '' : '2';
	if (this['_valueFieldObj'+k]) {
		/*Begins modified by Emprise Star 2009-10-08*/		
		if(k=='' && val==this.minVal && val!=0){
			//this['_valueFieldObj'+k].value = '-' + val;
			this['_valueFieldObj'+k].value = '<' + val;
		}
		else if(k=='2' && val==this.maxVal && val!=0){
			//this['_valueFieldObj'+k].value = val + '+';
			this['_valueFieldObj'+k].value = '>'+val;
		}
		else{
      		this['_valueFieldObj'+k].value = val;
		}
/*Ends modified by Emprise Star 2009-10-08*/		
    }
  }
  
  /**
  * Updates the value of the text box.
  * @access public
  * @param  mixed val (string or number)
	* @param  int knobId (default is 1 can be 2.)
  * @return void
  * @see    updateValueField()
  */
  this.updateValueText = function(val, knobId) {
		var k = ((typeof(knobId) == 'undefined') || (knobId == 1)) ? '' : '2';
    if (this['_valueTextObj'+k]) {
      this['_valueTextObj'+k].innerHTML = val;
    }
  }
  
  /**
  * @access private
  */
  this.arrowOnClick = function() {
  }
  
  /**
  * fires after the value has changed. fires a lot when sliding, also 
  * fires after an arrow click or input change.
  * @access private
  * @param int val (new value)
  */
  this.onChange = function(val) {
		if (this._disabled) return;
		this.setValue(val);
  }
  
  
  /**
  * DEPRECATED
  * updates the input field box and/or the text with the value.
  * @param  string val (number)
  * @access private
  * @return void
  * @deprecated
  */
  this.updateInputBox = function(val) {
		if (this._disabled) return;
    this.setValue(val);
  }
  
  
  /**
  * @access private
  * @param bool editMode
  */
  this.textboxEdit = function(editMode, knobId) {
		var k = ((typeof(knobId) == 'undefined') || (knobId == 1)) ? '' : '2';
    if (this._disabled) return;
    if (editMode) {
      if ('undefined' != typeof(this['_valueFieldObj'+k])) {
        this['_valueTextObj'+k].style.display = 'none';
        this['_valueFieldObj'+k].style.display = 'block';
        bsFormFieldSetFocusAndSelect(this['_valueFieldObj'+k], false);
      }
    } else {
      if ('undefined' != typeof(this['_valueTextObj'+k])) {
        this['_valueFieldObj'+k].style.display = 'none';
        this['_valueTextObj'+k].style.display  = 'block';
      }
    }
  }
  
  /**
  * Fires during the mouse move of the slider-handle (as long as the mouse button is hold)
  * @access private
  * @param  object ctrl The slider handle object
  * @param  object client
  */
  this.slideMove = function(ctrl, client) {
    ctrl.sliderObj.onChangeBySlide(ctrl);
  }
	
	
  /**
  * Fires on first click off the slider-handle
  * @access private
  * @param  object ctrl The slider handle object
  * @param  ? client
  */
  this.slideStart = function(ctrl, client) {
		//for some reason it happens that 'this' is not what it's supposed to be. 
		//we're not were we should. and the slider is disabled. in this case we 
		//ignore this call.
		//undone this, it renders all sliding useless. --andrej
		//if (this._disabled) return;
		//if (typeof(this._disabled) == 'undefined') return;
		
		if (ctrl.knobId == 1) {
			ctrl.sliderObj._handleObj.style.zIndex += 2;
	    ctrl.sliderObj._posEventSlideStartX = ctrl.startX;
	    ctrl.sliderObj._posEventSlideStartY = ctrl.startY;
	    ctrl.sliderObj._posObjSlideStartX   = ctrl.sliderObj._handleObj.style.left;
	    ctrl.sliderObj._posObjSlideStartY   = ctrl.sliderObj._handleObj.style.top;
    } else { //2
			ctrl.sliderObj._handleObj2.style.zIndex += 2;
	    ctrl.sliderObj._posEventSlideStartX2 = ctrl.startX;
	    ctrl.sliderObj._posEventSlideStartY2 = ctrl.startY;
	    ctrl.sliderObj._posObjSlideStartX2   = ctrl.sliderObj._handleObj2.style.left;
	    ctrl.sliderObj._posObjSlideStartY2   = ctrl.sliderObj._handleObj2.style.top;
		}
		
    var pos = ctrl.sliderObj.getSliderPos(ctrl.knobId);
    ctrl.sliderObj.setValue(pos, ctrl.knobId);
    
    if ('undefined' != typeof(ctrl.sliderObj.slideStartCB)) {
      ctrl.sliderObj.slideStartCB(ctrl.sliderObj, ctrl.sliderObj.getValue(), pos);
    }
  }
  
  
  /**
  * Fires on first release of the slider-handle.
  * @access private
  * @param  object ctrl The slider handle object
  * @param  ? client
  */
  this.slideEnd = function(ctrl, client){
		if (this._disabled) return;
		if (ctrl.knobId == 1) {
			ctrl.sliderObj._handleObj.style.zIndex -= 2;
		} else {
			ctrl.sliderObj._handleObj2.style.zIndex -= 2;
		}
    var pos = ctrl.sliderObj.getSliderPos();
    if ('undefined' != typeof(ctrl.sliderObj.slideEndCB)) {
      ctrl.sliderObj.slideEndCB(ctrl.sliderObj, ctrl.sliderObj.getValue(), pos);
    }
    return;
  }
  
  ///////////////////////////////////////////
  // constructor code
  ///////////////////////////////////////////
	this._constructor(theFieldnamePrefix); //call the constructor. needs to be at the end.
 
}

;
/*Default MAX values*/
var max_m=200000; //km
var max_p=1000000;
var from_currency='usd';
var to_currency='usd';
var url=Drupal.settings.basePath;
var yearSlider = new Bs_Slider();
var mileageSlider = new Bs_Slider();
var priceSlider = new Bs_Slider();
var viewAJAX;
//Filter
var ajaxUpdated = false;

$(document).ready(function() {
    registerAddress();
 /* $('#filter-side-bar-country .form-checkboxes input.form-checkbox').click(function () {
       var flag_id = $(this).parent().text().toLowerCase();
       flag_id = jQuery.trim(flag_id);
       if(flag_id == 'saudi arabia') {
           flag_id = 'saudi_arabia';
       }
       if (this.checked == true) {
         $('#'+flag_id).addClass('active_'+flag_id);
       }
       else {
         $('#'+flag_id).removeClass('active_'+flag_id);  
       }
  }); */
    
    $.address.change(function(e) {
        var path = Drupal.settings.basePath;
        for (var el in e.parameters) {
            if (e.parameters[el] == 'userdealerships') {
                path += 'dealerships';
            } else if (e.parameters[el] == 'tab-articles') {
                path += 'magazines';
            } else if (e.parameters[el] == 'tab-blog') {
                path += 'blogs';
            } else if (e.parameters[el] == 'tab-sell-a-car') {
                path += 'sell-a-car';
            }
        }
        if (location.pathname != path && e.value != '/') {
            //if (location.hash.substr(1).length > 0) {
            //    location.hash = '';
            //}
            location.href = path + '#' + e.value;
        }
    });
});



//Changing Mileage Unit
function mileage_select(unitMileage){
	var milage_from=$("#vfsliderDivMilage").attr('value');
	var milage_to=$("#vfsliderDivMilage2").attr('value');
	//milage_to=milage_to.replace("+","");
	milage_to=milage_to.replace(">","");

	//if(unitMileage.value=="mile" || unitMileage.value=="miles"){
	unitMileage=$("#edit-milage-units option:selected").text().toLowerCase();
	if(unitMileage=="mile" || unitMileage=="miles"){
		if (milage_from > 0) 	{ 	milage_from 	= Math.round(0.621 * milage_from);	}
		if (milage_to > 0) 		{ 	milage_to 		= Math.round(0.621 * milage_to);	}
		mileageSlider.maxVal=Math.round(0.621 * max_m);
		mileageSlider.maxVal2=Math.round(0.621 * max_m);
		//mySlider.maxDefault2=Math.round(0.621 * max_m);

	}
	else if(unitMileage=="km" || unitMileage=="kms"){
		if (milage_from > 0) 	{ 	milage_from 	= Math.round(milage_from/0.621);	}
		if (milage_to > 0) 		{ 	milage_to 		= Math.round(milage_to/0.621);	}
		mileageSlider.maxVal=max_m;	
		mileageSlider.maxVal2=max_m;	
		//mySlider.maxDefault2=max_m;	
	}
//	mileageSlider.valueInterval = mileageSlider.maxVal/;
	$("#edit-milage1").attr('value',milage_from);
	$("#edit-milage2").attr('value',milage_to);
	$("#vfsliderDivMilage").attr('value',milage_from);
	
	if((mileageSlider.maxVal2 *1)	<=	(milage_to*1)){
		milage_to=">"+milage_to;
	}
	$("#vfsliderDivMilage2").attr('value',milage_to);
	
}
//Changing Currency Unit
function currency_unit_change(unitPrice){
	from_currency=to_currency;
	//to_currency=unitPrice.value;	
	to_currency=$("#edit-price-units option:selected").text().toLowerCase();
	
	$.getJSON(url+"/?q=usd_rate/"+ to_currency, null, output_usd_rate);
	
	

}
//Rate of USD with current currency
function output_usd_rate(response){
	$("#usd_rate_wrapper").html(response.data);	
       $.getJSON(url+"/?q=convert_currency/"+ from_currency +"/" + to_currency + "/1", null, output_currency_rate);
}
//Rendering slider bar
function output_currency_rate(response){
	$("#convert_currency").html(response.data);	
	max_p = $('#edit-max-price').attr('value');
	var unitPrice=$("#edit-price-units");
	var price_from	=	$("#vfsliderDivPrice").attr('value');
	var price_to	=	$("#vfsliderDivPrice2").attr('value');
	//price_to=price_to.replace("+","");
	price_to=price_to.replace(">","");
	var rate		=	 $("#currency_rate").attr('value');
	if (price_from > 0) 	{ 	price_from 	= Math.round(rate * price_from *1);	}
	if (price_to > 0) 		{ 	price_to 	= Math.round(rate * price_to *1);		}

	if($("#edit-price-units option:selected").text().toLowerCase()=="usd"){	
		priceSlider.maxVal=max_p;
		priceSlider.maxVal2=max_p;
	}
	else{
		var usd_rate=$("#usd_rate").attr('value');
		priceSlider.maxVal=Math.round( usd_rate * max_p) * 1;	
		
		priceSlider.maxVal2=Math.round( usd_rate * max_p) * 1;	
		
	}
	
	$("#edit-price1").attr('value',price_from);
	$("#edit-price2").attr('value',price_to);
	$("#vfsliderDivPrice").attr('value',price_from);
//	$("#vfsliderDivPrice2").attr('value',price_to+"+");
	if((priceSlider.maxVal2*1)	<=	(price_to*1)){
		price_to=">"+price_to;
	}
	$("#vfsliderDivPrice2").attr('value',price_to);
	tmp=$("#vfsliderDivPrice2");
	tmp.focus();
}
/*Click on tab Cars
argument 1: tab ID
argument 1: View name and arguments of the view
eg: MeaCarsFilter/1/2/3/4/5 will call view meacar/filter/1/2/3/4/5
*/

function load_view(tab, view, params){
    if (typeof(params) == 'undefined') {
        params = '';
    }

    if( view != 'MeaCarsFilter') {
        params += "&mine=1";
    }
    view= 'MeaCarsFilter';

    var response=new Object();
    response.data='<p class="center"><img src="'+Drupal.settings.basePath+'sites/all/themes/meacar/images/AnimatedCarLoadingStatus.gif" alt=""/></p>';
    output_find_now(response);

    var url = Drupal.settings.basePath + "load_view/" + view + find_now_url() + params;
    if( viewAJAX != undefined ){
        viewAJAX.abort();
    }
    viewAJAX =  $.getJSON(url, null, output_find_now);
    var li = $(".menu-tabs UL LI");

    for(i=0;i<li.length;i++){
        $("#"+li[i].id).removeClass("active");
        $("#"+li[i].id+" A").removeClass("active");
    }
    $("#"+tab).addClass("active");
    $("#"+tab+" A").addClass("active");

    return false;
}
/*Submit Find now*/
/*Convert an array to string  separated by plus (+)*/
function checkboxes_to_param(checkboxes){
	var str='';
       var all =true;
	if(checkboxes.length>0){
		for(i=0;i<checkboxes.length;i++){
			if(checkboxes[i].checked){
				
				var value=checkboxes[i].value;
				if(value=="-1" || value=="0" || value==0){
					value="";
				}
				str  = str + (str.length==0 ? value : '+' + value);
				
			}
                     else{all = false;}
		}
	}
	
	if(str.length==0) str='all';
	//if( all) str='all';
	return str;
	
}

/*
$link = $base_url . '?q='.(empty($language->prefix) ? '' : $language->prefix.'/') .'meacars/filter/' . $countriesArg .'/' 	.$companiesArg.'/'.$transmissionArg.'/'.$listingArg.'/'. $display_photos_only.'/'.$vehicleTypeArg.'/';
$link.=$milage_units.'/'.$currency.'/'.$form_state['values']['price1'].'/'.$form_state['values']['price2'];

	$link .= '&mileage[min]=' . (empty($milage_from) ? "0" : $milage_from). '&mileage[max]=' . (empty($milage_to) ? "0":$milage_to); //Mikage
	$link .= '&price[min]=' . (empty($minPrice) ? "0" : $minPrice) . '&price[max]=' . (empty($maxPrice) ? "0" : $maxPrice);			//Price
	$link .= '&year[min]=' . $year_from . '&year[max]='.$year_to;			//Year
	drupal_goto($link);
*/
function find_now_url() {
	var url= 'u';
	//var url=Drupal.settings.basePath+"?q=meacars/filter";
	/*Country*/
	var countries=$("#filter-side-bar-country INPUT[type='checkbox']");
	url  =url + "/" + checkboxes_to_param(countries);
    //alert(url);

	/*companies-make*/
	var companies=$("#filter-side-bar-make INPUT[type='checkbox']");
	url  =url + "/" + checkboxes_to_param(companies);
//alert(checkboxes_to_param(companies));
	
	/*Transmission*/
	var transmission=$(".container-transmission INPUT[type='radio']");
	url  =url + "/" + checkboxes_to_param(transmission);

	
	/*Listing*/
	var listing=$(".listing-checkboxes INPUT[type='checkbox']");
	url  =url + "/" + checkboxes_to_param(listing);
	
	/*Dealerships*/
	var dealerships=$(".container-dealerships INPUT[type='checkbox']");
	url  =url + "/" + checkboxes_to_param(dealerships);
	
	
	/*Display photo only*/	
	var photo_only=$("#edit-display-photos-only");
	//alert(photo_only.attr("checked"))
	if(photo_only.attr("checked"))  url  =url + "/yes";
	else url  =url + "/all";
	
	/*Category-vehicleType*/
	var category=$("#filter-side-bar-category INPUT[type='checkbox']");
	url  =url + "/" + checkboxes_to_param(category);
	
	/*Mileage*/	
	var munit=$("#edit-milage-units").val();
	var mmin=$("#edit-milage1").val();
	var mmax=$("#edit-milage2").val();
	
	var unitMileage=$("#edit-milage-units option:selected").text().toLowerCase();
	if(munit	==	"-1" ){
		mmin 	= Math.round(mmin*1) / 1.6;
		mmax	= Math.round(mmax*1) / 1.6;
		//mySlider.maxDefault2=max_m;	
	}
	
	if(mileageSlider.maxVal2==$("#edit-milage2").val()){
		mmax="";
	}
	//if(mmax==mileage_max) mmax='max';
//	url  =url + "/" + munit + "/" + mmin + "/" + mmax ;
	url  =url + "&mileage[min]=" + mmin + "&mileage[max]=" + mmax ;
	
	/*Currency*/	

	var cunit=$("#edit-price-units").val();
	
	var cmin=$("#edit-price1").val();
	var cmax=$("#edit-price2").val();
	if(priceSlider.maxVal2==$("#edit-price2").val()){
		cmax="";
	}
	if($("#edit-price-units option:selected").text().toLowerCase()!="usd"){	
		var usd_rate=$("#usd_rate").attr('value');
		if(cmin !="" && cmin>0)	cmin=  Math.round(cmin / usd_rate) * 1;
		if(cmax !="" && cmax>0)	cmax=  Math.round(cmax / usd_rate) *1 ;
		if(cmax==max_p) cmax="";
	}	
	//if(cmax==currency_max) cmax='max';
	//url  =url + "/" + cunit + "/" + cmin + "/" + cmax ;
	url  =url + "&price[min]=" + cmin + "&price[max]=" + cmax ;
	
	/*Year*/
	
	var ymin=$("#edit-year1").val();
	if(yearSlider.minVal==$("#edit-year1").val()){
		ymin="";
	}
	var ymax=$("#edit-year2").val();
	if(yearSlider.maxVal2==$("#edit-year2").val()){
		//ymax="";
	}
	//if(ymax==year_max) ymax='max';
	//url  =url +  "/" + ymin + "/" + ymax ;
	url  =url +  "&year[min]=" + ymin + "&year[max]=" + ymax ;
	//alert(url);
	//url		=url+"&popup=true";
	//document.write(url);
	//var url=Drupal.settings.basePath+"?q=meacars/filter/";
	//url=url + '1+5+14+15/1+5+69+70/all/all/all/?mileage[min]=&mileage[max]=&price[min]=&price[max]=&year[min]=2006&year[max]=2009&popup=true';
	//alert(url);
	/*
	for(i=0;i<transmission.length;i++){
	
		alert(transmission[i].checked);
	}
	*/
	//url + = checkboxes_to_param(transmission);
/*	var url=Drupal.settings.basePath+"?q=load_view/MeaCarsFilter/" +"1+5+14+15/1+5+69+70/1/all/all/all/&mileage[min]=&mileage[max]=&price[min]=&price[max]=&year[min]=2006&year[max]=2009";
*/
    
	return url;
}

function submit_find_now() {
    $.address.value('/');
    $.address.parameter('u', find_now_url(), true);
    $.address.parameter('a', "c", true);
    $.address.update();
    return false;
}

function loadfilteredCars(filterurl) {
    var url=Drupal.settings.basePath+"?q=load_view/MeaCarsFilter" +  filterurl
    var response=new Object();
    response.data='<p class="center"><img src="'+Drupal.settings.basePath+'sites/all/themes/meacar/images/AnimatedCarLoadingStatus.gif" alt=""/></p>';
    output_find_now(response);
    if( viewAJAX != undefined ){
        viewAJAX.abort();
    }
    viewAJAX = $.getJSON(url, null, output_find_now);
    removeArticlesBlogs();
    $('.menu-tabs li, .menu-tabs a').removeClass("active");
    $("#tab-cars").addClass("active");
    $("#tab-cars a").addClass("active");
    return false;
}

function output_find_now(response){
    var new_content=$("#main").html(response.data);
    load_meacars_dealership_filter_block_oncars();
    return false;
}

function load_make_model(){
	var selectCC=new Object();
	selectCC.value=$("#edit-car-info-carcompany").val();
	/* if(selectCC.value =="Select a Make"){
   		change_select(selectCC,"edit-car-info-carModel","meacarsModels","modelid,modelName");
	} */
	if(selectCC.value && selectCC.value!=""){
   		change_select(selectCC,"edit-car-info-carModel","meacarsModels","modelid,modelName","makeid");
	}	
}
function load_country_city(){
	var selectCC=new Object();
	selectCC.value=$("#edit-location-info-country").val();
	if(selectCC.value && selectCC.value!=""){
		change_select2(selectCC,"edit-location-info-city","meacarsCity","cityid,cityName","cid");
	}
}
/*Ajax loading Form*/
function load_node_form(tab, form_id, args){
    $.address.value('/');
    $.address.parameter('tab', tab, true);
    $.address.parameter('form_id', form_id, true);
    $.address.parameter('args', args, true);
    $.address.parameter('a', "node", true);
    $.address.update();
        
    return false;

	return false;
}

function ajaxLoadNodeForm(tab,form_id,args) {
	var response=new Object();
	response.data='<p class="center"><img src="'+Drupal.settings.basePath+'sites/all/themes/meacar/images/AnimatedCarLoadingStatus.gif" alt=""/></p>';
	output_node_form(response);
	
	$.getJSON(Drupal.settings.basePath+"?q=load_form/"+form_id, null, output_node_form);
	
	var li = $(".menu-tabs UL LI");
	for(i=0;i<li.length;i++){
		$("#"+li[i].id).removeClass("active");
		$("#"+li[i].id+" A").removeClass("active");
	}
	$("#"+tab).addClass("active");
	$("#"+tab+" A").addClass("active");
	
	jQuery.extend(Drupal.settings, { "basePath": Drupal.settings.basePath,"ahah": { "edit-node-images-attach": { "url": Drupal.settings.basePath+"node_images/js", "event": "mousedown", "keypress": true, "wrapper": "node_images-attach-wrapper", "selector": "#edit-node-images-attach", "effect": "none", "method": "replace", "progress": { "type": "bar", "message": "Please wait..." }, "button": { "attach": "Attach" } }, "edit-submit-2": { "url": Drupal.settings.basePath+"node_images/js", "event": "mousedown", "keypress": true, "wrapper": "main", "selector": "#edit-submit-2", "effect": "fade", "method": "replace", "progress": { "type": "throbber" }, "button": { "op": "Sell your car" } } }, "tableDrag": { "node_images_attach_list": { "node_images-weight": [ { "target": "node_images-weight", "source": "node_images-weight", "relationship": "sibling", "action": "order", "hidden": true, "limit": 0 } ] } } });


}

function output_node_form(response){

	var new_content=$("#main").html(response.data);
    Drupal.attachBehaviors(new_content);
	Drupal.unfreezeHeight();
	//Currency
	if($("#edit-price-units").val()!=""){
		$("#edit-car-info-currency").val($("#edit-price-units").val());
	}
	//Mileage
	if($("#dit-milage-units").val()!=""){
		$("#edit-car-info-mileageUnit").val($("#edit-milage-units").val());
	}
	//Make
	var make=$("#filter-side-bar-make INPUT[type='checkbox'][checked]");
	//$("#edit-car-info-carcompany").val(make[0].value);
	load_make_model();
	load_country_city();
	//change_select(this,"edit-car-info-carModel","meacarsModels","modelid,modelName","makeid");
	return false;
}
/*Contact Seller tab*/
function load_form_contact(tab,form_id,uid,nid){
	var response=new Object();	
	response.data='<p style="text-align:center;"><img src="'+Drupal.settings.basePath+'sites/all/themes/meacar/images/AnimatedCarLoadingStatus.gif" alt=""/></p>';
	output_node_content(response);
	$.getJSON(Drupal.settings.basePath+"?q=load_form/"+form_id+'/'+uid+'/'+nid, null, output_node_content);
	var li = $(".meacars-detail-tab UL LI");
	for(i=0;i<li.length;i++){
		$("#"+li[i].id).removeClass("active-first");
		$("#"+li[i].id).removeClass("active-second");
		$("#"+li[i].id).removeClass("active-third");
		$("#"+li[i].id).removeClass("active-fourth");
	}
	if(tab=="meacars-contact-seller"){
		for(i=0;i<li.length;i++){
			$("#"+li[i].id).addClass("active-fourth");
		}
	}
	for(i=0;i<li.length;i++){
		$("#"+li[i].id).removeClass("active");
		$("#"+li[i].id+" A").removeClass("active");
	}
	$("#"+tab).addClass("active");
	$("#"+tab+" A").addClass("active");
  if(tab=="meacars-contact-seller") {
      $(".meacars-detail-tab UL").removeClass("this_active_first");
      $(".meacars-detail-tab UL").addClass("this_active_second"); 
  }
  
	return false;
}

/*AJax node content*/
function load_node_content(tab,nid){
	var response=new Object();	
	response.data='<p style="text-align:center;"><img src="'+Drupal.settings.basePath+'sites/all/themes/meacar/images/AnimatedCarLoadingStatus.gif" alt=""/></p>';
	output_node_content(response);
	$.getJSON(Drupal.settings.basePath+"?q=load_page/"+ tab +"/node/"+nid, null, output_node_content);
	var li = $(".meacars-detail-tab UL LI");
	for(i=0;i<li.length;i++){
		$("#"+li[i].id).removeClass("active-first");
		$("#"+li[i].id).removeClass("active-second");
		$("#"+li[i].id).removeClass("active-third");
		$("#"+li[i].id).removeClass("active-fourth");
	}
	
	if(tab=="meacars-overview"){
		for(i=0;i<li.length;i++){
			$("#"+li[i].id).addClass("active-first");
		}
	}
	else if(tab=="meacars-options"){
		for(i=0;i<li.length;i++){
			$("#"+li[i].id).addClass("active-second");
		}
	}
	else if(tab=="meacars-details"){
		for(i=0;i<li.length;i++){
			$("#"+li[i].id).addClass("active-third");
		}
	}
	for(i=0;i<li.length;i++){
		$("#"+li[i].id).removeClass("active");
		$("#"+li[i].id+" A").removeClass("active");
	}
	$("#"+tab).addClass("active");
	$("#"+tab+" A").addClass("active");
}
/*Conact Seller tab*/
function output_node_content(response){

	var new_content=$("#content-swapper").html(response.data);	
  /** Adding classes to not checked labels */
  $("#options-node-page INPUT[type='checkbox']").each(function() {
    if (this.checked == false) { 
       $(this).parent().addClass('disabled_checkboxes');
       $(this).attr('disabled','disabled');
    }
   });
	return false;
}
/*Ajax Car info changed*/
var selectId;
var selectId2;

function change_select(select_element,id,table,select_field,where_field){
  var model_val = $('#' + id).val();
	$('#'+ id +'').children().remove();
	selectId=id;
  if(selectId == 'edit-car-info-carModel') {
       $.getJSON(Drupal.settings.basePath+"?q=load_onchange/"+table+"/"+ select_field + "/" + where_field + "/" + select_element.value + "/" + model_val, null, output_select_element); 
  }
  else {
	$.getJSON(Drupal.settings.basePath+"?q=load_onchange/"+table+"/"+ select_field + "/" + where_field + "/" + select_element.value, null, output_select_element);
  }
	return false;
}

function change_select2(select_element,id,table,select_field,where_field){
	$('#'+ id +'').children().remove();
	selectId2=id;
	$.getJSON(Drupal.settings.basePath+"?q=load_onchange/"+table+"/"+ select_field + "/" + where_field + "/" + select_element.value, null, output_select_element2);
	return false;
}

function output_select_element2(response){	
	var arr_options=response.data.split("][");
	var items='';
	for(i=0;i<arr_options.length;i++){
		values=arr_options[i].split("=>");
		items +='<option value="'+values[0]+'">'+values[1]+'</option>';
	}
	$('#'+ selectId2 +'').html(items);

}

function output_select_element(response){
	if(response.data != null){
	var arr_options=response.data.split("][");
	var items='';
	for(i=0;i<arr_options.length;i++){
		values=arr_options[i].split("=>");
    if (response.default_value == values[0]) {
       items +='<option selected="selected" value="'+values[0]+'">'+values[1]+'</option>'; 
    }
    else {
		  items +='<option value="'+values[0]+'">'+values[1]+'</option>';
    }
	}
	$('#'+ selectId +'').html(items);
 }
}
/*Category onlick()*/
function category_all_cars(cars){
	$("#filter-side-bar-category" + " INPUT[type='checkbox']").attr('checked', false);
	var array_cars=cars.split(";");
	for(i=0;i<array_cars.length;i++){
			$("#edit-category-options-"+array_cars[i]).attr('checked', true);
	}
    return false;
}
function category_all_trucks(trucks) {
	$("#filter-side-bar-category" + " INPUT[type='checkbox']").attr('checked', false);
	var array_trucks=trucks.split(";");
	for(i=0;i<array_trucks.length;i++){
			$("#edit-category-options-"+array_trucks[i]).attr('checked', true);
	}
    return false;
}
function category_x() {
    $("#filter-side-bar-category" + " INPUT[type='checkbox']").attr('checked', false);
    return false;
}

function category_all(){
    $("#filter-side-bar-category" + " INPUT[type='checkbox']").attr('checked', true);
    return false;
}
/*Make onlick()*/
function make_european(european) {
    $("#filter-side-bar-make" + " INPUT[type='checkbox']").attr('checked', false);
    var array_european = european.split(";");
    for (i=0; i < array_european.length; i++) {
        $("#edit-make-options-" + array_european[i]).attr('checked', true);
    }
    return false;
}

function make_american(american) {
    $("#filter-side-bar-make" + " INPUT[type='checkbox']").attr('checked', false);
    var array_american = american.split(";");
    for (i = 0; i < array_american.length; i++) {
        $("#edit-make-options-" + array_american[i]).attr('checked', true);
    }
    return false;
}

function make_x(){
    $("#filter-side-bar-make" + " INPUT[type='checkbox']").attr('checked', false);
    return false;
}

function make_japanese(japanes) {
    $("#filter-side-bar-make" + " INPUT[type='checkbox']").attr('checked', false);
    var array_japanes = japanes.split(";");
    for(i = 0; i < array_japanes.length; i++) {
        $("#edit-make-options-" + array_japanes[i]).attr('checked', true);
    }
    return false;
}

function make_all_cars() {
	$("#filter-side-bar-make" + " INPUT[type='checkbox']").attr('checked', true);
    return false;
}

/*Country onlick()*/
function top_select_country(cid) {
    if (activeTab == 'C') {
        $("#filter-side-bar-country" + " input[type='checkbox']").attr('checked', false);
        $("#edit-country-options-" + cid).attr('checked', true);
        show_dealerships_by_country(cid);
        mdf_country_select();
        return pre_submit_findnow();
    }
    if (activeTab == 'D') {
        $("#mdf-filter-side-bar-country" + " input[type='checkbox']").attr('checked', false);
        $("#edit-mdf-country-options-" + cid).attr('checked', true);
        $('.country-list li').removeClass();
        $('.country-list #' + c_a[cid]).addClass('active_' + c_a[cid]);
        new_mdf_country_select();
        mdf_flag_country_select(function() {
            mdf_submit_find_now();
        });
        return false;
    }
}

function new_mdf_country_select() {
    $("#mdf-filter-side-bar-country" + " input[type='checkbox']").each(function() {
        if ($(this).attr('checked') == true) {
            var country = c_a[$(this).val()];
            $('.country-bar #' + country).addClass('active_' + country);
        } else {
            var country = c_a[$(this).val()];
            $('.country-bar #' + country).removeClass('active_' + country);
        }
    });
    var country = {};
    $("#mdf-filter-side-bar-country" + " INPUT[type='checkbox']").each(function() {
        if(this.checked) {
            country[this.value] = this.value;
        }
    });
    $.post(
        Drupal.settings.filterarea.url,
        country,
        function(response) {
            $('#filter-side-bar-area div.fieldset-wrapper div.form-checkboxes').html(response.data);
        },'json'
    );
}

/** select all countries */
/*Country onlick()*/
function top_select_country_all() {
    if (activeTab == 'C') {
        $("#filter-side-bar-country" + " input[type='checkbox']").attr('checked', true);
        select_all_remove_class();
        all_dealerships();
        return submit_find_now();
    }
    if (activeTab == 'D') {
        $("#mdf-filter-side-bar-country" + " input[type='checkbox']").attr('checked', true);
        select_all_remove_class();
        all_dealerships();
        mdf_all_flag_country_select();
        return false;
    }
}


function country_gulf(gulf){
	$("#filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', false);
    $("#mdf-filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', false);
	var array_gulf=gulf.split(";");
	for(i=0;i<array_gulf.length;i++){
        $("#edit-mdf-country-options-"+array_gulf[i]).attr('checked', true);
        $("#edit-country-options-"+array_gulf[i]).attr('checked', true);
		show_dealerships_by_country(array_gulf[i]);
	}	
    return false;							   
}					   
function country_north(north){
	$("#filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', false);
    $("#mdf-filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', false);
	var array_north=north.split(";");
	for(i=0;i<array_north.length;i++){
		$("#edit-mdf-country-options-"+array_north[i]).attr('checked', true);
        $("#edit-country-options-"+array_north[i]).attr('checked', true);
		show_dealerships_by_country(array_north[i]);
	}	
	
    return false;								
}					
function country_x(){
    $("#filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', false);
    $("#mdf-filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', false);
    var dealerships=$("#filter-side-bar-listings INPUT[type='checkbox']");
    for(j=0;j<dealerships.length;j++){
        dealerships[j].checked=false;
        $("#"+dealerships[j].id+'-wrapper').hide();
    }
    return false;
}				
function country_central(center){
	$("#filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', false);
    $("#mdf-filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', false);
	var array_central=center.split(";");
	for(i=0;i<array_central.length;i++){
		$("#edit-country-options-"+array_central[i]).attr('checked', true);
        $("#edit-mdf-country-options-"+array_central[i]).attr('checked', true);
        $("#edit-country-options-"+array_central[i]).attr('checked', true);
		show_dealerships_by_country(array_central[i]);
	}	
    return false;								 
}					 
function country_west(west){
	$("#filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', false);
    $("#mdf-filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', false);  
	var array_west=west.split(";");
	for(i=0;i<array_west.length;i++){
        $("#edit-mdf-country-options-"+array_west[i]).attr('checked', true);
        $("#edit-country-options-"+array_west[i]).attr('checked', true);
		/////////////////////////
		show_dealerships_by_country(array_west[i]);
	}	
	
    return false;							   
}	
function all_country(){
	$("#filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', true);
	$("#mdf-filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', true);
	var dealerships=$("#filter-side-bar-listings INPUT[type='checkbox']");
	for(j=0;j<dealerships.length;j++){
		$("#"+dealerships[j].id+'-wrapper').show();
	}
	return false;
}
/*filter dealerships by country when onlick() an item*/
function country_select(selitem, str_uid) {
    var array_uid = str_uid.split(";");
    var country = '';
    if (typeof(c_a) != "undefined") {
        country = c_a[selitem.value];
    }
    if (selitem.checked) {
        if (country) {
            $('#' + country).addClass('active_' + country);
        }
        for (i = 0; i < array_uid.length; i++) {
            if($("#edit-listings-users-options-" + array_uid[i] + "-" + selitem.value).attr('checked') == false) {
                $("#edit-listings-users-options-" + array_uid[i] + "-" + selitem.value).attr('checked', true);
                $("#edit-listings-users-options-" + array_uid[i] + "-" + selitem.value + "-wrapper").show();
            }
        }
    } else {
        if (country) {
            $('#' + country).removeClass('active_' + country);
        }
        for (i = 0; i < array_uid.length; i++) {
            if ($("#edit-listings-users-options-" + array_uid[i] + "-" + selitem.value + "-wrapper")) {
                $("#edit-listings-users-options-" + array_uid[i] + "-" + selitem.value).attr('checked', false);
                $("#edit-listings-users-options-" + array_uid[i] + "-" + selitem.value + "-wrapper").hide();
            }
        }
    }
}

function show_dealerships_by_country(country_id){
    var dealerships = $("#filter-side-bar-listings input[type='checkbox']");
    for (j = 0; j < dealerships.length; j++) {
        $("#edit-listings-users-options-" + dealerships[j].value + "-" + country_id + '-wrapper').show();
    }
}
/*Dealerships onlick()*/
function all_dealerships(){
	$("#filter-side-bar-listings" + " INPUT[type='checkbox']").attr('checked', true);
	return false;
}
function x_dealerships(){
	$("#filter-side-bar-listings" + " INPUT[type='checkbox']").attr('checked', false);
	return false;
}
/************/
/**
* @param object sliderObj
* @param int val (the value)
* @param int newPos
* @param int knobNo
 */
function bsSliderChangeMilage(sliderObj, val, newPos, knobNumber) { 
	var left = ($("#edit-milage1").attr('value'))*1;
	var right= ($("#edit-milage2").attr('value'))*1;
	if(left>right) {
		$("#edit-milage1").attr('value',val);	
		$("#edit-milage2").attr('value',val);	
		
	}
	else{
		$("#edit-milage"+knobNumber).attr('value',val);	
	}
	if(knobNumber==2){
		if($("#edit-milage2").attr('value')==max_m) {
			$("#milage_max_value").show();
		}
		else{
			$("#milage_max_value").hide();
		}
	}
}

function bsSliderChangeYear(sliderObj, val, newPos, knobNumber) { 
	var left = ($("#edit-year1").attr('value'))*1;
	var right= ($("#edit-year2").attr('value'))*1;
	if(left>right) {
		$("#edit-year1").attr('value',left);	
		$("#edit-year2").attr('value',left);	
/*		
		$("#vfsliderDivYear").attr('value',left);	
		$("#vfsliderDivYear2").attr('value',left);	
		*/
	}
	else{
		$("#edit-year"+knobNumber).attr('value',val);
	}
}

function bsSliderChangePrice(sliderObj, val, newPos, knobNumber) { 
	var left = ($("#edit-price1").attr('value'))*1;
	var right= ($("#edit-price2").attr('value'))*1;
	if(left>right) {
		$("#edit-price1").attr('value',left);	
		$("#edit-price2").attr('value',left);			
	}
	else{
		$("#edit-price"+knobNumber).attr('value',val);
	}
	if(knobNumber==2){		
		if($("#edit-price2").attr('value')==max_p) {
			$("#price_max_value").show();
		}
		else{
			$("#price_max_value").hide();
		}
	}

}

////////////////////////add a sliderbar
function createYearSlider(width,height,minVal,maxVal,valueInterval,valueDefault,minVal2,maxVal2,valueInterval2,valueDefault2,wrapper,imgDir){
	
  	yearSlider.width         = width;
  	yearSlider.height        = height;
  	yearSlider.imgDir   = imgDir+'sites/all/modules/filter_side_bar/slider/';
  	yearSlider.setBackgroundImage('meacar/background.gif', 'no-repeat');
  	if(wrapper=='Year'){
	  	yearSlider.attachOnChange(bsSliderChangeYear);

  	}
  	else if(wrapper=='Milage'){
	   	yearSlider.attachOnChange(bsSliderChangeMilage);

  	}
  	else if(wrapper=='Price'){
	   	yearSlider.attachOnChange(bsSliderChangePrice);

  	}
  	yearSlider.fieldName     = 'slider'+wrapper+'_start';
  	yearSlider.minVal        = minVal;
  	yearSlider.maxVal        = maxVal;
  	yearSlider.valueInterval = valueInterval;
  	yearSlider.valueDefault  = valueDefault;
  	yearSlider.setSliderIcon('meacar/slider.gif', 8, 17);
  	yearSlider.useInputField = 2;
  	yearSlider.styleValueFieldClass = 'sliderInput';
	
  	yearSlider.colorbar = new Object({ color:'grey',cssClass:'colobar', height:11, widthDifference:-46, offsetLeft:6, offsetTop:4 });
	
	yearSlider.useSecondKnob  = true;
	yearSlider.wheelAmount    = 0; //disable mouse wheeling cause we have 2 knobs.
	
	yearSlider.fieldName2     = 'slider'+wrapper+'_end';
  	yearSlider.minVal2        = minVal2;
  	yearSlider.maxVal2        = maxVal2;
  	yearSlider.valueInterval2 = valueInterval2;
  	yearSlider.valueDefault2  = valueDefault2;
  	yearSlider.setSliderIcon2('meacar/slider.gif', 8, 17);
  	yearSlider.useInputField2 = 2;
  	yearSlider.styleValueFieldClass2 = 'sliderInput';
    yearSlider.colorbar2 = new Object({ color:'grey', cssClass:'colobar2',height:11, widthDifference:-45, offsetLeft:50, offsetTop:4 });

  	yearSlider.drawInto('sliderDiv'+wrapper);
}
function createPriceSlider(width,height,minVal,maxVal,valueInterval,valueDefault,minVal2,maxVal2,valueInterval2,valueDefault2,wrapper,imgDir){
	
  	priceSlider.width         = width;
  	priceSlider.height        = height;
  	priceSlider.imgDir   = imgDir+'sites/all/modules/filter_side_bar/slider/';
  	priceSlider.setBackgroundImage('meacar/background.gif', 'no-repeat');
  	if(wrapper=='Year'){
	  	priceSlider.attachOnChange(bsSliderChangeYear);

  	}
  	else if(wrapper=='Milage'){
	   	priceSlider.attachOnChange(bsSliderChangeMilage);

  	}
  	else if(wrapper=='Price'){
	   	priceSlider.attachOnChange(bsSliderChangePrice);

  	}
  	priceSlider.fieldName     = 'slider'+wrapper+'_start';
  	priceSlider.minVal        = minVal;
  	priceSlider.maxVal        = maxVal;
  	priceSlider.valueInterval = 1000;
  	priceSlider.valueDefault  = valueDefault;
  	priceSlider.setSliderIcon('meacar/slider.gif', 8, 17);
  	priceSlider.useInputField = 2;
  	priceSlider.styleValueFieldClass = 'sliderInput';
	
  	priceSlider.colorbar = new Object({ color:'grey',cssClass:'colobar', height:11, widthDifference:-43, offsetLeft:-3, offsetTop:4 });
	
	priceSlider.useSecondKnob  = true;
	priceSlider.wheelAmount    = 0; //disable mouse wheeling cause we have 2 knobs.
	
	priceSlider.fieldName2     = 'slider'+wrapper+'_end';
  	priceSlider.minVal2        = minVal2;
  	priceSlider.maxVal2        = maxVal2;
  	priceSlider.valueInterval2 = 1000;
  	priceSlider.valueDefault2  = valueDefault2;
  	priceSlider.setSliderIcon2('meacar/slider.gif', 8, 17);
  	priceSlider.useInputField2 = 2;
  	priceSlider.styleValueFieldClass2 = 'sliderInput';
    priceSlider.colorbar2 = new Object({ color:'grey', cssClass:'colobar2',height:11, widthDifference:-39, offsetLeft:42, offsetTop:4 });

  	priceSlider.drawInto('sliderDiv'+wrapper);
}
function createMileageSlider(width,height,minVal,maxVal,valueInterval,valueDefault,minVal2,maxVal2,valueInterval2,valueDefault2,wrapper,imgDir){
	
  	mileageSlider.width         = width;
  	mileageSlider.height        = height;
  	mileageSlider.imgDir   = imgDir+'sites/all/modules/filter_side_bar/slider/';
  	mileageSlider.setBackgroundImage('meacar/background.gif', 'no-repeat');
  	if(wrapper=='Year'){
	  	mileageSlider.attachOnChange(bsSliderChangeYear);

  	}
  	else if(wrapper=='Milage'){
	   	mileageSlider.attachOnChange(bsSliderChangeMilage);

  	}
  	else if(wrapper=='Price'){
	   	mileageSlider.attachOnChange(bsSliderChangePrice);

  	}
  	mileageSlider.fieldName     = 'slider'+wrapper+'_start';
  	mileageSlider.minVal        = minVal;
  	mileageSlider.maxVal        = maxVal;
  	mileageSlider.valueInterval = 1000;
  	mileageSlider.valueDefault  = valueDefault;
  	mileageSlider.setSliderIcon('meacar/slider.gif', 8, 17);
  	mileageSlider.useInputField = 2;
  	mileageSlider.styleValueFieldClass = 'sliderInput';
	
  	mileageSlider.colorbar = new Object({ color:'grey',cssClass:'colobar', height:11, widthDifference:-32, offsetLeft:-13, offsetTop:4 });
	
	mileageSlider.useSecondKnob  = true;
	mileageSlider.wheelAmount    = 0; //disable mouse wheeling cause we have 2 knobs.
	
	mileageSlider.fieldName2     = 'slider'+wrapper+'_end';
  	mileageSlider.minVal2        = minVal2;
  	mileageSlider.maxVal2        = maxVal2;
  	mileageSlider.valueInterval2 = 1000;
  	mileageSlider.valueDefault2  = valueDefault2;
  	mileageSlider.setSliderIcon2('meacar/slider.gif', 8, 17);
  	mileageSlider.useInputField2 = 2;
  	mileageSlider.styleValueFieldClass2 = 'sliderInput';
    mileageSlider.colorbar2 = new Object({ color:'grey', cssClass:'colobar2',height:11, widthDifference:-30, offsetLeft:32, offsetTop:4 });

  	mileageSlider.drawInto('sliderDiv'+wrapper);
}
//dealership values on selected item, if default_value=all then list all dealerships
function put_dealership(default_value)
{
	//if default_value=all then list all dealerships
	if(default_value!="all"){
		
		if($("#edit-listings-role-1").attr('checked')){
			var country=$("#filter-side-bar-country INPUT[type='checkbox']");
			var dealerships=$("#filter-side-bar-listings INPUT[type='checkbox']");
			for(i=0;i<dealerships.length;i++){
				var array_uid=dealerships[i].value.split("-");
				var j=0;
				while(j<country.length){
					if(country[j].checked){			
						if($("#edit-listings-users-options-"+array_uid[0]+"-"+array_uid[1]+"-"+country[j].value+"-wrapper")){							
							$("#edit-listings-users-options-"+array_uid[0]+"-"+array_uid[1]+"-"+country[j].value).attr('checked', true);
							$("#edit-listings-users-options-"+array_uid[0]+"-"+array_uid[1]+"-"+country[j].value+"-wrapper").show();				
						}					
					}
					else{
						if($("#edit-listings-users-options-"+array_uid[0]+"-"+array_uid[1]+"-"+country[j].value+"-wrapper")){								
							$("#edit-listings-users-options-"+array_uid[0]+"-"+array_uid[1]+"-"+country[j].value).attr('checked', false);
							$("#edit-listings-users-options-"+array_uid[0]+"-"+array_uid[1]+"-"+country[j].value+"-wrapper").hide();				
						}	
					}
					j++;
				}
			}
		}
	}
	//just show up the items on selected country
	else{
		if($("#edit-listings-role-1").attr('checked')){
			var country=$("#filter-side-bar-country INPUT[type='checkbox']");
			var dealerships=$("#filter-side-bar-listings INPUT[type='checkbox']");
			for(i=0;i<dealerships.length;i++){
				var array_uid=dealerships[i].value.split("-");
				var j=0;
				while(j<country.length){
					if($("#edit-listings-users-options-"+array_uid[0]+"-"+array_uid[1]+"-"+country[j].value+"-wrapper")){							
						$("#edit-listings-users-options-"+array_uid[0]+"-"+array_uid[1]+"-"+country[j].value).attr('checked', true);
						$("#edit-listings-users-options-"+array_uid[0]+"-"+array_uid[1]+"-"+country[j].value+"-wrapper").show();				
					}								
					j++;
				}
			}
		}
	}
}
//Listing onclick()
function dealership(str_uid){
	var array_uid=str_uid.split(";");
	var dealer = 1;
	var owner	= 0;
	var country=$("#filter-side-bar-country INPUT[type='checkbox']");		
	//alert($("#edit-listings-role-1").attr('checked'));
	if($("#edit-listings-role-1").attr('checked')){
	//if($("#edit-listings-role-Dealership").attr('checked')){
		
		$("#filter-side-bar-listings").show();
		var has_checked=false;
		for(i=0;i<array_uid.length;i++){			
			var j=0;
			//checked by countries
			while(j<country.length){
				if(country[j].checked){	
					has_checked=true;
					if($("#edit-listings-users-options-"+array_uid[i]+"-"+dealer+'-'+country[j].value+"-wrapper")){		
						
						$("#edit-listings-users-options-"+array_uid[i]+"-"+dealer+'-'+country[j].value).attr('checked', true);
						$("#edit-listings-users-options-"+array_uid[i]+"-"+dealer+'-'+country[j].value+"-wrapper").show();				
					}					
				}
				else{
					if($("#edit-listings-users-options-"+array_uid[i]+"-"+dealer+'-'+country[j].value+"-wrapper")){		
						
						$("#edit-listings-users-options-"+array_uid[i]+"-"+dealer+'-'+country[j].value).attr('checked', false);
						$("#edit-listings-users-options-"+array_uid[i]+"-"+dealer+'-'+country[j].value+"-wrapper").hide();				
					}	
				}
				j++;
			}
			
		}	
		//No selection == All Selection.
		if(!has_checked){
			for(i=0;i<array_uid.length;i++){			
				var j=0;
				while(j<country.length){								
					$("#edit-listings-users-options-"+array_uid[i]+"-"+dealer+'-'+country[j].value).attr('checked', true);
					$("#edit-listings-users-options-"+array_uid[i]+"-"+dealer+'-'+country[j].value+"-wrapper").show();				
					j++;
				}
			}
		}
	}
	else{
		$("#filter-side-bar-listings").hide();
		for(i=0;i<array_uid.length;i++){
			var j=0;
			while(j<country.length){
				if($("#edit-listings-users-options-"+array_uid[i]+"-"+dealer+'-'+country[j].value+"-wrapper")){								
					$("#edit-listings-users-options-"+array_uid[i]+"-"+dealer+'-'+country[j].value).attr('checked', false);
					$("#edit-listings-users-options-"+array_uid[i]+"-"+dealer+'-'+country[j].value+"-wrapper").hide();				
				}
				j++;
			}
		}	
	}
	//if($("#edit-listings-role--1").attr('checked')){
	if($("#edit-listings-role-2").attr('checked')){
	//if($("#edit-listings-role-Private-Owners").attr('checked')){
		for(i=0;i<array_uid.length;i++){

			if($("#edit-listings-users-options-"+array_uid[i]+"-"+owner+"-wrapper")){
				//$("#edit-listings-users-options-"+array_uid[i]+"-"+owner).attr('checked', true);
				$("#edit-listings-users-options-"+array_uid[i]+"-"+owner+"-wrapper").show();
			}
		}	
	}
	else{
		for(i=0;i<array_uid.length;i++){
			if($("#edit-listings-users-options-"+array_uid[i]+"-"+owner+"-wrapper")){
				$("#edit-listings-users-options-"+array_uid[i]+"-"+owner).attr('checked', false);
				$("#edit-listings-users-options-"+array_uid[i]+"-"+owner+"-wrapper").hide();
			}
		}	
	}
	
	

}
/*initialize dealerships values on page loads
str_uid are dealerships
str_dealers are selected dealerships
*/
function load_dealership(str_uid,str_dealers){
	var array_uid=str_uid.split(";");
	var array_dealer=str_dealers.split(" ");
	

	for(i=0;i<array_uid.length;i++){		
		var found=false;
		var arr_d=array_uid[i].split("-");
		
		var j=0;
		//Find all dealerships selected when page loads
		while(!found && j<array_dealer.length){
			if(arr_d[0]==array_dealer[j]){
				found=true;
			}
			j++;
		}
		//if dealership item was checked
		if(found){			
			//show it
			if($("#edit-listings-users-options-"+array_uid[i])){
				$("#edit-listings-users-options-"+array_uid[i]).attr('checked', true);		
			}
		}
		//dealership item was not checked
		else{
			//hide it
			if($("#edit-listings-users-options-"+array_uid[i])){
				$("#edit-listings-users-options-"+array_uid[i]).attr('checked', false);
			}
		}

	}
	var country=$("#filter-side-bar-country INPUT[type='checkbox']");
	//If Dealership checkbox was checked
	if($("#edit-listings-role-1").attr('checked')){
		//shop dropdown menu
		$("#filter-side-bar-listings").show();

		if(str_dealers!='null' && array_dealer.length>0){
			//if has dealerships on dropdown menu were selected
			if(array_dealer[0]!='null'){
				for(i=0;i<array_uid.length;i++){
					var arr_d=array_uid[i].split("-");
					var found=false;
					var k=0;
					//alert(array_dealer.length);
					//checking this item (i) was selected, was it not?
					while(!found && k<array_dealer.length){
						var tmp=array_dealer[k]+"-1";
						if(array_uid[i]==tmp){						
							found=true;
						}
						k++;
					}
					var j=0;
					while(j<country.length){
						//if this item (i) was selected
						if(found && $("#edit-listings-users-options-"+array_uid[i]+"-"+country[j].value+"-wrapper")){								
							//$("#edit-listings-users-options-"+array_uid[i]+"-"+country[j].value).attr('checked', true);
							$("#edit-listings-users-options-"+array_uid[i]+"-"+country[j].value).attr('checked', false);
							$("#edit-listings-users-options-"+array_uid[i]+"-"+country[j].value+"-wrapper").show();				
						}
						//if this item (i) was not selected
						else{					
							//$("#edit-listings-users-options-"+array_uid[i]+"-"+country[j].value).attr('checked', false);
							$("#edit-listings-users-options-"+array_uid[i]+"-"+country[j].value).attr('checked', true);
							//$("#edit-listings-users-options-"+array_uid[i]+"-"+country[j].value+"-wrapper").hide();				
						}
						j++;
					}
				}
				
			}
			//if has not dealerships on dropdown menu were selected
			else{
				put_dealership('all');
				
			}
		}
		else{
			//checking countries were selected or not selected then showup all dealerships of that countries
			//else then hide all dealerships are not in the countries were not selected
			if(str_dealers!='null'){
				for(i=0;i<array_uid.length;i++){
					var arr_d=array_uid[i].split("-");
					var j=0;
					while(j<country.length){
						//show it
						if(country[j].checked && arr_d[1]=="1" && $("#edit-listings-users-options-"+array_uid[i]+"-wrapper")){			
							if($("#edit-listings-users-options-"+array_uid[i]+"-"+country[j].value+"-wrapper")){		
						
								$("#edit-listings-users-options-"+array_uid[i]+"-"+country[j].value).attr('checked', true);
								$("#edit-listings-users-options-"+array_uid[i]+"-"+country[j].value+"-wrapper").show();				
							}					
						}
						//hide it
						else{
							if($("#edit-listings-users-options-"+array_uid[i]+"-"+country[j].value+"-wrapper")){		
						
								$("#edit-listings-users-options-"+array_uid[i]+"-"+country[j].value).attr('checked', false);
								$("#edit-listings-users-options-"+array_uid[i]+"-"+country[j].value+"-wrapper").hide();				
							}	
						}
						j++;
					}
			
					/*
					if(arr_d[1]=="1" && $("#edit-listings-users-options-"+array_uid[i]+"-wrapper")){
						$("#edit-listings-users-options-"+array_uid[i]+"-wrapper").show();
					}
					*/
				}
			}
			else{
				for(i=0;i<array_uid.length;i++){
					var arr_d=array_uid[i].split("-");
					var j=0;
					while(j<country.length){
						//show it
						if(country[j].checked && arr_d[1]=="1" && $("#edit-listings-users-options-"+array_uid[i]+"-wrapper")){			
							if($("#edit-listings-users-options-"+array_uid[i]+"-"+country[j].value+"-wrapper")){		
						
								$("#edit-listings-users-options-"+array_uid[i]+"-"+country[j].value).attr('checked', false);
								$("#edit-listings-users-options-"+array_uid[i]+"-"+country[j].value+"-wrapper").show();				
							}					
						}
						//hide it
						else{
							if($("#edit-listings-users-options-"+array_uid[i]+"-"+country[j].value+"-wrapper")){		
						
								$("#edit-listings-users-options-"+array_uid[i]+"-"+country[j].value).attr('checked', false);
								$("#edit-listings-users-options-"+array_uid[i]+"-"+country[j].value+"-wrapper").hide();				
							}	
						}
						j++;
					}
			
					/*
					if(arr_d[1]=="1" && $("#edit-listings-users-options-"+array_uid[i]+"-wrapper")){
						$("#edit-listings-users-options-"+array_uid[i]+"-wrapper").show();
					}
					*/
				}
			}
		}
	}
	////If Dealership checkbox was not checked
	else{
		//hide dropdown menu and deselect dealerships
		$("#filter-side-bar-listings").hide();
		for(i=0;i<array_uid.length;i++){
			var arr_d=array_uid[i].split("-");
			var j=0;
			while(j<country.length){
				if($("#edit-listings-users-options-"+array_uid[i]+"-"+country[j].value+"-wrapper")){								
					$("#edit-listings-users-options-"+array_uid[i]+"-"+country[j].value).attr('checked', false);
					$("#edit-listings-users-options-"+array_uid[i]+"-"+country[j].value+"-wrapper").hide();				
				}
				j++;
			}
		}	
	}
/*	
	if($("#edit-listings-role--1").attr('checked')){
		for(i=0;i<array_uid.length;i++){
			var arr_d=array_uid[i].split("-");
			if(arr_d[1]=="0" && $("#edit-listings-users-options-"+array_uid[i]+"-wrapper")){
				$("#edit-listings-users-options-"+array_uid[i]+"-wrapper").show();
			}
		}	
	}
	else{
		for(i=0;i<array_uid.length;i++){
			var arr_d=array_uid[i].split("-");
			if(arr_d[1]=="0" && $("#edit-listings-users-options-"+array_uid[i]+"-wrapper")){
				$("#edit-listings-users-options-"+array_uid[i]+"-wrapper").hide();
			}
		}	
	}
*/	
	
}
//initialize MAX values on page loads
function load_max_value(max_mileage,max_price){
	max_m=max_mileage;
	max_p=max_price;
	//Mileage
	/*
	if($("#edit-milage2").attr('value')==max_mileage) {
		$("#milage_max_value").show();
	}
	*/
	//Price
	/*
	if($("#edit-price2").attr('value')==max_price) {
		$("#price_max_value").show();
	}
	*/
}
function submit_default() {
    setalldefault();
    submit_find_now();
    return false;
}

function setalldefault() {
    $("#edit-milage-units option:contains('km')").attr('selected', "selected");
    $("#edit-price-units option:contains('USD')").attr('selected', "selected");
    maxYear = $('#edit-yearmaxdef')[0].value;
    minYear = $('#edit-yearmindef')[0].value;

    yearSlider.minVal= minYear;
    yearSlider.minVal2=minYear;
    yearSlider.maxVal= maxYear;
    yearSlider.maxVal2=maxYear;


    $("#edit-year1").attr('value',minYear);
    $("#edit-year2").attr('value',maxYear);
    $("#vfsliderDivYear").attr('value',minYear);
    var tmp=$("#vfsliderDivYear");
    tmp.focus();
    $("#vfsliderDivYear2").attr('value',maxYear);
    tmp=$("#vfsliderDivYear2");
    tmp.focus();

    mileageSlider.minVal= 0;
    mileageSlider.minVal2=0;
    mileageSlider.maxVal= 200000;
    mileageSlider.maxVal2=200000;


    $("#edit-milage1").attr('value',"0");
    $("#edit-milage2").attr('value',"200000");
    $("#vfsliderDivMilage").attr('value',"0");
    tmp=$("#vfsliderDivMilage");
    tmp.focus();
    //$("#vfsliderDivMilage2").attr('value',"200000");
    tmp=$("#vfsliderDivMilage2");
    tmp.focus();

    priceSlider.minVal= 0;
    priceSlider.minVal2=0;
    priceSlider.maxVal= max_p;
    priceSlider.maxVal2=max_p;


    $("#edit-price1").attr('value',"0");
    $("#edit-price2").attr('value',max_p);
    $("#vfsliderDivPrice").attr('value',"0");
    tmp=$("#vfsliderDivPrice");
    tmp.focus();
    $("#vfsliderDivPrice2").attr('value',max_p);
    tmp=$("#vfsliderDivPrice2");
    tmp.focus();

    $("#edit-transmission-all").attr("checked", "checked");
    tmp=$("#edit-transmission-all");
    tmp.focus();
    category_all();
    make_all_cars();
    all_dealerships();
    all_country();
    flag_sync();

    $("#edit-display-photos-only").attr('checked', false);
    tmp=$("#edit-display-photos-only");
    tmp.focus();
    $(".listing-checkboxes INPUT[type='checkbox']").attr('checked', true);
    //$("#filter-side-bar-make" + " INPUT[type='checkbox']").attr('checked', true);
}

/*filter dealerships by country when onlick() an item*/
function mdf_flag_country_select(callback) {
    var country = {};
    $("#mdf-filter-side-bar-country" + " INPUT[type='checkbox']").each( function() {
        if(this.checked) {
            country[this.value] = this.value;
        }
    });
    $.post(Drupal.settings.filterarea.url, country, function(response) {
        $('#filter-side-bar-area div.fieldset-wrapper div.form-checkboxes').html(response.data);
        if (typeof(callback) == 'function') {
            callback();
        }
    },'json');
}
/** filter all countries */
function mdf_all_flag_country_select(){
   var country = {};
   $("#mdf-filter-side-bar-country" + " INPUT[type='checkbox']").each( function() {
       if(this.checked) {
        country[this.value] = this.value;   
       }
   });
   $.post(Drupal.settings.filterarea.url,country,function(response) {
       $('#filter-side-bar-area div.fieldset-wrapper div.form-checkboxes').html(response.data);
       mdf_submit_find_now();
   },'json');
}

function pre_submit_findnow() {
    flag_sync();
    return submit_find_now();
}

function flag_sync() {
    var allselected = true;
    $('#all_middle_east').removeClass('middle_east_selected');
    $("#filter-side-bar-country INPUT[type='checkbox']").each(function() {
        if ($('#edit-country-options-' + this.defaultValue)[0].checked == true) {
            var flag_id = $(this).parent().text().toLowerCase();
            flag_id = jQuery.trim(flag_id);
            if (flag_id == 'saudi arabia') {
                flag_id = 'saudi_arabia';
            }
            $('#'+flag_id).addClass('active_' + flag_id);
        } else {
            var flag_id = $(this).parent().text().toLowerCase();
            flag_id = jQuery.trim(flag_id);
            if (flag_id == 'saudi arabia') {
                flag_id = 'saudi_arabia';
            }
            $('#'+flag_id).removeClass('active_'+flag_id);
            allselected = false;
        }
    });
    if (allselected) {
        select_all_remove_class();
    }
}


/** removing the flag class on select all */
function select_all_remove_class() {
$("#filter-side-bar-country INPUT[type='checkbox']").each(function() {
       var flag_id = $(this).parent().text().toLowerCase();
       flag_id = jQuery.trim(flag_id);
       if(flag_id == 'saudi arabia') {
           flag_id = 'saudi_arabia';
       }
       $('#'+flag_id).removeClass('active_'+flag_id); 
 });
 $('#all_middle_east').addClass('middle_east_selected');
}

function registerAddress() {
    $.address.autoUpdate(false);
    $.address.change(function(event) {
        var a = event.parameters['a'];
        if (typeof(a) == 'undefined') {
            if (window.location.pathname == '/') {
                //setalldefault();
                load_view('tab-cars', 'MeaCarsFilter');
                if (typeof(removed_articles_blogs) == undefined
                    || true === removed_articles_blogs
                ) {
                    removeArticlesBlogs();
                }
            } else {
                if (ajaxUpdated){
                    window.location.reload();
                }
            }
            return;
        }
        if (a == "c" || a == "d") {
            u = event.parameters['u'];
            u1 = u;
            for (i = 0; i < event.parameterNames.length; ++i) {
                if (event.parameterNames[i] != 'u' && event.parameterNames[i] != 'a') {
                    u1 += "&" + event.parameterNames[i] + "=" + event.parameters[event.parameterNames[i]];
                }
            }
        }
        
        if (a == "c") {
            var args = u.split('/');
            param_to_check("#filter-side-bar-country INPUT[type='checkbox']", args[1]);
            flag_sync();
            param_to_check("#filter-side-bar-make INPUT[type='checkbox']", args[2]);
            param_to_check(".container-transmission INPUT[type='radio']", args[3]);
            param_to_check(".listing-checkboxes INPUT[type='checkbox']", args[4]);
            param_to_check(".container-dealerships INPUT[type='checkbox']", args[5]);
            param_to_check("#filter-side-bar-category INPUT[type='checkbox']", args[7]);
            loadfilteredCars(u1);
            try {
                if (event.parameters['mileage[min]']) {
                    mileageSlider.setValue(event.parameters['mileage[min]']);
                }
                if (event.parameters['mileage[max]'] != '') {
                    mileageSlider.setValue(event.parameters['mileage[max]'], 2);
                }
                if (event.parameters['year[min]']) {
                    yearSlider.setValue(event.parameters['year[min]']);
                }
                if (event.parameters['year[max]'] != '') {
                    yearSlider.setValue(event.parameters['year[max]'], 2);
                }
                if (event.parameters['price[min]']) {
                    priceSlider.setValue(event.parameters['price[min]']);
                }
                if (event.parameters['price[max]'] != '') {
                    priceSlider.setValue(event.parameters['price[max]'], 2);
                }
            } catch(e) {}

            ajaxUpdated = true;
        }
        if (a == "d") {
            loadDealers(u1);
            ajaxUpdated = true;
        }
        if (a == "ba") {
            loadblogarticletab(event.parameters['tab'],event.parameters['view'],event.parameters['arg'], event.parameters['display']);
            ajaxUpdated = true;
        }
        if (a == "n") {
            loadNode(event.parameters['tab'],event.parameters['nid']);
            ajaxUpdated = true;
        }
        if (a == "node") {
            ajaxLoadNodeForm(event.parameters['tab'],event.parameters['form_id'],event.parameters['args'])
            ajaxUpdated = true;
        }
        if (a == "carnode") {
            loadcarnode(event.parameters['nid']);
            ajaxUpdated = true;
        }
    });
}


function param_to_check(check, str) {
    if (str == 'all') {
        $(check).attr('checked', true);
        return;
    }
    $(check).attr('checked', false);
    var chk = str.split('+');
    for (i = 0; i < chk.length; i++) {
        $(check + "[value=" + chk[i] + "]").attr('checked', true);
    }
}

function filter_side_bar_shownode(nid) {
  load_next_previous_content(nid); 
}
/*AJax node content*/
function load_next_previous_content(nid){
    $.address.value('/');
    $.address.parameter('a', "carnode", true);
    $.address.parameter('nid', nid, true);
    $.address.update();
}

function loadcarnode(nid) {
    var response=new Object();    
    response.data='<p style="text-align:center;"><img src="'+Drupal.settings.basePath+'sites/all/themes/meacar/images/AnimatedCarLoadingStatus.gif" alt=""/></p>';
    output_next_previous_content(response);
    $.getJSON(Drupal.settings.basePath+"?q=load_next_previous/"+nid, null, output_next_previous_content);
}

function output_next_previous_content(response){
    var new_content=$("#main").html(response.data); 
    if( response.setting != undefined ) {
     for (var i =0; i < response.setting.length; ++i) {
       if( response.setting[i].jcarousel )
        jQuery.extend(Drupal.settings.jcarousel, response.setting[i].jcarousel);
     }
     Drupal.attachBehaviors();      
     FB.Facebook.init("c6e2e204dc703b56548d144dc8a77844", "/sites/all/modules/fbconnect/xd_receiver.html"); 
    }
    return false;
}
function search_form_submit() {
  $('#search-theme-form input.form-submit').trigger('click');
};
/*
 * jQuery Address Plugin v1.2
 * http://www.asual.com/jquery/address/
 *
 * Copyright (c) 2009-2010 Rostislav Hristov
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * Date: 2010-05-05 08:15:54 +0300 (Wed, 05 May 2010)
 */
(function ($) {

    $.address = (function () {

        var _trigger = function(name) {
                $($.address).trigger(
                    $.extend($.Event(name), 
                        (function() {
                            var parameters = {},
                                parameterNames = $.address.parameterNames();
                            for (var i = 0, l = parameterNames.length; i < l; i++) {
                                parameters[parameterNames[i]] = $.address.parameter(parameterNames[i]);
                            }
                            return {
                                value: $.address.value(),
                                path: $.address.path(),
                                pathNames: $.address.pathNames(),
                                parameterNames: parameterNames,
                                parameters: parameters,
                                queryString: $.address.queryString()
                            };
                        }).call($.address)
                    )
                );
            },
            _bind = function(value, data, fn) {
                $($.address).bind(value, data, fn);
                return $.address;
            },
            _hash = function() {
                var index = _l.href.indexOf('#');
                return index != -1 ? _ec(_dc(_crawl(_l.href.substr(index + 1), FALSE))) : '';
            },
            _window = function() {
                try {
                    return top.document !== undefined ? top : window;
                } catch (e) { 
                    return window;
                }
            },
            _js = function() {
                return 'javascript';
            },
            _strict = function(value, force) {
                if (_opts.strict) {
                    value = force ? (value.substr(0, 1) != '/' ? '/' + value : value) : (value == '' ? '/' : value);
                }
                return value;
            },
            _local = function(value, direction) {
                return (_msie && _l.protocol == 'file:') ? 
                    (direction ? _value.replace(/\?/, '%3F') : _value.replace(/%253F/, '?')) : value;
            },
            _crawl = function(value, direction) {
                if (_opts.crawlable && direction) {
                    return (value != '' ? '!' : '') + value;
                }
                return value.replace(/^\!/, '');
            },
            _cssint = function(el, value) {
                return parseInt(el.css(value), 10);
            },
            _search = function(el) {
                var url, s;
                for (var i = 0, l = el.childNodes.length; i < l; i++) {
                    if (el.childNodes[i].src) {
                        url = String(el.childNodes[i].src);
                    }
                    s = _search(el.childNodes[i]);
                    if (s) {
                        url = s;
                    }
                }
                return url;
            },
            _listen = function() {
                if (!_silent) {
                    var hash = _hash(),
                        diff = _value != hash;
                    if (_safari && _version < 523) {
                        if (_length != _h.length) {
                            _length = _h.length;
                            if (typeof _stack[_length - 1] != UNDEFINED) {
                                _value = _stack[_length - 1];
                            }
                            _update(FALSE);
                        }
                    } else if (_msie && _version < 7 && diff) {
                        _l.reload();
                    } else if (diff) {
                        _value = hash;
                        _update(FALSE);
                    }
                }
            },
            _update = function(internal) {
                _trigger(CHANGE);
                _trigger(internal ? INTERNAL_CHANGE : EXTERNAL_CHANGE);
                _st(_track, 10);
            },
            _track = function() {
                var value = (_l.pathname + (/\/$/.test(_l.pathname) ? '' : '/') + 
                    ($.address ? $.address.value() : '')).replace(/\/\//, '/').replace(/^\/$/, ''),
                    fn = _t[_opts.tracker];
                if (typeof fn == FUNCTION) {
                    fn(value);
                } else if (typeof urchinTracker == FUNCTION) {
                    urchinTracker(value);
                } else if (typeof pageTracker != UNDEFINED && typeof pageTracker._trackPageview == FUNCTION) {
                    pageTracker._trackPageview(value);
                } else if (typeof _gaq != UNDEFINED && typeof _gaq.push == FUNCTION) {
                    _gaq.push(['_trackPageview', value]);
                }
            },
            _html = function() {
                var doc = _frame.contentWindow.document;
                doc.open();
                doc.write('<html><head><title>' + _d.title + '</title><script>var ' + ID + ' = "' + _hash() + '";</' + 'script></head></html>');
                doc.close();
            },
            _load = function() {
                if (!_loaded) {
                    _loaded = TRUE;
                    var body = $('body').ajaxComplete(function() {
                        _unescape.call(this);
                    }).trigger('ajaxComplete');
                    if (_opts.wrap) {
                        var wrap = $('body > *')
                            .wrapAll('<div style="padding:' + 
                                (_cssint(body, 'marginTop') + _cssint(body, 'paddingTop')) + 'px ' + 
                                (_cssint(body, 'marginRight') + _cssint(body, 'paddingRight')) + 'px ' + 
                                (_cssint(body, 'marginBottom') + _cssint(body, 'paddingBottom')) + 'px ' + 
                                (_cssint(body, 'marginLeft') + _cssint(body, 'paddingLeft')) + 'px;" />')
                            .parent()
                            .wrap('<div id="' + ID + '" style="height:100%; overflow:auto;' + 
                                (_safari ? (window.statusbar.visible && !/chrome/i.test(_agent) ? '' : ' resize:both;') : '') + '" />');
                        $('html, body')
                            .css({
                                height: '100%',
                                margin: 0,
                                padding: 0,
                                overflow: 'hidden'
                            });
                        if (_safari) {
                            $('<style type="text/css" />')
                                .appendTo('head')
                                .text('#' + ID + '::-webkit-resizer { background-color: #fff; }');
                        }
                    }
                    if (_msie && _version < 8) {
                        var frameset = _d.getElementsByTagName('frameset')[0];
                        _frame = _d.createElement((frameset ? '' : 'i') + 'frame');
                        if (frameset) {
                            frameset.insertAdjacentElement('beforeEnd', _frame);
                            frameset[frameset.cols ? 'cols' : 'rows'] += ',0';
                            _frame.src = _js() + ':' + FALSE;
                            _frame.noResize = TRUE;
                            _frame.frameBorder = _frame.frameSpacing = 0;
                        } else {
                            _frame.src = _js() + ':' + FALSE;
                            _frame.style.display = 'none';
                            _d.body.insertAdjacentElement('afterBegin', _frame);
                        }
                        _st(function() {
                            $(_frame).bind('load', function() {
                                var win = _frame.contentWindow;
                                var src = win.location.href;
                                _value = (typeof win[ID] != UNDEFINED ? win[ID] : '');
                                if (_value != _hash()) {
                                    _update(FALSE);
                                    _l.hash = _local(_crawl(_value, TRUE), TRUE);
                                }
                            });
                            if (typeof _frame.contentWindow[ID] == UNDEFINED) {
                                _html();
                            }
                        }, 50);
                    } else if (_safari) {
                        if (_version < 418) {
                            $(_d.body).append('<form id="' + ID + '" style="position:absolute;top:-9999px;" method="get"></form>');
                            _form = _d.getElementById(ID);
                        }
                        if (typeof _l[ID] == UNDEFINED) {
                            _l[ID] = {};
                        }
                        if (typeof _l[ID][_l.pathname] != UNDEFINED) {
                            _stack = _l[ID][_l.pathname].split(',');
                        }
                    }

                    _st(function() {
                        _trigger('init');
                        _update(FALSE);
                    }, 1);
                    
                    if ((_msie && _version > 7) || (!_msie && ('on' + HASH_CHANGE) in _t)) {
                        if (_t.addEventListener) {
                            _t.addEventListener(HASH_CHANGE, _listen, false);
                        } else if (_t.attachEvent) {
                            _t.attachEvent('on' + HASH_CHANGE, _listen);
                        }
                    } else {
                        _si(_listen, 50);
                    }
                    
                    //$('a[rel]').filter('[rel*=address:]').address();
                }
            },
            _unload = function() {
                if (_t.removeEventListener) {
                    _t.removeEventListener(HASH_CHANGE, _listen, false);
                } else if (_t.detachEvent) {
                    _t.detachEvent('on' + HASH_CHANGE, _listen);
                }
            },
            _unescape = function() {
                var base = _l.pathname.replace(/\/$/, ''),
                    fragment = '_escaped_fragment_';
                $('a[href]:not([href^=http])', this).each(function() {
                    var href = $(this).attr('href').replace(new RegExp(base + '/?$'), '');
                    if (href == '' || href.indexOf(fragment) != -1) {
                        $(this).attr('href', '#' + decodeURIComponent(href.replace(new RegExp('/(.*)\\?' + fragment + '=(.*)$'), '!$2')));
                    }
                });
            },
            ID = 'jQueryAddress',
            FUNCTION = 'function',
            UNDEFINED = 'undefined',
            HASH_CHANGE = 'hashchange',
            INIT = 'init',
            CHANGE = 'change',
            INTERNAL_CHANGE = 'internalChange',
            EXTERNAL_CHANGE = 'externalChange',
            TRUE = true,
            FALSE = false,
            _opts = {
                autoUpdate: TRUE, 
                crawlable: FALSE,
                history: TRUE, 
                strict: TRUE,
                wrap: FALSE
            },
            _browser = $.browser, 
            _version = parseFloat($.browser.version),
            _mozilla = _browser.mozilla,
            _msie = _browser.msie,
            _opera = _browser.opera,
            _safari = _browser.safari,
            _supported = FALSE,
            _t = _window(),
            _d = _t.document,
            _h = _t.history, 
            _l = _t.location,
            _si = setInterval,
            _st = setTimeout, 
            _dc = decodeURI,
            _ec = encodeURI,
            _agent = navigator.userAgent,            
            _frame,
            _form,
            _url = _search(document),
            _qi = _url ? _url.indexOf('?') : -1,
            _title = _d.title, 
            _length = _h.length, 
            _silent = FALSE,
            _loaded = FALSE,
            _justset = TRUE,
            _juststart = TRUE,
            _updating = FALSE,
            _stack = [], 
            _listeners = {}, 
            _value = _hash();
            
        if (_msie) {
            _version = parseFloat(_agent.substr(_agent.indexOf('MSIE') + 4));
            if (_d.documentMode && _d.documentMode != _version) {
                _version = _d.documentMode != 8 ? 7 : 8;
            }
            $(document).bind('propertychange', function() {
                if (_d.title != _title && _d.title.indexOf('#' + _hash()) != -1) {
                    _d.title = _title;
                }
            });
        }
        
        _supported = 
            (_mozilla && _version >= 1) || 
            (_msie && _version >= 6) ||
            (_opera && _version >= 9.5) ||
            (_safari && _version >= 312);
            
        if (_supported) {
        
            for (var i = 1; i < _length; i++) {
                _stack.push('');
            }
            
            _stack.push(_value);
        
            if (_msie && _l.hash != _value) {
                _l.hash = '#' + _local(_crawl(_value, TRUE), TRUE);
            }
            
            if (_opera) {
                history.navigationMode = 'compatible'; 
            }
            
            if (_url && _qi != -1) {
                var param, params = _url.substr(_qi + 1).split('&');
                for (i = 0; i < params.length; i++) {
                    param = params[i].split('=');
                    if (/^(autoUpdate|crawlable|history|strict|wrap)$/.test(param[0])) {
                        _opts[param[0]] = (isNaN(param[1]) ? /^(true|yes)$/i.test(param[1]) : (parseInt(param[1], 10) !== 0));
                    }
                    if (/^tracker$/.test(param[0])) {
                        _opts[param[0]] = param[1];
                    }
                }
            }

            if (document.readyState == 'complete') {
                _load();
            }
            $(_load);
            $(window).bind('unload', _unload);
            
        } else if ((!_supported && _hash() != '') || 
            (_safari && _version < 418 && _hash() != '' && _l.search != '')) {
            _d.open();
            _d.write('<html><head><meta http-equiv="refresh" content="0;url=' + 
                encodeURI(_l.href.substr(0, _l.href.indexOf('#'))) + '" /></head></html>');
            _d.close();
        } else {
            _track();
        }

        return {
            bind: function(type, data, fn) {
                return _bind(type, data, fn);
            },
            init: function(fn) {
                return _bind(INIT, fn);
            },
            change: function(fn) {
                return _bind(CHANGE, fn);
            },
            internalChange: function(fn) {
                return _bind(INTERNAL_CHANGE, fn);
            },
            externalChange: function(fn) {
                return _bind(EXTERNAL_CHANGE, fn);
            },
            baseURL: function() {
                var url = _l.href;
                if (url.indexOf('#') != -1) {
                    url = url.substr(0, url.indexOf('#'));
                }
                if (/\/$/.test(url)) {
                    url = url.substr(0, url.length - 1);
                }
                return url;
            },
            autoUpdate: function(value) {
                if (value !== undefined) {
                    _opts.autoUpdate = value;
                    return this;
                }
                return _opts.autoUpdate;
            },
            crawlable: function(value) {
                if (value !== undefined) {
                    _opts.crawlable = value;
                    return this;
                }
                return _opts.crawlable;
            },
            history: function(value) {
                if (value !== undefined) {
                    _opts.history = value;
                    return this;
                }
                return _opts.history;
            },
            strict: function(value) {
                if (value !== undefined) {
                    _opts.strict = value;
                    return this;
                }
                return _opts.strict;
            },
            tracker: function(value) {
                if (value !== undefined) {
                    _opts.tracker = value;
                    return this;
                }
                return _opts.tracker;
            },
            wrap: function(value) {
                if (value !== undefined) {
                    _opts.wrap = value;
                    return this;
                }
                return _opts.wrap;
            },
            update: function() {
                _updating = TRUE;
                this.value(_value);
                _updating = FALSE;
                return this;
            },
            title: function(value) {
                if (value !== undefined) {
                    value = _dc(value);
                    _st(function() {
                        _title = _d.title = value;
                        if (_juststart && _frame && _frame.contentWindow && _frame.contentWindow.document) {
                            _frame.contentWindow.document.title = value;
                            _juststart = FALSE;
                        }
                        if (!_justset && _mozilla) {
                            _l.replace(_l.href.indexOf('#') != -1 ? _l.href : _l.href + '#');
                        }
                        _justset = FALSE;
                    }, 50);
                    return this;
                }
                return _d.title;
            },
            value: function(value) {
                if (value !== undefined) {
                    value = _ec(_dc(_strict(value, TRUE)));
                    if (value == '/') {
                        value = '';
                    }
                    if (_value == value && !_updating) {
                        return;
                    }
                    _justset = TRUE;
                    _value = value;
                    if (_opts.autoUpdate || _updating) {
                        _silent = TRUE;
                        _update(TRUE);
                        _stack[_h.length] = _value;
                        if (_safari) {
                            if (_opts.history) {
                                _l[ID][_l.pathname] = _stack.toString();
                                _length = _h.length + 1;
                                if (_version < 418) {
                                    if (_l.search == '') {
                                        _form.action = '#' + _crawl(_value, TRUE);
                                        _form.submit();
                                    }
                                } else if (_version < 523 || _value == '') {
                                    var evt = _d.createEvent('MouseEvents');
                                    evt.initEvent('click', TRUE, TRUE);
                                    var anchor = _d.createElement('a');
                                    anchor.href = '#' + _crawl(_value, TRUE);
                                    anchor.dispatchEvent(evt);                
                                } else {
                                    _l.hash = '#' + _crawl(_value, TRUE);
                                }
                            } else {
                                _l.replace('#' + _crawl(_value, TRUE));
                            }
                        } else if (_value != _hash()) {
                            if (_opts.history) {
                                _l.hash = '#' + _local(_crawl(_value, TRUE), TRUE);
                            } else {
                                _l.replace('#' + _crawl(_value, TRUE));
                            }
                        }
                        if ((_msie && _version < 8) && _opts.history) {
                            _st(_html, 50);
                        }
                        if (_safari) {
                            _st(function(){ _silent = FALSE; }, 1);
                        } else {
                            _silent = FALSE;
                        }
                    }
                    return this;
                }
                if (!_supported) {
                    return null;
                }
                return _dc(_strict(_local(_value, FALSE), FALSE));
            },
            path: function(value) {
                if (value !== undefined) {
                    var qs = this.queryString(),
                        hash = this.hash();
                    this.value(value + (qs ? '?' + qs : '') + (hash ? '#' + hash : ''));
                    return this;
                }
                return this.value().split('#')[0].split('?')[0];
            },
            queryString: function(value) {
                if (value !== undefined) {
                    var hash = this.hash();
                    this.value(this.path() + (value ? '?' + value : '') + (hash ? '#' + hash : ''));
                    return this;
                }
                var arr = this.value().split('?');
                return arr.slice(1, arr.length).join('?').split('#')[0];
            },
            parameter: function(name, value, append) {
                var i, params;
                if (value !== undefined) {
                    var names = this.parameterNames();
                    params = [];
                    for (i = 0; i < names.length; i++) {
                        var n = names[i],
                            v = this.parameter(n);
                        if (typeof v == 'string') {
                            v = [v];
                        }
                        if (n == name) {
                            v = (value === null || value == '') ? [] : 
                                (append ? v.concat([value]) : [value]);
                        }
                        for (var j = 0; j < v.length; j++) {
                            params.push(n + '=' + v[j]);
                        }
                    }
                    if ($.inArray(name, names) == -1 && value !== null && value != '') {
                        params.push(name + '=' + value);
                    }
                    this.queryString(params.join('&'));
                    return this;
                }
                value = this.queryString();
                if (value) {
                    params = value.split('&');
                    var r = [];
                    for (i = 0; i < params.length; i++) {
                        var p = params[i].split('=');
                        if (p[0] == name) {
                            r.push(p[1]);
                        }
                    }
                    if (r.length !== 0) {
                        return r.length != 1 ? r : r[0];
                    }
                }
            },
            pathNames: function() {
                var path = this.path(),
                    names = path.replace(/\/{2,9}/g, '/').split('/');
                if (path.substr(0, 1) == '/' || path.length === 0) {
                    names.splice(0, 1);
                }
                if (path.substr(path.length - 1, 1) == '/') {
                    names.splice(names.length - 1, 1);
                }
                return names;
            },
            parameterNames: function() {
                var qs = this.queryString(),
                    names = [];
                if (qs && qs.indexOf('=') != -1) {
                    var params = qs.split('&');
                    for (var i = 0; i < params.length; i++) {
                        var name = params[i].split('=')[0];
                        if ($.inArray(name, names) == -1) {
                            names.push(name);
                        }
                    }
                }
                return names;
            },
            hash: function(value) {
                if (value !== undefined) {
                    this.value(this.value().split('#')[0] + (value ? '#' + value : ''));
                    return this;
                }
                var arr = this.value().split('#');
                return arr.slice(1, arr.length).join('#');
            }            
        };
        
    })();
    
    $.fn.address = function(fn) {
        var f = function() {
            if ($(this).is('a')) {
                var value = fn ? fn.call(this) : 
                    /address:/.test($(this).attr('rel')) ? $(this).attr('rel').split('address:')[1].split(' ')[0] : 
                    $(this).attr('href').replace(/^#\!?/, '');
                $.address.value(value);
                return false;
            }
        };
        $(this).click(f).live('click', f);
        $(this).live('submit', function() {
            if ($(this).is('form')) {
                var value = fn ? fn.call(this) : $(this).attr('action') + '?' + $(this).serialize();
                $.address.value(value);
                return false;
            }
        });
        return this;
    };
    
}(jQuery));;

/**
 * A progressbar object. Initialized with the given id. Must be inserted into
 * the DOM afterwards through progressBar.element.
 *
 * method is the function which will perform the HTTP request to get the
 * progress bar state. Either "GET" or "POST".
 *
 * e.g. pb = new progressBar('myProgressBar');
 *      some_element.appendChild(pb.element);
 */
Drupal.progressBar = function (id, updateCallback, method, errorCallback) {
  var pb = this;
  this.id = id;
  this.method = method || "GET";
  this.updateCallback = updateCallback;
  this.errorCallback = errorCallback;

  this.element = document.createElement('div');
  this.element.id = id;
  this.element.className = 'progress';
  $(this.element).html('<div class="bar"><div class="filled"></div></div>'+
                       '<div class="percentage"></div>'+
                       '<div class="message">&nbsp;</div>');
};

/**
 * Set the percentage and status message for the progressbar.
 */
Drupal.progressBar.prototype.setProgress = function (percentage, message) {
  if (percentage >= 0 && percentage <= 100) {
    $('div.filled', this.element).css('width', percentage +'%');
    $('div.percentage', this.element).html(percentage +'%');
  }
  $('div.message', this.element).html(message);
  if (this.updateCallback) {
    this.updateCallback(percentage, message, this);
  }
};

/**
 * Start monitoring progress via Ajax.
 */
Drupal.progressBar.prototype.startMonitoring = function (uri, delay) {
  this.delay = delay;
  this.uri = uri;
  this.sendPing();
};

/**
 * Stop monitoring progress via Ajax.
 */
Drupal.progressBar.prototype.stopMonitoring = function () {
  clearTimeout(this.timer);
  // This allows monitoring to be stopped from within the callback
  this.uri = null;
};

/**
 * Request progress data from server.
 */
Drupal.progressBar.prototype.sendPing = function () {
  if (this.timer) {
    clearTimeout(this.timer);
  }
  if (this.uri) {
    var pb = this;
    // When doing a post request, you need non-null data. Otherwise a
    // HTTP 411 or HTTP 406 (with Apache mod_security) error may result.
    $.ajax({
      type: this.method,
      url: this.uri,
      data: '',
      dataType: 'json',
      success: function (progress) {
        // Display errors
        if (progress.status == 0) {
          pb.displayError(progress.data);
          return;
        }
        // Update display
        pb.setProgress(progress.percentage, progress.message);
        // Schedule next timer
        pb.timer = setTimeout(function() { pb.sendPing(); }, pb.delay);
      },
      error: function (xmlhttp) {
        pb.displayError(Drupal.ahahError(xmlhttp, pb.uri));
      }
    });
  }
};

/**
 * Display errors on the page.
 */
Drupal.progressBar.prototype.displayError = function (string) {
  var error = document.createElement('div');
  error.className = 'error';
  error.innerHTML = string;

  $(this.element).before(error).hide();

  if (this.errorCallback) {
    this.errorCallback(this);
  }
};
;

/**
 * Attaches the autocomplete behavior to all required fields
 */
Drupal.behaviors.autocomplete = function (context) {
  var acdb = [];
  $('input.autocomplete:not(.autocomplete-processed)', context).each(function () {
    var uri = this.value;
    if (!acdb[uri]) {
      acdb[uri] = new Drupal.ACDB(uri);
    }
    var input = $('#' + this.id.substr(0, this.id.length - 13))
      .attr('autocomplete', 'OFF')[0];
    $(input.form).submit(Drupal.autocompleteSubmit);
    new Drupal.jsAC(input, acdb[uri]);
    $(this).addClass('autocomplete-processed');
  });
};

/**
 * Prevents the form from submitting if the suggestions popup is open
 * and closes the suggestions popup when doing so.
 */
Drupal.autocompleteSubmit = function () {
  return $('#autocomplete').each(function () {
    this.owner.hidePopup();
  }).size() == 0;
};

/**
 * An AutoComplete object
 */
Drupal.jsAC = function (input, db) {
  var ac = this;
  this.input = input;
  this.db = db;

  $(this.input)
    .keydown(function (event) { return ac.onkeydown(this, event); })
    .keyup(function (event) { ac.onkeyup(this, event); })
    .blur(function () { ac.hidePopup(); ac.db.cancel(); });

};

/**
 * Handler for the "keydown" event
 */
Drupal.jsAC.prototype.onkeydown = function (input, e) {
  if (!e) {
    e = window.event;
  }
  switch (e.keyCode) {
    case 40: // down arrow
      this.selectDown();
      return false;
    case 38: // up arrow
      this.selectUp();
      return false;
    default: // all other keys
      return true;
  }
};

/**
 * Handler for the "keyup" event
 */
Drupal.jsAC.prototype.onkeyup = function (input, e) {
  if (!e) {
    e = window.event;
  }
  switch (e.keyCode) {
    case 16: // shift
    case 17: // ctrl
    case 18: // alt
    case 20: // caps lock
    case 33: // page up
    case 34: // page down
    case 35: // end
    case 36: // home
    case 37: // left arrow
    case 38: // up arrow
    case 39: // right arrow
    case 40: // down arrow
      return true;

    case 9:  // tab
    case 13: // enter
    case 27: // esc
      this.hidePopup(e.keyCode);
      return true;

    default: // all other keys
      if (input.value.length > 0)
        this.populatePopup();
      else
        this.hidePopup(e.keyCode);
      return true;
  }
};

/**
 * Puts the currently highlighted suggestion into the autocomplete field
 */
Drupal.jsAC.prototype.select = function (node) {
  this.input.value = node.autocompleteValue;
};

/**
 * Highlights the next suggestion
 */
Drupal.jsAC.prototype.selectDown = function () {
  if (this.selected && this.selected.nextSibling) {
    this.highlight(this.selected.nextSibling);
  }
  else {
    var lis = $('li', this.popup);
    if (lis.size() > 0) {
      this.highlight(lis.get(0));
    }
  }
};

/**
 * Highlights the previous suggestion
 */
Drupal.jsAC.prototype.selectUp = function () {
  if (this.selected && this.selected.previousSibling) {
    this.highlight(this.selected.previousSibling);
  }
};

/**
 * Highlights a suggestion
 */
Drupal.jsAC.prototype.highlight = function (node) {
  if (this.selected) {
    $(this.selected).removeClass('selected');
  }
  $(node).addClass('selected');
  this.selected = node;
};

/**
 * Unhighlights a suggestion
 */
Drupal.jsAC.prototype.unhighlight = function (node) {
  $(node).removeClass('selected');
  this.selected = false;
};

/**
 * Hides the autocomplete suggestions
 */
Drupal.jsAC.prototype.hidePopup = function (keycode) {
  // Select item if the right key or mousebutton was pressed
  if (this.selected && ((keycode && keycode != 46 && keycode != 8 && keycode != 27) || !keycode)) {
    this.input.value = this.selected.autocompleteValue;
  }
  // Hide popup
  var popup = this.popup;
  if (popup) {
    this.popup = null;
    $(popup).fadeOut('fast', function() { $(popup).remove(); });
  }
  this.selected = false;
};

/**
 * Positions the suggestions popup and starts a search
 */
Drupal.jsAC.prototype.populatePopup = function () {
  // Show popup
  if (this.popup) {
    $(this.popup).remove();
  }
  this.selected = false;
  this.popup = document.createElement('div');
  this.popup.id = 'autocomplete';
  this.popup.owner = this;
  $(this.popup).css({
    marginTop: this.input.offsetHeight +'px',
    width: (this.input.offsetWidth - 4) +'px',
    display: 'none'
  });
  $(this.input).before(this.popup);

  // Do search
  this.db.owner = this;
  this.db.search(this.input.value);
};

/**
 * Fills the suggestion popup with any matches received
 */
Drupal.jsAC.prototype.found = function (matches) {
  // If no value in the textfield, do not show the popup.
  if (!this.input.value.length) {
    return false;
  }

  // Prepare matches
  var ul = document.createElement('ul');
  var ac = this;
  for (key in matches) {
    var li = document.createElement('li');
    $(li)
      .html('<div>'+ matches[key] +'</div>')
      .mousedown(function () { ac.select(this); })
      .mouseover(function () { ac.highlight(this); })
      .mouseout(function () { ac.unhighlight(this); });
    li.autocompleteValue = key;
    $(ul).append(li);
  }

  // Show popup with matches, if any
  if (this.popup) {
    if (ul.childNodes.length > 0) {
      $(this.popup).empty().append(ul).show();
    }
    else {
      $(this.popup).css({visibility: 'hidden'});
      this.hidePopup();
    }
  }
};

Drupal.jsAC.prototype.setStatus = function (status) {
  switch (status) {
    case 'begin':
      $(this.input).addClass('throbbing');
      break;
    case 'cancel':
    case 'error':
    case 'found':
      $(this.input).removeClass('throbbing');
      break;
  }
};

/**
 * An AutoComplete DataBase object
 */
Drupal.ACDB = function (uri) {
  this.uri = uri;
  this.delay = 300;
  this.cache = {};
};

/**
 * Performs a cached and delayed search
 */
Drupal.ACDB.prototype.search = function (searchString) {
  var db = this;
  this.searchString = searchString;

  // See if this key has been searched for before
  if (this.cache[searchString]) {
    return this.owner.found(this.cache[searchString]);
  }

  // Initiate delayed search
  if (this.timer) {
    clearTimeout(this.timer);
  }
  this.timer = setTimeout(function() {
    db.owner.setStatus('begin');

    // Ajax GET request for autocompletion
    $.ajax({
      type: "GET",
      url: db.uri +'/'+ Drupal.encodeURIComponent(searchString),
      dataType: 'json',
      success: function (matches) {
        if (typeof matches['status'] == 'undefined' || matches['status'] != 0) {
          db.cache[searchString] = matches;
          // Verify if these are still the matches the user wants to see
          if (db.searchString == searchString) {
            db.owner.found(matches);
          }
          db.owner.setStatus('found');
        }
      },
      error: function (xmlhttp) {
        alert(Drupal.ahahError(xmlhttp, db.uri));
      }
    });
  }, this.delay);
};

/**
 * Cancels the current autocomplete request
 */
Drupal.ACDB.prototype.cancel = function() {
  if (this.owner) this.owner.setStatus('cancel');
  if (this.timer) clearTimeout(this.timer);
  this.searchString = '';
};
;

/**
 * Toggle the visibility of a fieldset using smooth animations
 */
Drupal.toggleFieldset = function(fieldset) {
  if ($(fieldset).is('.collapsed')) {
    // Action div containers are processed separately because of a IE bug
    // that alters the default submit button behavior.
    var content = $('> div:not(.action)', fieldset);
    $(fieldset).removeClass('collapsed');
    content.hide();
    content.slideDown( {
      duration: 'fast',
      easing: 'linear',
      complete: function() {
        Drupal.collapseScrollIntoView(this.parentNode);
        this.parentNode.animating = false;
        $('div.action', fieldset).show();
      },
      step: function() {
        // Scroll the fieldset into view
        Drupal.collapseScrollIntoView(this.parentNode);
      }
    });
  }
  else {
    $('div.action', fieldset).hide();
    var content = $('> div:not(.action)', fieldset).slideUp('fast', function() {
      $(this.parentNode).addClass('collapsed');
      this.parentNode.animating = false;
    });
  }
};

/**
 * Scroll a given fieldset into view as much as possible.
 */
Drupal.collapseScrollIntoView = function (node) {
  var h = self.innerHeight || document.documentElement.clientHeight || $('body')[0].clientHeight || 0;
  var offset = self.pageYOffset || document.documentElement.scrollTop || $('body')[0].scrollTop || 0;
  var posY = $(node).offset().top;
  var fudge = 55;
  if (posY + node.offsetHeight + fudge > h + offset) {
    if (node.offsetHeight > h) {
      window.scrollTo(0, posY);
    } else {
      window.scrollTo(0, posY + node.offsetHeight - h + fudge);
    }
  }
};

Drupal.behaviors.collapse = function (context) {
  $('fieldset.collapsible > legend:not(.collapse-processed)', context).each(function() {
    var fieldset = $(this.parentNode);
    // Expand if there are errors inside
    if ($('input.error, textarea.error, select.error', fieldset).size() > 0) {
      fieldset.removeClass('collapsed');
    }

    // Turn the legend into a clickable link and wrap the contents of the fieldset
    // in a div for easier animation
    var text = this.innerHTML;
      $(this).empty().append($('<a href="#">'+ text +'</a>').click(function() {
        var fieldset = $(this).parents('fieldset:first')[0];
        // Don't animate multiple times
        if (!fieldset.animating) {
          fieldset.animating = true;
          Drupal.toggleFieldset(fieldset);
        }
        return false;
      }))
      .after($('<div class="fieldset-wrapper"></div>')
      .append(fieldset.children(':not(legend):not(.action)')))
      .addClass('collapse-processed');
  });
};
;

Drupal.behaviors.textarea = function(context) {
  $('textarea.resizable:not(.textarea-processed)', context).each(function() {
    // Avoid non-processed teasers.
    if ($(this).is(('textarea.teaser:not(.teaser-processed)'))) {
      return false;  
    }
    var textarea = $(this).addClass('textarea-processed'), staticOffset = null;

    // When wrapping the text area, work around an IE margin bug.  See:
    // http://jaspan.com/ie-inherited-margin-bug-form-elements-and-haslayout
    $(this).wrap('<div class="resizable-textarea"><span></span></div>')
      .parent().append($('<div class="grippie"></div>').mousedown(startDrag));

    var grippie = $('div.grippie', $(this).parent())[0];
    grippie.style.marginRight = (grippie.offsetWidth - $(this)[0].offsetWidth) +'px';

    function startDrag(e) {
      staticOffset = textarea.height() - e.pageY;
      textarea.css('opacity', 0.25);
      $(document).mousemove(performDrag).mouseup(endDrag);
      return false;
    }

    function performDrag(e) {
      textarea.height(Math.max(32, staticOffset + e.pageY) + 'px');
      return false;
    }

    function endDrag(e) {
      $(document).unbind("mousemove", performDrag).unbind("mouseup", endDrag);
      textarea.css('opacity', 1);
    }
  });
};
;
// $Id: ahah_helper.js,v 1.1 2008/08/29 18:58:21 wimleers Exp $

(function($) {

if (Drupal.jsEnabled) {
  $(document).ready(function() {
    if (Drupal.ahah != undefined) {

/**
 * Override of Drupal.ahah.prototype.success. The only difference is that we
 * allow for new Drupal.settings.
 */
Drupal.ahah.prototype.success = function (response, status) {
  var wrapper = $(this.wrapper);
  var form = $(this.element).parents('form');
  // Manually insert HTML into the jQuery object, using $() directly crashes
  // Safari with long string lengths. http://dev.jquery.com/ticket/1152
  var new_content = $('<div></div>').html(response.data);

  // Restore the previous action and target to the form.
  form.attr('action', this.form_action);
  this.form_target ? form.attr('target', this.form_target) : form.removeAttr('target');
  this.form_encattr ? form.attr('target', this.form_encattr) : form.removeAttr('encattr');

  // Remove the progress element.
  if (this.progress.element) {
    $(this.progress.element).remove();
  }
  if (this.progress.object) {
    this.progress.object.stopMonitoring();
  }
  $(this.element).removeClass('progress-disabled').attr('disabled', false);

  // Add the new content to the page.
  Drupal.freezeHeight();
  if (this.method == 'replace') {
    wrapper.empty().append(new_content);
  }
  else {
    wrapper[this.method](new_content);
  }

  // Immediately hide the new content if we're using any effects.
  if (this.showEffect != 'show') {
    new_content.hide();
  }

  // Determine what effect use and what content will receive the effect, then
  // show the new content. For browser compatibility, Safari is excluded from
  // using effects on table rows.
  if (($.browser.safari && $("tr.ahah-new-content", new_content).size() > 0)) {
    new_content.show();
  }
  else if ($('.ahah-new-content', new_content).size() > 0) {
    $('.ahah-new-content', new_content).hide();
    new_content.show();
    $(".ahah-new-content", new_content)[this.showEffect](this.showSpeed);
  }
  else if (this.showEffect != 'show') {
    new_content[this.showEffect](this.showSpeed);
  }

  // Merge in new and changed settings, if any.
  if (response.settings) {
    $.extend(Drupal.settings, response.settings);
  }

  // Attach all javascript behaviors to the new content, if it was successfully
  // added to the page, this if statement allows #ahah[wrapper] to be optional.
  if (new_content.parents('html').length > 0) {
    Drupal.attachBehaviors(new_content);
  }

  Drupal.unfreezeHeight();
};

    }
  });
}

})(jQuery);
;
// $Id: googleanalytics.js,v 1.9.2.4 2010/09/19 11:39:20 hass Exp $

$(document).ready(function() {

  // Attach onclick event to document only and catch clicks on all elements.
  $(document.body).click(function(event) {
    // Catch only the first parent link of a clicked element.
    $(event.target).parents("a:first,area:first").andSelf().filter("a,area").each(function() {

      var ga = Drupal.settings.googleanalytics;
      // Expression to check for absolute internal links.
      var isInternal = new RegExp("^(https?):\/\/" + window.location.host, "i");
      // Expression to check for special links like gotwo.module /go/* links.
      var isInternalSpecial = new RegExp("(\/go\/.*)$", "i");
      // Expression to check for download links.
      var isDownload = new RegExp("\\.(" + ga.trackDownloadExtensions + ")$", "i");

      // Is the clicked URL internal?
      if (isInternal.test(this.href)) {
        // Is download tracking activated and the file extension configured for download tracking?
        if (ga.trackDownload && isDownload.test(this.href)) {
          // Download link clicked.
          var extension = isDownload.exec(this.href);
          _gaq.push(["_trackEvent", "Downloads", extension[1].toUpperCase(), this.href.replace(isInternal, '')]);
        }
        else if (isInternalSpecial.test(this.href)) {
          // Keep the internal URL for Google Analytics website overlay intact.
          _gaq.push(["_trackPageview", this.href.replace(isInternal, '')]);
        }
      }
      else {
        if (ga.trackMailto && $(this).is("a[href^=mailto:],area[href^=mailto:]")) {
          // Mailto link clicked.
          _gaq.push(["_trackEvent", "Mails", "Click", this.href.substring(7)]);
        }
        else if (ga.trackOutgoing && this.href) {
          // External link clicked.
          _gaq.push(["_trackEvent", "Outgoing links", "Click", this.href]);
        }
      }

    });
  });
});
;
// $Id: base.js,v 1.11.2.1 2010/03/10 20:08:58 merlinofchaos Exp $
/**
 * @file base.js
 *
 * Some basic behaviors and utility functions for Views.
 */

Drupal.Views = {};

/**
 * jQuery UI tabs, Views integration component
 */
Drupal.behaviors.viewsTabs = function (context) {
  $('#views-tabset:not(.views-processed)').addClass('views-processed').each(function() {
    new Drupal.Views.Tabs($(this), {selectedClass: 'active'});
  });

  $('a.views-remove-link')
    .addClass('views-processed')
    .click(function() {
      var id = $(this).attr('id').replace('views-remove-link-', '');
      $('#views-row-' + id).hide();
      $('#views-removed-' + id).attr('checked', true);
      return false;
    });
}

/**
 * For IE, attach some javascript so that our hovers do what they're supposed
 * to do.
 */
Drupal.behaviors.viewsHoverlinks = function() {
  if ($.browser.msie) {
    // If IE, attach a hover event so we can see our admin links.
    $("div.view:not(.views-hover-processed)").addClass('views-hover-processed').hover(
      function() {
        $('div.views-hide', this).addClass("views-hide-hover"); return true;
      },
      function(){
        $('div.views-hide', this).removeClass("views-hide-hover"); return true;
      }
    );
    $("div.views-admin-links:not(.views-hover-processed)")
      .addClass('views-hover-processed')
      .hover(
        function() {
          $(this).addClass("views-admin-links-hover"); return true;
        },
        function(){
          $(this).removeClass("views-admin-links-hover"); return true;
        }
      );
  }
}

/**
 * Helper function to parse a querystring.
 */
Drupal.Views.parseQueryString = function (query) {
  var args = {};
  var pos = query.indexOf('?');
  if (pos != -1) {
    query = query.substring(pos + 1);
  }
  var pairs = query.split('&');
  for(var i in pairs) {
    var pair = pairs[i].split('=');
    // Ignore the 'q' path argument, if present.
    if (pair[0] != 'q' && pair[1]) {
      args[pair[0]] = decodeURIComponent(pair[1].replace(/\+/g, ' '));
    }
  }
  return args;
};

/**
 * Helper function to return a view's arguments based on a path.
 */
Drupal.Views.parseViewArgs = function (href, viewPath) {
  var returnObj = {};
  var path = Drupal.Views.getPath(href);
  // Ensure we have a correct path.
  if (viewPath && path.substring(0, viewPath.length + 1) == viewPath + '/') {
    var args = decodeURIComponent(path.substring(viewPath.length + 1, path.length));
    returnObj.view_args = args;
    returnObj.view_path = path;
  }
  return returnObj;
};

/**
 * Strip off the protocol plus domain from an href.
 */
Drupal.Views.pathPortion = function (href) {
  // Remove e.g. http://example.com if present.
  var protocol = window.location.protocol;
  if (href.substring(0, protocol.length) == protocol) {
    // 2 is the length of the '//' that normally follows the protocol
    href = href.substring(href.indexOf('/', protocol.length + 2));
  }
  return href;
};

/**
 * Return the Drupal path portion of an href.
 */
Drupal.Views.getPath = function (href) {
  href = Drupal.Views.pathPortion(href);
  href = href.substring(Drupal.settings.basePath.length, href.length);
  // 3 is the length of the '?q=' added to the url without clean urls.
  if (href.substring(0, 3) == '?q=') {
    href = href.substring(3, href.length);
  }
  var chars = ['#', '?', '&'];
  for (i in chars) {
    if (href.indexOf(chars[i]) > -1) {
      href = href.substr(0, href.indexOf(chars[i]));
    }
  }
  return href;
};
;
// $Id: ajax_view.js,v 1.19.2.5 2010/03/25 18:25:28 merlinofchaos Exp $

/**
 * @file ajaxView.js
 *
 * Handles AJAX fetching of views, including filter submission and response.
 */

Drupal.Views.Ajax = Drupal.Views.Ajax || {};

/**
 * An ajax responder that accepts a packet of JSON data and acts appropriately.
 *
 * The following fields control behavior.
 * - 'display': Display the associated data in the view area.
 */
Drupal.Views.Ajax.ajaxViewResponse = function(target, response) {

  if (response.debug) {
    alert(response.debug);
  }

  var $view = $(target);

  // Check the 'display' for data.
  if (response.status && response.display) {
    var $newView = $(response.display);
    $view.replaceWith($newView);
    $view = $newView;
    Drupal.attachBehaviors($view.parent());
  }

  if (response.messages) {
    // Show any messages (but first remove old ones, if there are any).
    $view.find('.views-messages').remove().end().prepend(response.messages);
  }
};

/**
 * Ajax behavior for views.
 */
Drupal.behaviors.ViewsAjaxView = function() {
  if (Drupal.settings && Drupal.settings.views && Drupal.settings.views.ajaxViews) {
    var ajax_path = Drupal.settings.views.ajax_path;
    // If there are multiple views this might've ended up showing up multiple times.
    if (ajax_path.constructor.toString().indexOf("Array") != -1) {
      ajax_path = ajax_path[0];
    }
    $.each(Drupal.settings.views.ajaxViews, function(i, settings) {
      var view = '.view-dom-id-' + settings.view_dom_id;
      if (!$(view).size()) {
        // Backward compatibility: if 'views-view.tpl.php' is old and doesn't
        // contain the 'view-dom-id-#' class, we fall back to the old way of
        // locating the view:
        view = '.view-id-' + settings.view_name + '.view-display-id-' + settings.view_display_id;
      }


      // Process exposed filter forms.
      $('form#views-exposed-form-' + settings.view_name.replace(/_/g, '-') + '-' + settings.view_display_id.replace(/_/g, '-'))
      .filter(':not(.views-processed)')
      .each(function () {
        // remove 'q' from the form; it's there for clean URLs
        // so that it submits to the right place with regular submit
        // but this method is submitting elsewhere.
        $('input[name=q]', this).remove();
        var form = this;
        // ajaxSubmit doesn't accept a data argument, so we have to
        // pass additional fields this way.
        $.each(settings, function(key, setting) {
          $(form).append('<input type="hidden" name="'+ key + '" value="'+ setting +'"/>');
        });
      })
      .addClass('views-processed')
      .submit(function () {
        $('input[type=submit], button', this).after('<span class="views-throbbing">&nbsp</span>');
        var object = this;
        $(this).ajaxSubmit({
          url: ajax_path,
          type: 'GET',
          success: function(response) {
            // Call all callbacks.
            if (response.__callbacks) {
              $.each(response.__callbacks, function(i, callback) {
                eval(callback)(view, response);
              });
              $('.views-throbbing', object).remove();
            }
          },
          error: function(xhr) { Drupal.Views.Ajax.handleErrors(xhr, ajax_path); $('.views-throbbing', object).remove(); },
          dataType: 'json'
        });

        return false;
      });

      $(view).filter(':not(.views-processed)')
        // Don't attach to nested views. Doing so would attach multiple behaviors
        // to a given element.
        .filter(function() {
          // If there is at least one parent with a view class, this view
          // is nested (e.g., an attachment). Bail.
          return !$(this).parents('.view').size();
        })
        .each(function() {
          // Set a reference that will work in subsequent calls.
          var target = this;
          $(this)
            .addClass('views-processed')
            // Process pager, tablesort, and attachment summary links.
            .find('ul.pager > li > a, th.views-field a, .attachment .views-summary a')
            .each(function () {
              var viewData = { 'js': 1 };
              // Construct an object using the settings defaults and then overriding
              // with data specific to the link.
              $.extend(
                viewData,
                Drupal.Views.parseQueryString($(this).attr('href')),
                // Extract argument data from the URL.
                Drupal.Views.parseViewArgs($(this).attr('href'), settings.view_base_path),
                // Settings must be used last to avoid sending url aliases to the server.
                settings
              );
              $(this).click(function () {
                $.extend(viewData, Drupal.Views.parseViewArgs($(this).attr('href'), settings.view_base_path));
                $(this).addClass('views-throbbing');
                $.ajax({
                  url: ajax_path,
                  type: 'GET',
                  data: viewData,
                  success: function(response) {
                    $(this).removeClass('views-throbbing');
                    // Scroll to the top of the view. This will allow users
                    // to browse newly loaded content after e.g. clicking a pager
                    // link.
                    var offset = $(target).offset();
                    // We can't guarantee that the scrollable object should be
                    // the body, as the view could be embedded in something
                    // more complex such as a modal popup. Recurse up the DOM
                    // and scroll the first element that has a non-zero top.
                    var scrollTarget = target;
                    while ($(scrollTarget).scrollTop() == 0 && $(scrollTarget).parent()) {
                      scrollTarget = $(scrollTarget).parent()
                    }
                    // Only scroll upward
                    if (offset.top - 10 < $(scrollTarget).scrollTop()) {
                      $(scrollTarget).animate({scrollTop: (offset.top - 10)}, 500);
                    }
                    // Call all callbacks.
                    if (response.__callbacks) {
                      $.each(response.__callbacks, function(i, callback) {
                        eval(callback)(target, response);
                      });
                    }
                  },
                  error: function(xhr) { $(this).removeClass('views-throbbing'); Drupal.Views.Ajax.handleErrors(xhr, ajax_path); },
                  dataType: 'json'
                });

                return false;
              });
            }); // .each function () {
      }); // $view.filter().each
    }); // .each Drupal.settings.views.ajaxViews
  } // if
};
;
var activeTab = 'C';
var tab_blog_init = false;
var tab_articles_init = false;

function load_new_pages(tab, view){
    var response=new Object();
    response.data='<p class="center"><img src="'+Drupal.settings.basePath+'sites/all/themes/meacar/images/AnimatedCarLoadingStatus.gif" alt=""/></p>';
    output_find_now(response);
    $.getJSON(Drupal.settings.basePath+"?q="+view, null, ajaxResponse);
    var li = $(".menu-tabs UL LI");
    
    for(i=0;i<li.length;i++){
        $("#"+li[i].id).removeClass("active");
        $("#"+li[i].id+" A").removeClass("active");
    }
    $("#"+tab).addClass("active");
    $("#"+tab+" A").addClass("active");
    
    
    if(tab == 'tab-articles' && !tab_articles_init) {
        tab_articles_init = true;
        $.getJSON(Drupal.settings.basePath+"?q=meacars/ajax/block/0", null, output_block_now);
        $.getJSON(Drupal.settings.basePath+"?q=meacars/ajax/viewblock/magazine_users_list-block_1", null, output_block_now);   
    }
    if(tab == 'tab-blog' && !tab_blog_init) {
        tab_blog_init = true;
        $.getJSON(Drupal.settings.basePath + "meacars/ajax/block/1", null, output_block_now);
        $.getJSON(Drupal.settings.basePath + "meacars/ajax/viewblock/magazine_users_list-block_2", null, output_block_now);
    }
    return false;
}
function load_node_pages(tab, nid){
  $.address.value('/');
  $.address.parameter('tab', tab, true);
  $.address.parameter('nid', nid, true);
  $.address.parameter('a', "n", true);
  $.address.update();
  return false;
}

function loadNode(tab, nid) {
    var response=new Object();
    response.data='<p class="center"><img src="'+Drupal.settings.basePath+'sites/all/themes/meacar/images/AnimatedCarLoadingStatus.gif" alt=""/></p>';
    output_find_now(response);
    $.getJSON(Drupal.settings.basePath+"?q=meacars/ajax/node/"+nid, null, ajaxResponseNode);

    if( tab == 'tab-articles' ){
      showArticlesBlocks();
    }
    else {
      showBlogBlocks();
    }

    var li = $(".menu-tabs UL LI");
    
    for(i=0;i<li.length;i++){
        $("#"+li[i].id).removeClass("active");
        $("#"+li[i].id+" A").removeClass("active");
    }
    $("#"+tab).addClass("active");
    $("#"+tab+" A").addClass("active");
}

function enableTab(tab) {
    var li = $(".menu-tabs UL LI");    
    for(i=0;i<li.length;i++){
        $("#"+li[i].id).removeClass("active");
        $("#"+li[i].id+" A").removeClass("active");
    }
    $("#"+tab).addClass("active");
    $("#"+tab+" A").addClass("active");
}

function output_block_now(response) {
  $('.sidebar-left').prepend(response.data);      
  Drupal.attachBehaviors();
  return false;
}
function output_more_block(response) {
  $("#main").append(response.data);
  Drupal.attachBehaviors();

}

function ajaxResponseNode(response){
  /*$("#main").html(response.data + '<br clear="all"/><fb:comments css="http://www.meacars.com/sites/all/themes/meacar/fb.css?35"></fb:comments>');
  $.extend(Drupal.settings, response.settings);
  Drupal.attachBehaviors();
  FB.Facebook.init("c6e2e204dc703b56548d144dc8a77844", "/sites/all/modules/fbconnect/xd_receiver.html");
  */
  
  if( response.name == 'articles' ) {
    $.getJSON(Drupal.settings.basePath+"?q=meacars/ajax/block/3", null, output_more_block);   
  }

  if( response.name == 'blogs' ) {
    $.getJSON(Drupal.settings.basePath+"?q=meacars/ajax/block/2", null, output_more_block); 
  }

  return false;
  
}

function ajaxResponse(response){
  $("#main").html(response.data + '<br clear="all"/>');
  $.extend(Drupal.settings, response.settings);
  Drupal.attachBehaviors();
  
  if( response.name == 'articles' ) {
    $.getJSON(Drupal.settings.basePath+"?q=meacars/ajax/block/3", null, output_more_block);   
  }

  if( response.name == 'blogs' ) {
    $.getJSON(Drupal.settings.basePath+"?q=meacars/ajax/block/2", null, output_more_block); 
  }

  
  return false;
}

function load_new_view(tab, view, arg, display) {
    if ( display == null && view == 'blogs') {
        display = 'default';
    }
    if ( display == null) {
        display = 'default';
    }

    $.address.value('/');
    $.address.parameter('tab', tab, true);
    $.address.parameter('view', view, true);
    $.address.parameter('arg', arg, true);
    $.address.parameter('display', display, true);

    $.address.parameter('a', "ba", true);
    $.address.update();

    return false;
}

function loadblogarticletab(tab,view,arg, display) {
    var response=new Object();
    response.data='<p class="center"><img src="'+Drupal.settings.basePath+'sites/all/themes/meacar/images/AnimatedCarLoadingStatus.gif" alt=""/></p>';
    output_find_now(response);
    if( viewAJAX != undefined ){
		viewAJAX.abort();
    }
    viewAJAX = $.getJSON(Drupal.settings.basePath+"?q=meacars/ajax/loadview/"+view+"/"+display +"/"+arg, null, ajaxResponse);
    if( view == 'articles' || view == 'article_term'){
      showArticlesBlocks();
    }
    else {
      showBlogBlocks();
    }
    var li = $(".menu-tabs UL LI");
    
    for(i=0;i<li.length;i++){
        $("#"+li[i].id).removeClass("active");
        $("#"+li[i].id+" A").removeClass("active");
    }
    $("#"+tab).addClass("active");
    $("#"+tab+" A").addClass("active");

}



Drupal.behaviors.MeaCarsAjax = function (context) {
  /*
  $("form#views-exposed-form-articles-default #edit-submit").hide();
  $("form#views-exposed-form-articles-default .form-text").change(function() {      
  // Execute the submit function on the form
    $("form#iews-exposed-form-articles-default").submit();
  });
    */

  //$('#views-exposed-form-articles-default').hide();
  $('#block-views-magazine_users_list-block_1 input#filter-content-by-user').click( function () {
	  	  var markers='';
	  $.each($("#block-views-magazine_users_list-block_1 .views-field input"), function(i,v) {
		  if(this.checked==true) {
        markers += this.value+",";
      }
    });
    $('#edit-uid').val(markers);
    $('#views-exposed-form-articles-page-1').submit();
    $('#views-exposed-form-articles-default').submit();
    $('#views-exposed-form-article-term-page-1').submit();
    $('#views-exposed-form-article-term-page').submit();
    $.getJSON(Drupal.settings.basePath+"?q=meacars/ajax/block/3/"+markers, null, output_more_block_3);


  });

  $('#views-exposed-form-blogs-page-1').hide();
     $('#block-views-magazine_users_list-block_2 input#filter-content-by-user').click( function () {
	   var markers='';
	   $.each($("#block-views-magazine_users_list-block_2 .views-field input"), function(i,v) {
       if(this.checked==true) {
          markers += this.value+',';
       }
     });
     $('#edit-uid').val(markers);
     $('#views-exposed-form-blogs-default').submit();
     $('#views-exposed-form-blogs-page-1').submit();     
     $('#views-exposed-form-taxonomy-term-page-1').submit();
     $('#views-exposed-form-taxonomy-term-page').submit();
     $.getJSON(Drupal.settings.basePath+"?q=meacars/ajax/block/2/"+markers, null, output_more_block_2);
  });

  //remove articles and blog on Car click
  $('#link-cars').click(removeArticlesBlogs);
  $('#link-dealerships').click(removeArticlesBlogsDealer);
  //$('#link-articles').click(showArticlesBlocks);
  //$('#link-blog').click(showBlogBlocks);
   
}

function output_more_block_2(response) {
  $("#block-MeaCarsMagazine-2").html(response.data);
  //Drupal.attachBehaviors();

}
function output_more_block_3(response) {
  $("#block-MeaCarsMagazine-3").html(response.data);
  //Drupal.attachBehaviors();

}

function showBlogBlocks() {
  $("#tab-cars").removeClass("active");
  $("#tab-blog").addClass("active");
  if( $('#block-MeaCarsMagazine-1').length == 0 ) {    
    $.getJSON(Drupal.settings.basePath+"?q=meacars/ajax/block/1", null, output_block_blogs);
  }
  else {
    $('#block-MeaCarsMagazine-1').show();
    $('#block-views-magazine_users_list-block_2').show();
    $('#block-filter_side_bar-0').hide();
  }

  $('#block-MeaCarsMagazine-0').hide();
  $('#block-views-magazine_users_list-block_1').hide();
  $('#block-filter_side_bar-dealer').hide();

}

function output_block_blogs(response) {
  $('.sidebar-left').prepend(response.data);
  $.getJSON(Drupal.settings.basePath+"?q=meacars/ajax/viewblock/magazine_users_list-block_2", null, output_block_now);        
  $('#block-filter_side_bar-0').hide();
  $('#block-filter_side_bar-dealer').hide();

  Drupal.attachBehaviors();
  return false;
}

function showArticlesBlocks() {
  if( $('#block-MeaCarsMagazine-0').length == 0 && !tab_articles_init) {
    tab_articles_init = true;
    $.getJSON(Drupal.settings.basePath+"?q=meacars/ajax/block/0", null, output_block_article);
  }
  else {
    $('#block-MeaCarsMagazine-0').show();
    $('#block-views-magazine_users_list-block_1').show();
    $('#block-filter_side_bar-0').hide();    
  }


  $('#block-MeaCarsMagazine-1').hide();
  $('#block-views-magazine_users_list-block_2').hide();
  $('#block-filter_side_bar-dealer').hide();

}

function output_block_article(response) {
  $('.sidebar-left').prepend(response.data);
  $.getJSON(Drupal.settings.basePath+"?q=meacars/ajax/viewblock/magazine_users_list-block_1", null, output_block_now);
  $('#block-filter_side_bar-0').hide();
  activeTab = 'B';
  Drupal.attachBehaviors();
  return false;
}

function removeArticlesBlogs() {
  $('#block-MeaCarsMagazine-0').hide();
  $('#block-MeaCarsMagazine-1').hide();  
  $('#block-views-magazine_users_list-block_1').hide(); 
  $('#block-views-magazine_users_list-block_2').hide(); 
  $('#block-filter_side_bar-dealer').hide();
  $('#block-filter_side_bar-0').show();
  createYearSlider(111,26,1990,2011,1,1990,1990,2011,1,2011,'Year','/');
  createMileageSlider(111,26,0,150000,1,0,0,150000,1,150000,'Milage','/');		
  createPriceSlider(111,26,0,100000,1,0,0,100000,1,100000,'Price','/');
  activeTab ='C';
}
function removeArticlesBlogsDealer() {
  $('#block-MeaCarsMagazine-0').hide();
  $('#block-MeaCarsMagazine-1').hide();  
  $('#block-views-magazine_users_list-block_1').hide(); 
  $('#block-views-magazine_users_list-block_2').hide(); 
};
Drupal.behaviors.MeacarsDealershipFilter = function (context) {
    
}
function mdf_country_west(west){
  $("#mdf-filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', false);
  $("#filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', false);
  var array_west=west.split(";");
  for(i=0;i<array_west.length;i++){
    $("#edit-mdf-country-options-"+array_west[i]).attr('checked', true);
    $("#edit-country-options-"+array_west[i]).attr('checked', true);
  }
  mdf_country_select();  
  return false;                 
}  
function mdf_all_country(){
  $("#mdf-filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', true);
  $("#filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', true);
  mdf_country_select();
  return false;
}
function mdf_country_gulf(gulf){
  $("#mdf-filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', false);
  $("#filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', false);
  var array_gulf=gulf.split(";");
  for(i=0;i<array_gulf.length;i++){
    $("#edit-mdf-country-options-"+array_gulf[i]).attr('checked', true);
    $("#edit-country-options-"+array_gulf[i]).attr('checked', true);
  } 
    mdf_country_select(); 
    return false;                 
}             
function mdf_country_north(north){
  $("#mdf-filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', false);
  $("#filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', false);
  var array_north=north.split(";");
  for(i=0;i<array_north.length;i++){
    $("#edit-mdf-country-options-"+array_north[i]).attr('checked', true);
    $("#edit-country-options-"+array_north[i]).attr('checked', true);
  }  
    mdf_country_select();
    return false;                
}          
function mdf_country_x(){
  $("#mdf-filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', false);
  $("#filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', false);
  var dealerships=$("#filter-side-bar-listings INPUT[type='checkbox']");
  for(j=0;j<dealerships.length;j++){
    dealerships[j].checked=false;
    $("#"+dealerships[j].id+'-wrapper').hide();    
  }
    mdf_country_select();
    return false;          
}        
function mdf_country_central(center){
  $("#mdf-filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', false);
  $("#filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', false);
  var array_central=center.split(";");
  for(i=0;i<array_central.length;i++){
    $("#edit-mdf-country-options-"+array_central[i]).attr('checked', true);
    $("#edit-country-options-"+array_central[i]).attr('checked', true);
  }
  mdf_country_select();  
    return false;                 
}
/*filter dealerships by country when onlick() an item*/
function mdf_country_select() {
    var country = {};
    $("#mdf-filter-side-bar-country" + " INPUT[type='checkbox']").each(function() {
        if(this.checked) {
            country[this.value] = this.value;
        }
    });
    $.post(
        Drupal.settings.filterarea.url,
        country,
        function(response) {
            $('#filter-side-bar-area div.fieldset-wrapper div.form-checkboxes').html(response.data);
        },'json'
    );
}

function mdf_submit_find_now() {
    var area = {};
    $("#filter-side-bar-area" + " INPUT[type='checkbox']").each( function() {
        if(this.checked) {
            area[this.value] = this.value;
        }
    });
    var check_val = $('#sub-links a.active').html();
    if (check_val == 'Best Ratings') {
        //return load_dealership_page('tab-dealerships', 'userdealerships', '', 'sort=rating&order=desc');
        return load_dealership_page('tab-dealerships','userdealerships&sort=rating&order=desc');
    } else if (check_val == 'Most Cars') {
        //return load_dealership_page('tab-dealerships', 'userdealerships', '', 'sort=mostcars&order=desc')
        return load_dealership_page('tab-dealerships','userdealerships&sort=mostcars&order=desc')
    } else if (check_val == 'A to Z') {
        //return load_dealership_page('tab-dealerships', 'userdealerships', '', 'sort=alpha&order=desc')
        return load_dealership_page('tab-dealerships','userdealerships&sort=alpha&order=desc')
    } else {
        //return load_dealership_page('tab-dealerships', 'userdealerships', '', 'sort=node_created&order=desc');
        return load_dealership_page('tab-dealerships','userdealerships&sort=node_created&order=desc');
    }
    return false;
}

function mdf_all_area() {
   $("#filter-side-bar-area" + " INPUT[type='checkbox']").attr('checked', true);
   return false;    
}
function mdf_area_x() {
  $("#filter-side-bar-area" + " INPUT[type='checkbox']").attr('checked', false);
  return false;   
}
function mdf_default_filteration(){
  $("#mdf-filter-side-bar-country" + " INPUT[type='checkbox']").attr('checked', true);
  var country = {};
   $("#mdf-filter-side-bar-country" + " INPUT[type='checkbox']").each( function() {
       if(this.checked) {
        country[this.value] = this.value;   
       }
   });
   $.post(Drupal.settings.filterarea.url,country,function(response) { $('#filter-side-bar-area div.fieldset-wrapper div.form-checkboxes').html(response.data);  mdf_submit_find_now(); },'json');
  return false;
}
function mdf_pre_submit_find_now() {
    mdf_flag_sync();
    return mdf_submit_find_now();
}
function mdf_flag_sync() {
 var allselected = true;
 $('#all_middle_east').removeClass('middle_east_selected');   
 $("#mdf-filter-side-bar-country INPUT[type='checkbox']").each(function() {
   if ($('#edit-mdf-country-options-' + this.defaultValue)[0].checked == true) {
       var flag_id = $(this).parent().text().toLowerCase();
       flag_id = jQuery.trim(flag_id);
       if(flag_id == 'saudi arabia') {
           flag_id = 'saudi_arabia';
       }
       $('#'+flag_id).addClass('active_'+flag_id);
   }
   else {
       var flag_id = $(this).parent().text().toLowerCase();
       flag_id = jQuery.trim(flag_id);
       if(flag_id == 'saudi arabia') {
           flag_id = 'saudi_arabia';
       }
       $('#'+flag_id).removeClass('active_'+flag_id); 
    allselected = false;
   }
 });
 if( allselected ) {
   select_all_remove_class();
 }
};
var filter_cars_is_loaded = false;
var filter_dealerships_is_loaded = false;

Drupal.behaviors.MeacarsDealershipProfile = function (context) {
    $('.dealerships_users_page ul.pager li a').click( function() {
        var url = this.href;
        s1 = url.match("page=[1-9]") + " ";
        s2 = s1.split('=');
        var page = s2[1];
        var test = url.match("sort=[a-z]") + " ";
        var s_type = test.split('=');
        var chars ="\\s";
        var sort_optm = jQuery.trim(s_type[1]);
        var sort = '';
        if (sort_optm=='a') {
            sort='alpha';
        } else if(sort_optm=='m') {
            sort='mostcars';
        } else if(sort_optm=='r') {
            sort='rating';
        } else {
            sort='node_created';
        }

        load_dealership_page('tab-dealerships', "&q=userdealerships", page,sort);
        return false;
    });
    $('#link-dealerships').click( function() {
        //load_meacars_dealership_filter_block();
        return true;
    });
}
function load_dealership_page(tab, view, page, sort) {
    load_meacars_dealership_filter_block();
    var area = '';
    var allarea = true;

    $("#filter-side-bar-area" + " input[type='checkbox']").each( function() {
        if (this.checked) {
            area += this.value + ',';
        } else {
            allarea = false;
        }
    });
    $("#filter-side-bar-country" + " input[type='checkbox']").each( function() {
        if (!this.checked) {
            allarea = false;
        }
    });
    $("#mdf-filter-side-bar-country" + " input[type='checkbox']").each( function() {
        if (!this.checked) {
            allarea = false;
        }
    });

    var new_url = view;
    if (!allarea) {
        new_url += '&area_=' + area;
    }

    if (page != 0 && page != null) {
        new_url += "&page=" + page;
    }
    if (sort != 0 && sort != null) {
        new_url += "&sort=" + sort;
    }
    $.address.value('/');
    $.address.parameter('u', new_url, true);
    $.address.parameter('a', "d", true);
    if (areapage) {
        $.address.parameter('showarea', "1", true);
    }
    $.address.update();

    return false;
}

function loadDealers(new_url) {
    load_meacars_dealership_filter_block();
    var response=new Object();
    response.data='<p class="center"><img src="'+Drupal.settings.basePath+'sites/all/themes/meacar/images/AnimatedCarLoadingStatus.gif" alt=""/></p>';
    output_find_now(response);
    if (viewAJAX != undefined) {
        viewAJAX.abort();
    }
    
    viewAJAX = $.getJSON(Drupal.settings.basePath + new_url, null, ajaxResponse);
    removeArticlesBlogsDealer();
    $('.menu-tabs li, .menu-tabs a').removeClass("active");
    $("#tab-dealerships, #tab-dealerships a").addClass("active");
    Drupal.attachBehaviors(); 
}

function loadMagazines() {
    //load_meacars_magazines_filter_block();
    load_new_pages('tab-articles', 'articles');
    $('.block-filter_side_bar').hide();
    var response = new Object();
    response.data='<p class="center">'
        + '<img src="' + Drupal.settings.basePath
        + 'sites/all/themes/meacar/images/AnimatedCarLoadingStatus.gif" alt="" />'
        + '</p>';
    output_find_now(response);
    if (viewAJAX != undefined) {
        viewAJAX.abort();
    }
    viewAJAX = $.getJSON(Drupal.settings.basePath + "meacars/ajax/loadview/articles/default/", null, ajaxResponse);
    $('.menu-tabs li, .menu-tabs a').removeClass("active");
    $("#tab-articles, #tab-articles a").addClass("active");
    Drupal.attachBehaviors();
}

function loadBlogs() {
    load_new_pages('tab-blog', 'blogs');
    $('.block-filter_side_bar').hide();
    var response = new Object();
    response.data='<p class="center">'
        + '<img src="' + Drupal.settings.basePath
        + 'sites/all/themes/meacar/images/AnimatedCarLoadingStatus.gif" alt="" />'
        + '</p>';
    output_find_now(response);
    if (viewAJAX != undefined) {
        viewAJAX.abort();
    }
    //$('.sidebar-left').html();
    viewAJAX = $.getJSON(Drupal.settings.basePath + "meacars/ajax/loadview/blogs/default/", null, ajaxResponse);
    $('.menu-tabs li, .menu-tabs a').removeClass("active");
    $("#tab-blog, #tab-blog a").addClass("active");
    Drupal.attachBehaviors();
}

function loadSellCar() {
    viewAJAX = $.getJSON(Drupal.settings.basePath + "load_form/meacars_node_form", null, ajaxResponse);
    $('.menu-tabs li, .menu-tabs a').removeClass("active");
    $("#tab-sell-a-car, #tab-sell-a-car a").addClass("active");
    Drupal.attachBehaviors();
}

/*AJax node content*/
function load_dealarship_content(tab,uid){
    var response=new Object();
    response.data='<p style="text-align:center;"><img src="'+Drupal.settings.basePath+'sites/all/themes/meacar/images/AnimatedCarLoadingStatus.gif" alt=""/></p>';
    output_node_content(response);
    $.getJSON(Drupal.settings.basePath+"load_dealerpage/"+ tab +"/user/"+uid, null, output_node_content);
    var li = $(".meacars-detail-tab UL LI");
    for(i=0;i<li.length;i++){
        $("#"+li[i].id).removeClass("active-first");
        $("#"+li[i].id).removeClass("active-second");
        $("#"+li[i].id).removeClass("active-third");
        $("#"+li[i].id).removeClass("active-fourth");
    }
    if(tab=="meacars-overview"){
        $(".meacars-detail-tab UL").addClass("this_active_first");
        $(".meacars-detail-tab UL").removeClass("this_active_second");
    }
    if(tab=="meacars-contact-seller") {
        $(".meacars-detail-tab UL").removeClass("this_active_first");
        $(".meacars-detail-tab UL").addClass("this_active_second");
    }


    if (tab=="meacars-overview"){
        for(i=0;i<li.length;i++){
            $("#"+li[i].id).addClass("active-first");
        }
    }
    for(i=0;i<li.length;i++){
        $("#"+li[i].id).removeClass("active");
        $("#"+li[i].id+" A").removeClass("active");
    }
    $("#"+tab).addClass("active");
    $("#"+tab+" A").addClass("active");
}

function load_meacars_dealership_filter_block() {
    if (filter_dealerships_is_loaded) {
        return true;
    }
    var url = Drupal.settings.newpath.url;
    if ($('#block-filter_side_bar-dealer').length == 0) {
        $.getJSON(url, null, add_dealership_block_content);
        filter_dealerships_is_loaded = true;
    } else {
        $('#block-filter_side_bar-dealer').show();
        dealership_hide_other_blocks();
    }
    activeTab = 'D';
}

function dealership_hide_other_blocks() {
    $('#block-filter_side_bar-0').hide();
    $('#block-MeaCarsMagazine-0').hide();
    $('#block-MeaCarsMagazine-1').hide();
    $('#block-views-magazine_users_list-block_1').hide();
    $('#block-views-magazine_users_list-block_2').hide();
}

function add_dealership_block_content(response) {
    if ($('#block-filter_side_bar-dealer').length == 0) {
        $('.sidebar-left').prepend(response.data);
        dealership_hide_other_blocks();
        Drupal.attachBehaviors();
    }
}
function load_dealership_page_country(country) {
  mdf_country_x();
  $("#edit-country-options-" + country).attr('checked', true);
  var country = {};
   $("#filter-side-bar-country" + " INPUT[type='checkbox']").each( function() {
       if(this.checked) {
        country[this.value] = this.value;   
       }
   });
  $.post(Drupal.settings.filterarea.url,country,function(response) { $('#filter-side-bar-area div.fieldset-wrapper div.form-checkboxes').html(response.data);mdf_submit_find_now(); },'json');   

  
  return false;  
}
var areapage=false;
function load_dealership_page_city(city) {
 mdf_area_x();
 $("#edit-area-options-" + city).attr('checked', true);
 areapage=true;
 mdf_submit_find_now();
 areapage=false;
 return false;   
}

function load_dealership_cars(uid, cid) {
  $("#filter-side-bar-listings" + " INPUT[type='checkbox']").attr('checked', false);
  $("#edit-listings-users-options-"+uid+"-1-"+cid).attr('checked', true);
  $("#edit-listings-role-2").attr('checked', false);
  $("#edit-listings-role-1").attr('checked', true);

  var li = $(".menu-tabs UL LI"); 
  for(i=0;i<li.length;i++){
        $("#"+li[i].id).removeClass("active");
        $("#"+li[i].id+" A").removeClass("active");
  }
  submit_find_now();
  $('#block-filter_side_bar-0').show();
  createYearSlider(111,26,1990,2011,1,1990,1990,2011,1,2011,'Year','/');
  createMileageSlider(111,26,0,150000,1,0,0,150000,1,150000,'Milage','/');		
  createPriceSlider(111,26,0,100000,1,0,0,100000,1,100000,'Price','/');

  $('#block-filter_side_bar-dealer').hide();
  return false;
}
function load_meacars_dealership_filter_block_oncars() {
    if (filter_cars_is_loaded) {
        return true;
    }
    var url = Drupal.settings.newpath.url;
    $.getJSON(url, null, add_dealership_block_content_oncars);
    filter_cars_is_loaded = true;
}
function add_dealership_block_content_oncars(response) {
    if ($('#block-filter_side_bar-dealer').length == 0) {
        $('.sidebar-left').prepend(response.data);
        $('#block-filter_side_bar-dealer').hide();
        Drupal.attachBehaviors();
    }
};
jQuery(document).ready(function() {
   $('.jcarousel-container').mouseover(function() {
	  $(".jcarousel-prev").attr("title", "Click for previous suggestions");
      $(".jcarousel-prev-disabled").attr("title", "");
	  $(".jcarousel-next").attr("title", "Click for next suggestions");
	  $(".jcarousel-next-disabled").attr("title", "");
    });  
});

function loadItems(carousel, state, url) {
      // Check if the requested items already exist
    if (carousel.has(carousel.first, carousel.last)) {
        return;
    }

    jQuery.get(
        url,
        {
            first: carousel.first,
            last: carousel.last,
            nid: $('#nodeid')[0].value
        },
        function(data) {
            relatedItemAddCallback(carousel, carousel.first, carousel.last, data);
        },
        'json'
    );
};

function relatedItemLoadCallback(carousel, state) {
  loadItems(carousel, state, '/?q=dealership/relatedblock');
};

function relatedSellerItemLoadCallback(carousel, state) {
  loadItems(carousel, state, '/?q=dealership/relatedsellerblock');   
};

function relatedItemAddCallback(carousel, first, last, data)
{
    // Set the size of the carousel
    carousel.size(data[0]);

    jQuery.each(data, function(i) {
        if( i !=  0)
          carousel.add(first + i-1, data[i]);
    });
};


;
/**
 * 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/
 */

(function($) {
    /**
     * Creates a carousel for all matched elements.
     *
     * @example $("#mycarousel").jcarousel();
     * @before <ul id="mycarousel" class="jcarousel-skin-name"><li>First item</li><li>Second item</li></ul>
     * @result
     *
     * <div class="jcarousel-skin-name">
     *   <div class="jcarousel-container">
     *     <div disabled="disabled" class="jcarousel-prev jcarousel-prev-disabled"></div>
     *     <div class="jcarousel-next"></div>
     *     <div class="jcarousel-clip">
     *       <ul class="jcarousel-list">
     *         <li class="jcarousel-item-1">First item</li>
     *         <li class="jcarousel-item-2">Second item</li>
     *       </ul>
     *     </div>
     *   </div>
     * </div>
     *
     * @name jcarousel
     * @type jQuery
     * @param Hash o A set of key/value pairs to set as configuration properties.
     * @cat Plugins/jCarousel
     */
    $.fn.jcarousel = function(o) {
        return this.each(function() {
            new $jc(this, o);
        });
    };

    // Default configuration properties.
    var defaults = {
        vertical: false,
        start: 1,
        offset: 1,
        size: null,
        scroll: 3,
        visible: null,
        animation: 'normal',
        easing: 'swing',
        auto: 0,
        wrap: null,
        initCallback: null,
        reloadCallback: null,
        itemLoadCallback: null,
        itemFirstInCallback: null,
        itemFirstOutCallback: null,
        itemLastInCallback: null,
        itemLastOutCallback: null,
        itemVisibleInCallback: null,
        itemVisibleOutCallback: null,
        buttonNextHTML: '<div></div>',
        buttonPrevHTML: '<div></div>',
        buttonNextEvent: 'click',
        buttonPrevEvent: 'click',
        buttonNextCallback: null,
        buttonPrevCallback: null
    };

    /**
     * The jCarousel object.
     *
     * @constructor
     * @name $.jcarousel
     * @param Object e The element to create the carousel for.
     * @param Hash o A set of key/value pairs to set as configuration properties.
     * @cat Plugins/jCarousel
     */
    $.jcarousel = function(e, o) {
        this.options    = $.extend({}, defaults, o || {});

        this.locked     = false;

        this.container  = null;
        this.clip       = null;
        this.list       = null;
        this.buttonNext = null;
        this.buttonPrev = null;

        this.wh = !this.options.vertical ? 'width' : 'height';
        this.lt = !this.options.vertical ? 'left' : 'top';

        // Extract skin class
        var skin = '', split = e.className.split(' ');

        for (var i = 0; i < split.length; i++) {
            if (split[i].indexOf('jcarousel-skin') != -1) {
                $(e).removeClass(split[i]);
                var skin = split[i];
                break;
            }
        }

        if (e.nodeName == 'UL' || e.nodeName == 'OL') {
            this.list = $(e);
            this.container = this.list.parent();

            if (this.container.hasClass('jcarousel-clip')) {
                if (!this.container.parent().hasClass('jcarousel-container'))
                    this.container = this.container.wrap('<div></div>');

                this.container = this.container.parent();
            } else if (!this.container.hasClass('jcarousel-container'))
                this.container = this.list.wrap('<div></div>').parent();
        } else {
            this.container = $(e);
            this.list = $(e).find('>ul,>ol,div>ul,div>ol');
        }

        if (skin != '' && this.container.parent()[0].className.indexOf('jcarousel-skin') == -1)
        	this.container.wrap('<div class=" '+ skin + '"></div>');

        this.clip = this.list.parent();

        if (!this.clip.length || !this.clip.hasClass('jcarousel-clip'))
            this.clip = this.list.wrap('<div></div>').parent();

        this.buttonPrev = $('.jcarousel-prev', this.container);

        if (this.buttonPrev.size() == 0 && this.options.buttonPrevHTML != null)
            this.buttonPrev = this.clip.before(this.options.buttonPrevHTML).prev();

        this.buttonPrev.addClass(this.className('jcarousel-prev'));

        this.buttonNext = $('.jcarousel-next', this.container);

        if (this.buttonNext.size() == 0 && this.options.buttonNextHTML != null)
            this.buttonNext = this.clip.before(this.options.buttonNextHTML).prev();

        this.buttonNext.addClass(this.className('jcarousel-next'));

        this.clip.addClass(this.className('jcarousel-clip'));
        this.list.addClass(this.className('jcarousel-list'));
        this.container.addClass(this.className('jcarousel-container'));

        var di = this.options.visible != null ? Math.ceil(this.clipping() / this.options.visible) : null;
        var li = this.list.children('li');

        var self = this;

        if (li.size() > 0) {
            var wh = 0, i = this.options.offset;
            li.each(function() {
                self.format(this, i++);
                wh += self.dimension(this, di);
            });

            this.list.css(this.wh, wh + 'px');

            // Only set if not explicitly passed as option
            if (!o || o.size === undefined)
                this.options.size = li.size();
        }

        // For whatever reason, .show() does not work in Safari...
        this.container.css('display', 'block');
        this.buttonNext.css('display', 'block');
        this.buttonPrev.css('display', 'block');

        this.funcNext   = function() { self.next(); };
        this.funcPrev   = function() { self.prev(); };
        this.funcResize = function() { self.reload(); };

        if (this.options.initCallback != null)
            this.options.initCallback(this, 'init');

        if ($.browser.safari) {
            this.buttons(false, false);
            $(window).bind('load', function() { self.setup(); });
        } else
            this.setup();
    };

    // Create shortcut for internal use
    var $jc = $.jcarousel;

    $jc.fn = $jc.prototype = {
        jcarousel: '0.2.3'
    };

    $jc.fn.extend = $jc.extend = $.extend;

    $jc.fn.extend({
        /**
         * Setups the carousel.
         *
         * @name setup
         * @type undefined
         * @cat Plugins/jCarousel
         */
        setup: function() {
            this.first     = null;
            this.last      = null;
            this.prevFirst = null;
            this.prevLast  = null;
            this.animating = false;
            this.timer     = null;
            this.tail      = null;
            this.inTail    = false;

            if (this.locked)
                return;

            this.list.css(this.lt, this.pos(this.options.offset) + 'px');
            var p = this.pos(this.options.start);
            this.prevFirst = this.prevLast = null;
            this.animate(p, false);

           // $(window).unbind('resize', this.funcResize).bind('resize', this.funcResize);
        },

        /**
         * Clears the list and resets the carousel.
         *
         * @name reset
         * @type undefined
         * @cat Plugins/jCarousel
         */
        reset: function() {
            this.list.empty();

            this.list.css(this.lt, '0px');
            this.list.css(this.wh, '10px');

            if (this.options.initCallback != null)
                this.options.initCallback(this, 'reset');

            this.setup();
        },

        /**
         * Reloads the carousel and adjusts positions.
         *
         * @name reload
         * @type undefined
         * @cat Plugins/jCarousel
         */
        reload: function() {
            if (this.tail != null && this.inTail)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + this.tail);

            this.tail   = null;
            this.inTail = false;

            if (this.options.reloadCallback != null)
                this.options.reloadCallback(this);

            if (this.options.visible != null) {
                var self = this;
                var di = Math.ceil(this.clipping() / this.options.visible), wh = 0, lt = 0;
                $('li', this.list).each(function(i) {
                    wh += self.dimension(this, di);
                    if (i + 1 < self.first)
                        lt = wh;
                });

                this.list.css(this.wh, wh + 'px');
                this.list.css(this.lt, -lt + 'px');
            }

            this.scroll(this.first, false);
        },

        /**
         * Locks the carousel.
         *
         * @name lock
         * @type undefined
         * @cat Plugins/jCarousel
         */
        lock: function() {
            this.locked = true;
            this.buttons();
        },

        /**
         * Unlocks the carousel.
         *
         * @name unlock
         * @type undefined
         * @cat Plugins/jCarousel
         */
        unlock: function() {
            this.locked = false;
            this.buttons();
        },

        /**
         * Sets the size of the carousel.
         *
         * @name size
         * @type undefined
         * @param Number s The size of the carousel.
         * @cat Plugins/jCarousel
         */
        size: function(s) {
            if (s != undefined) {
                this.options.size = s;
                if (!this.locked)
                    this.buttons();
            }

            return this.options.size;
        },

        /**
         * Checks whether a list element exists for the given index (or index range).
         *
         * @name get
         * @type bool
         * @param Number i The index of the (first) element.
         * @param Number i2 The index of the last element.
         * @cat Plugins/jCarousel
         */
        has: function(i, i2) {
            if (i2 == undefined || !i2)
                i2 = i;

            if (this.options.size !== null && i2 > this.options.size)
            	i2 = this.options.size;

            for (var j = i; j <= i2; j++) {
                var e = this.get(j);
                if (!e.length || e.hasClass('jcarousel-item-placeholder'))
                    return false;
            }

            return true;
        },

        /**
         * Returns a jQuery object with list element for the given index.
         *
         * @name get
         * @type jQuery
         * @param Number i The index of the element.
         * @cat Plugins/jCarousel
         */
        get: function(i) {
            return $('.jcarousel-item-' + i, this.list);
        },

        /**
         * Adds an element for the given index to the list.
         * If the element already exists, it updates the inner html.
         * Returns the created element as jQuery object.
         *
         * @name add
         * @type jQuery
         * @param Number i The index of the element.
         * @param String s The innerHTML of the element.
         * @cat Plugins/jCarousel
         */
        add: function(i, s) {
            var e = this.get(i), old = 0, add = 0;

            if (e.length == 0) {
                var c, e = this.create(i), j = $jc.intval(i);
                while (c = this.get(--j)) {
                    if (j <= 0 || c.length) {
                        j <= 0 ? this.list.prepend(e) : c.after(e);
                        break;
                    }
                }
            } else
                old = this.dimension(e);

            e.removeClass(this.className('jcarousel-item-placeholder'));
            typeof s == 'string' ? e.html(s) : e.empty().append(s);

            var di = this.options.visible != null ? Math.ceil(this.clipping() / this.options.visible) : null;
            var wh = this.dimension(e, di) - old;

            if (i > 0 && i < this.first)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - wh + 'px');

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) + wh + 'px');

            return e;
        },

        /**
         * Removes an element for the given index from the list.
         *
         * @name remove
         * @type undefined
         * @param Number i The index of the element.
         * @cat Plugins/jCarousel
         */
        remove: function(i) {
            var e = this.get(i);

            // Check if item exists and is not currently visible
            if (!e.length || (i >= this.first && i <= this.last))
                return;

            var d = this.dimension(e);

            if (i < this.first)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + d + 'px');

            e.remove();

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) - d + 'px');
        },

        /**
         * Moves the carousel forwards.
         *
         * @name next
         * @type undefined
         * @cat Plugins/jCarousel
         */
        next: function() {
            this.stopAuto();

            if (this.tail != null && !this.inTail)
                this.scrollTail(false);
            else
                this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'last') && this.options.size != null && this.last == this.options.size) ? 1 : this.first + this.options.scroll);
        },

        /**
         * Moves the carousel backwards.
         *
         * @name prev
         * @type undefined
         * @cat Plugins/jCarousel
         */
        prev: function() {
            this.stopAuto();

            if (this.tail != null && this.inTail)
                this.scrollTail(true);
            else
                this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'first') && this.options.size != null && this.first == 1) ? this.options.size : this.first - this.options.scroll);
        },

        /**
         * Scrolls the tail of the carousel.
         *
         * @name scrollTail
         * @type undefined
         * @param Bool b Whether scroll the tail back or forward.
         * @cat Plugins/jCarousel
         */
        scrollTail: function(b) {
            if (this.locked || this.animating || !this.tail)
                return;

            var pos  = $jc.intval(this.list.css(this.lt));

            !b ? pos -= this.tail : pos += this.tail;
            this.inTail = !b;

            // Save for callbacks
            this.prevFirst = this.first;
            this.prevLast  = this.last;

            this.animate(pos);
        },

        /**
         * Scrolls the carousel to a certain position.
         *
         * @name scroll
         * @type undefined
         * @param Number i The index of the element to scoll to.
         * @param Bool a Flag indicating whether to perform animation.
         * @cat Plugins/jCarousel
         */
        scroll: function(i, a) {
            if (this.locked || this.animating)
                return;

            this.animate(this.pos(i), a);
        },

        /**
         * Prepares the carousel and return the position for a certian index.
         *
         * @name pos
         * @type Number
         * @param Number i The index of the element to scoll to.
         * @cat Plugins/jCarousel
         */
        pos: function(i) {
            if (this.locked || this.animating)
                return;

            if (this.options.wrap != 'circular')
                i = i < 1 ? 1 : (this.options.size && i > this.options.size ? this.options.size : i);

            var back = this.first > i;
            var pos  = $jc.intval(this.list.css(this.lt));

            // Create placeholders, new list width/height
            // and new list position
            var f = this.options.wrap != 'circular' && this.first <= 1 ? 1 : this.first;
            var c = back ? this.get(f) : this.get(this.last);
            var j = back ? f : f - 1;
            var e = null, l = 0, p = false, d = 0;

            while (back ? --j >= i : ++j < i) {
                e = this.get(j);
                p = !e.length;
                if (e.length == 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    c[back ? 'before' : 'after' ](e);
                }

                c = e;
                d = this.dimension(e);

                if (p)
                    l += d;

                if (this.first != null && (this.options.wrap == 'circular' || (j >= 1 && (this.options.size == null || j <= this.options.size))))
                    pos = back ? pos + d : pos - d;
            }

            // Calculate visible items
            var clipping = this.clipping();
            var cache = [];
            var visible = 0, j = i, v = 0;
            var c = this.get(i - 1);

            while (++visible) {
                e = this.get(j);
                p = !e.length;
                if (e.length == 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    // This should only happen on a next scroll
                    c.length == 0 ? this.list.prepend(e) : c[back ? 'before' : 'after' ](e);
                }

                c = e;
                var d = this.dimension(e);
                if (d == 0) {
                    //alert('jCarousel: No width/height set for items. This will cause an infinite loop. Aborting...');
                    return 0;
                }

                if (this.options.wrap != 'circular' && this.options.size !== null && j > this.options.size)
                    cache.push(e);
                else if (p)
                    l += d;

                v += d;

                if (v >= clipping)
                    break;

                j++;
            }

             // Remove out-of-range placeholders
            for (var x = 0; x < cache.length; x++)
                cache[x].remove();

            // Resize list
            if (l > 0) {
                this.list.css(this.wh, this.dimension(this.list) + l + 'px');

                if (back) {
                    pos -= l;
                    this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - l + 'px');
                }
            }

            // Calculate first and last item
            var last = i + visible - 1;
            if (this.options.wrap != 'circular' && this.options.size && last > this.options.size)
                last = this.options.size;

            if (j > last) {
                visible = 0, j = last, v = 0;
                while (++visible) {
                    var e = this.get(j--);
                    if (!e.length)
                        break;
                    v += this.dimension(e);
                    if (v >= clipping)
                        break;
                }
            }

            var first = last - visible + 1;
            if (this.options.wrap != 'circular' && first < 1)
                first = 1;

            if (this.inTail && back) {
                pos += this.tail;
                this.inTail = false;
            }

            this.tail = null;
            if (this.options.wrap != 'circular' && last == this.options.size && (last - visible + 1) >= 1) {
                var m = $jc.margin(this.get(last), !this.options.vertical ? 'marginRight' : 'marginBottom');
                if ((v - m) > clipping+10)
                    this.tail = v - clipping - m;
            }

            // Adjust position
            while (i-- > first)
                pos += this.dimension(this.get(i));

            // Save visible item range
            this.prevFirst = this.first;
            this.prevLast  = this.last;
            this.first     = first;
            this.last      = last;

            return pos;
        },

        /**
         * Animates the carousel to a certain position.
         *
         * @name animate
         * @type undefined
         * @param mixed p Position to scroll to.
         * @param Bool a Flag indicating whether to perform animation.
         * @cat Plugins/jCarousel
         */
        animate: function(p, a) {
            if (this.locked || this.animating)
                return;

            this.animating = true;

            var self = this;
            var scrolled = function() {
                self.animating = false;

                if (p == 0)
                    self.list.css(self.lt,  0);

                if (self.options.wrap == 'both' || self.options.wrap == 'last' || self.options.size == null || self.last < self.options.size)
                    self.startAuto();

                self.buttons();
                self.notify('onAfterAnimation');
            };

            this.notify('onBeforeAnimation');

            // Animate
            if (!this.options.animation || a == false) {
                this.list.css(this.lt, p + 'px');
                scrolled();
            } else {
                var o = !this.options.vertical ? {'left': p} : {'top': p};
                this.list.animate(o, this.options.animation, this.options.easing, scrolled);
            }
        },

        /**
         * Starts autoscrolling.
         *
         * @name auto
         * @type undefined
         * @param Number s Seconds to periodically autoscroll the content.
         * @cat Plugins/jCarousel
         */
        startAuto: function(s) {
            if (s != undefined)
                this.options.auto = s;

            if (this.options.auto == 0)
                return this.stopAuto();

            if (this.timer != null)
                return;

            var self = this;
            this.timer = setTimeout(function() { self.next(); }, this.options.auto * 1000);
        },

        /**
         * Stops autoscrolling.
         *
         * @name stopAuto
         * @type undefined
         * @cat Plugins/jCarousel
         */
        stopAuto: function() {
            if (this.timer == null)
                return;

            clearTimeout(this.timer);
            this.timer = null;
        },

        /**
         * Sets the states of the prev/next buttons.
         *
         * @name buttons
         * @type undefined
         * @cat Plugins/jCarousel
         */
        buttons: function(n, p) {
            if (n == undefined || n == null) {
                var n = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'first') || this.options.size == null || this.last < this.options.size);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'first') && this.options.size != null && this.last >= this.options.size)
                    n = this.tail != null && !this.inTail;
            }

            if (p == undefined || p == null) {
                var p = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'last') || this.first > 1);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'last') && this.options.size != null && this.first == 1)
                    p = this.tail != null && this.inTail;
            }

            var self = this;

            this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);
            this.buttonPrev[p ? 'bind' : 'unbind'](this.options.buttonPrevEvent, this.funcPrev)[p ? 'removeClass' : 'addClass'](this.className('jcarousel-prev-disabled')).attr('disabled', p ? false : true);

            if (this.buttonNext.length > 0 && (this.buttonNext[0].jcarouselstate == undefined || this.buttonNext[0].jcarouselstate != n) && this.options.buttonNextCallback != null) {
                this.buttonNext.each(function() { self.options.buttonNextCallback(self, this, n); });
                this.buttonNext[0].jcarouselstate = n;
            }

            if (this.buttonPrev.length > 0 && (this.buttonPrev[0].jcarouselstate == undefined || this.buttonPrev[0].jcarouselstate != p) && this.options.buttonPrevCallback != null) {
                this.buttonPrev.each(function() { self.options.buttonPrevCallback(self, this, p); });
                this.buttonPrev[0].jcarouselstate = p;
            }
        },

        notify: function(evt) {
            var state = this.prevFirst == null ? 'init' : (this.prevFirst < this.first ? 'next' : 'prev');

            // Load items
            this.callback('itemLoadCallback', evt, state);

            if (this.prevFirst !== this.first) {
                this.callback('itemFirstInCallback', evt, state, this.first);
                this.callback('itemFirstOutCallback', evt, state, this.prevFirst);
            }

            if (this.prevLast !== this.last) {
                this.callback('itemLastInCallback', evt, state, this.last);
                this.callback('itemLastOutCallback', evt, state, this.prevLast);
            }

            this.callback('itemVisibleInCallback', evt, state, this.first, this.last, this.prevFirst, this.prevLast);
            this.callback('itemVisibleOutCallback', evt, state, this.prevFirst, this.prevLast, this.first, this.last);
        },

        callback: function(cb, evt, state, i1, i2, i3, i4) {
            if (this.options[cb] == undefined || (typeof this.options[cb] != 'object' && evt != 'onAfterAnimation'))
                return;

            var callback = typeof this.options[cb] == 'object' ? this.options[cb][evt] : this.options[cb];

            if (!$.isFunction(callback))
                return;

            var self = this;

            if (i1 === undefined)
                callback(self, state, evt);
            else if (i2 === undefined)
                this.get(i1).each(function() { callback(self, this, i1, state, evt); });
            else {
                for (var i = i1; i <= i2; i++)
                    if (i !== null && !(i >= i3 && i <= i4))
                        this.get(i).each(function() { callback(self, this, i, state, evt); });
            }
        },

        create: function(i) {
            return this.format('<li></li>', i);
        },

        format: function(e, i) {
            var $e = $(e).addClass(this.className('jcarousel-item')).addClass(this.className('jcarousel-item-' + i));
            $e.attr('jcarouselindex', i);
            return $e;
        },

        className: function(c) {
            return c + ' ' + c + (!this.options.vertical ? '-horizontal' : '-vertical');
        },

        dimension: function(e, d) {
            var el = e.jquery != undefined ? e[0] : e;

            var old = !this.options.vertical ?
                el.offsetWidth + $jc.margin(el, 'marginLeft') + $jc.margin(el, 'marginRight') :
                el.offsetHeight + $jc.margin(el, 'marginTop') + $jc.margin(el, 'marginBottom');

            if (d == undefined || old == d)
                return old;

            var w = !this.options.vertical ?
                d - $jc.margin(el, 'marginLeft') - $jc.margin(el, 'marginRight') :
                d - $jc.margin(el, 'marginTop') - $jc.margin(el, 'marginBottom');

            $(el).css(this.wh, w + 'px');

            return this.dimension(el);
        },

        clipping: function() {
            return !this.options.vertical ?
                this.clip[0].offsetWidth - $jc.intval(this.clip.css('borderLeftWidth')) - $jc.intval(this.clip.css('borderRightWidth')) :
                this.clip[0].offsetHeight - $jc.intval(this.clip.css('borderTopWidth')) - $jc.intval(this.clip.css('borderBottomWidth'));
        },

        index: function(i, s) {
            if (s == undefined)
                s = this.options.size;

            return Math.round((((i-1) / s) - Math.floor((i-1) / s)) * s) + 1;
        }
    });

    $jc.extend({
        /**
         * Gets/Sets the global default configuration properties.
         *
         * @name defaults
         * @descr Gets/Sets the global default configuration properties.
         * @type Hash
         * @param Hash d A set of key/value pairs to set as configuration properties.
         * @cat Plugins/jCarousel
         */
        defaults: function(d) {
            return $.extend(defaults, d || {});
        },

        margin: function(e, p) {
            if (!e)
                return 0;

            var el = e.jquery != undefined ? e[0] : e;

            if (p == 'marginRight' && $.browser.safari) {
                var old = {'display': 'block', 'float': 'none', 'width': 'auto'}, oWidth, oWidth2;

                $.swap(el, old, function() { oWidth = el.offsetWidth; });

                old['marginRight'] = 0;
                $.swap(el, old, function() { oWidth2 = el.offsetWidth; });

                return oWidth2 - oWidth;
            }

            return $jc.intval($.css(el, p));
        },

        intval: function(v) {
            v = parseInt(v);
            return isNaN(v) ? 0 : v;
        }
    });

})(jQuery);










;
/* $Id: jcarousel.js,v 1.1.2.2.2.5 2009/03/25 18:10:22 robloach Exp $ */

/**
 * @file
 * Provides the jCarousel Drupal behavior.
 */

/**
 * The jCarousel Drupal behavior that creates the set of jCarousel elements from Drupal.settings.jcarousel.
 */
Drupal.behaviors.jcarousel = function() {
  // Iterate through each selector and add the carousel.
  jQuery.each(Drupal.settings.jcarousel, function(selector, options) {

    // Convert any callback arguments from strings to function calls.
    var callbacks = ['initCallback', 'itemLoadCallback', 'itemFirstInCallback', 'itemFirstOutCallback', 'itemLastOutCallback', 'itemLastInCallback', 'itemVisibleInCallback', 'itemVisibleOutCallback', 'buttonNextCallback', 'buttonPrevCallback'];
    for (callback in callbacks) {
      var callbackname = callbacks[callback];
      // The callback depends on its type.
      if (typeof(options[callbackname]) == 'string') {
        // Strings are evaluated as functions.
        options[callbackname] = eval(options[callbackname]);
      }
      else if (typeof(options[callbackname]) == 'object' && (options[callbackname] instanceof Array)) {
        // Arrays are evaluated as a list of callback registrations. This is because callbacks
        // like itemVisibleInCallback can either be a function call back, or an array of callbacks
        // consisting of both onBeforeAnimation and onAfterAnimation.
        for (subcallback in options[callbackname]) {
          var name = options[callbackname][subcallback];
          options[callbackname][name] = eval(options[callbackname][name]);
        }
      }
    }

    // Prepare the skin name to be added as a class name.
    var skin = options['skin'];
    if (typeof(skin) == 'string') {
      skin = ' jcarousel-skin-' + skin;
    }
    else {
      skin = '';
    }

    // Create the countdown element on non-processed elements.
    $(selector + ':not(.jcarousel-processed)').addClass('jcarousel-processed' + skin).jcarousel(options);
  });
};










;
var NodeGallery={};
NodeGallery.init=function(){

	this.activateLinks();
	this.activateUpDown();

	$(".gallary_thumblist>a:first").addClass("active_thumb");

	var gallary_thumnbs=$('a.gallary_thumb');

	var gallary_thumblist=$(".gallary_thumblist");

	if(gallary_thumnbs.length<5)
	{
		for(i=5;i>gallary_thumnbs.length;i--)
		{
			gallary_thumnbs.parent();
			gallary_thumblist.append("<a class='gallary_thumb' href='javascript:void(0);'><img  src='/sites/default/files/default.jpg'/></a>")
		}
	}
	
	if(gallary_thumnbs.length <= 5)
	{
		$(".gallary_up_arrow img").attr("src","/sites/all/modules/node_images/images/top_arrow_gray.gif").css({cursor:"default"});
		
		$(".gallary_down_arrow img").attr("src","/sites/all/modules/node_images/images/bottom_arrow_grey.gif").css({cursor:"default"});
	}
	else
	{
		$(".gallary_thumblist>a.gallary_thumb:gt(4)").hide();
	}
	
	
	
	
	
	

  gallary_thumnbs.each(function(){
	$(this).attr("index",parseInt(gallary_thumnbs.index(this))+1);
  });	

	  var index = 1;

	$("#gallerix-current-index").html(index);
  $("#gallerix-total-count").html(gallary_thumnbs.length); 
  
}
NodeGallery.activateLinks=function(){
	
	$(".gallary_thumb").each(function(){
		if(!$(this).data("binded"))
		{
			$(this).click(function(){
				$(".active_thumb").removeClass("active_thumb");								   
				$(this).addClass("active_thumb");
				var fullsizeImagePath = $("img",this).attr("src").replace("-tn","");
				$(".gallary_fullsize>img").attr("src",fullsizeImagePath);
				var index = $(this).attr("index");
				$("#gallerix-current-index").html(index);
				$("#gallerix-total-count").html(gallary_thumb.length); 
			});
			$(this).data("binded", true);
		}
	})
	
}

NodeGallery.activateUpDown=
		function(){
			if($(".gallary_thumb").length>5)
		{
		$('.gallary_down_arrow').click(function (e) {
			//var first_link = $(".gallary_thumblist>a:first").removeClass("active_thumb").remove();
      var first_link = $(".gallary_thumblist>a:first").remove();
			var last_link=$(".gallary_thumblist>a:last");
		
			$(".gallary_thumblist>a:hidden:first").show();
			last_link.after(first_link.hide());
		
			NodeGallery.activateLinks();
			e.preventDefault();
			return false;
	  });
	  
	  $('.gallary_up_arrow').click(function (e) {
		//	var last_link = $(".gallary_thumblist>a:last").removeClass("active_thumb").remove();
			  var last_link = $(".gallary_thumblist>a:last").remove();
      var first_link=$(".gallary_thumblist>a:first");
		
			$(".gallary_thumblist>a:visible:last").hide();
			first_link.before(last_link.show());
		
			NodeGallery.activateLinks();
			e.preventDefault();
			return false;
			
		

	  });
	  
	  $('.gallary_up_arrow').mouseover(function(){
     		 $(".gallary_up_arrow img").attr("src","/sites/all/modules/node_images/images/top_arrow_glowing.jpg");
   		 }).mouseout(function(){
      		$(".gallary_up_arrow img").attr("src","/sites/all/modules/node_images/images/top_arrow.gif");
   		 });
	  
	    $('.gallary_down_arrow').mouseover(function(){
     		 $(".gallary_down_arrow img").attr("src","/sites/all/modules/node_images/images/bottom_arrow_glowing.jpg");
   		 }).mouseout(function(){
      		$(".gallary_down_arrow img").attr("src","/sites/all/modules/node_images/images/bottom_arrow.gif");
   		 });
}
//end if
}
Drupal.behaviors.node_gallery = function() {
	NodeGallery.init();
}









;
/*!
* jQuery Form Plugin
* version: 2.43 (12-MAR-2010)
* @requires jQuery v1.3.2 or later
*
* Examples and documentation at: http://malsup.com/jquery/form/
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
(function(b){function o(){if(b.fn.ajaxSubmit.debug){var a="[jquery.form] "+Array.prototype.join.call(arguments,"");if(window.console&&window.console.log)window.console.log(a);else window.opera&&window.opera.postError&&window.opera.postError(a)}}b.fn.ajaxSubmit=function(a){function d(){function r(){var p=h.attr("target"),n=h.attr("action");j.setAttribute("target",z);j.getAttribute("method")!="POST"&&j.setAttribute("method","POST");j.getAttribute("action")!=g.url&&j.setAttribute("action",g.url);g.skipEncodingOverride||
h.attr({encoding:"multipart/form-data",enctype:"multipart/form-data"});g.timeout&&setTimeout(function(){C=true;s()},g.timeout);var m=[];try{if(g.extraData)for(var u in g.extraData)m.push(b('<input type="hidden" name="'+u+'" value="'+g.extraData[u]+'" />').appendTo(j)[0]);t.appendTo("body");t.data("form-plugin-onload",s);j.submit()}finally{j.setAttribute("action",n);p?j.setAttribute("target",p):h.removeAttr("target");b(m).remove()}}function s(){if(!D){var p=true;try{if(C)throw"timeout";var n,m;m=v.contentWindow?
v.contentWindow.document:v.contentDocument?v.contentDocument:v.document;var u=g.dataType=="xml"||m.XMLDocument||b.isXMLDoc(m);o("isXml="+u);if(!u&&(m.body==null||m.body.innerHTML=="")){if(--G){o("requeing onLoad callback, DOM not available");setTimeout(s,250);return}o("Could not access iframe DOM after 100 tries.");return}o("response detected");D=true;i.responseText=m.body?m.body.innerHTML:null;i.responseXML=m.XMLDocument?m.XMLDocument:m;i.getResponseHeader=function(H){return{"content-type":g.dataType}[H]};
if(g.dataType=="json"||g.dataType=="script"){var E=m.getElementsByTagName("textarea")[0];if(E)i.responseText=E.value;else{var F=m.getElementsByTagName("pre")[0];if(F)i.responseText=F.innerHTML}}else if(g.dataType=="xml"&&!i.responseXML&&i.responseText!=null)i.responseXML=A(i.responseText);n=b.httpData(i,g.dataType)}catch(B){o("error caught:",B);p=false;i.error=B;b.handleError(g,i,"error",B)}if(p){g.success(n,"success");w&&b.event.trigger("ajaxSuccess",[i,g])}w&&b.event.trigger("ajaxComplete",[i,g]);
w&&!--b.active&&b.event.trigger("ajaxStop");if(g.complete)g.complete(i,p?"success":"error");setTimeout(function(){t.removeData("form-plugin-onload");t.remove();i.responseXML=null},100)}}function A(p,n){if(window.ActiveXObject){n=new ActiveXObject("Microsoft.XMLDOM");n.async="false";n.loadXML(p)}else n=(new DOMParser).parseFromString(p,"text/xml");return n&&n.documentElement&&n.documentElement.tagName!="parsererror"?n:null}var j=h[0];if(b(":input[name=submit]",j).length)alert('Error: Form elements must not be named "submit".');
else{var g=b.extend({},b.ajaxSettings,a),q=b.extend(true,{},b.extend(true,{},b.ajaxSettings),g),z="jqFormIO"+(new Date).getTime(),t=b('<iframe id="'+z+'" name="'+z+'" src="'+g.iframeSrc+'" onload="(jQuery(this).data(\'form-plugin-onload\'))()" />'),v=t[0];t.css({position:"absolute",top:"-1000px",left:"-1000px"});var i={aborted:0,responseText:null,responseXML:null,status:0,statusText:"n/a",getAllResponseHeaders:function(){},getResponseHeader:function(){},setRequestHeader:function(){},abort:function(){this.aborted=
1;t.attr("src",g.iframeSrc)}},w=g.global;w&&!b.active++&&b.event.trigger("ajaxStart");w&&b.event.trigger("ajaxSend",[i,g]);if(q.beforeSend&&q.beforeSend(i,q)===false)q.global&&b.active--;else if(!i.aborted){var D=false,C=0;if(q=j.clk){var y=q.name;if(y&&!q.disabled){g.extraData=g.extraData||{};g.extraData[y]=q.value;if(q.type=="image"){g.extraData[y+".x"]=j.clk_x;g.extraData[y+".y"]=j.clk_y}}}g.forceSync?r():setTimeout(r,10);var G=100}}}if(!this.length){o("ajaxSubmit: skipping submit process - no element selected");
return this}if(typeof a=="function")a={success:a};var e=b.trim(this.attr("action"));if(e)e=(e.match(/^([^#]+)/)||[])[1];e=e||window.location.href||"";a=b.extend({url:e,type:this.attr("method")||"GET",iframeSrc:/^https/i.test(window.location.href||"")?"javascript:false":"about:blank"},a||{});e={};this.trigger("form-pre-serialize",[this,a,e]);if(e.veto){o("ajaxSubmit: submit vetoed via form-pre-serialize trigger");return this}if(a.beforeSerialize&&a.beforeSerialize(this,a)===false){o("ajaxSubmit: submit aborted via beforeSerialize callback");
return this}var f=this.formToArray(a.semantic);if(a.data){a.extraData=a.data;for(var c in a.data)if(a.data[c]instanceof Array)for(var l in a.data[c])f.push({name:c,value:a.data[c][l]});else f.push({name:c,value:a.data[c]})}if(a.beforeSubmit&&a.beforeSubmit(f,this,a)===false){o("ajaxSubmit: submit aborted via beforeSubmit callback");return this}this.trigger("form-submit-validate",[f,this,a,e]);if(e.veto){o("ajaxSubmit: submit vetoed via form-submit-validate trigger");return this}c=b.param(f);if(a.type.toUpperCase()==
"GET"){a.url+=(a.url.indexOf("?")>=0?"&":"?")+c;a.data=null}else a.data=c;var h=this,k=[];a.resetForm&&k.push(function(){h.resetForm()});a.clearForm&&k.push(function(){h.clearForm()});if(!a.dataType&&a.target){var x=a.success||function(){};k.push(function(r){var s=a.replaceTarget?"replaceWith":"html";b(a.target)[s](r).each(x,arguments)})}else a.success&&k.push(a.success);a.success=function(r,s,A){for(var j=0,g=k.length;j<g;j++)k[j].apply(a,[r,s,A||h,h])};c=b("input:file",this).fieldValue();l=false;
for(e=0;e<c.length;e++)if(c[e])l=true;if(c.length&&a.iframe!==false||a.iframe||l||0)a.closeKeepAlive?b.get(a.closeKeepAlive,d):d();else b.ajax(a);this.trigger("form-submit-notify",[this,a]);return this};b.fn.ajaxForm=function(a){return this.ajaxFormUnbind().bind("submit.form-plugin",function(d){d.preventDefault();b(this).ajaxSubmit(a)}).bind("click.form-plugin",function(d){var e=d.target,f=b(e);if(!f.is(":submit,input:image")){e=f.closest(":submit");if(e.length==0)return;e=e[0]}var c=this;c.clk=e;
if(e.type=="image")if(d.offsetX!=undefined){c.clk_x=d.offsetX;c.clk_y=d.offsetY}else if(typeof b.fn.offset=="function"){f=f.offset();c.clk_x=d.pageX-f.left;c.clk_y=d.pageY-f.top}else{c.clk_x=d.pageX-e.offsetLeft;c.clk_y=d.pageY-e.offsetTop}setTimeout(function(){c.clk=c.clk_x=c.clk_y=null},100)})};b.fn.ajaxFormUnbind=function(){return this.unbind("submit.form-plugin click.form-plugin")};b.fn.formToArray=function(a){var d=[];if(this.length==0)return d;var e=this[0],f=a?e.getElementsByTagName("*"):e.elements;
if(!f)return d;for(var c=0,l=f.length;c<l;c++){var h=f[c],k=h.name;if(k)if(a&&e.clk&&h.type=="image"){if(!h.disabled&&e.clk==h){d.push({name:k,value:b(h).val()});d.push({name:k+".x",value:e.clk_x},{name:k+".y",value:e.clk_y})}}else if((h=b.fieldValue(h,true))&&h.constructor==Array)for(var x=0,r=h.length;x<r;x++)d.push({name:k,value:h[x]});else h!==null&&typeof h!="undefined"&&d.push({name:k,value:h})}if(!a&&e.clk){a=b(e.clk);f=a[0];if((k=f.name)&&!f.disabled&&f.type=="image"){d.push({name:k,value:a.val()});
d.push({name:k+".x",value:e.clk_x},{name:k+".y",value:e.clk_y})}}return d};b.fn.formSerialize=function(a){return b.param(this.formToArray(a))};b.fn.fieldSerialize=function(a){var d=[];this.each(function(){var e=this.name;if(e){var f=b.fieldValue(this,a);if(f&&f.constructor==Array)for(var c=0,l=f.length;c<l;c++)d.push({name:e,value:f[c]});else f!==null&&typeof f!="undefined"&&d.push({name:this.name,value:f})}});return b.param(d)};b.fn.fieldValue=function(a){for(var d=[],e=0,f=this.length;e<f;e++){var c=
b.fieldValue(this[e],a);c===null||typeof c=="undefined"||c.constructor==Array&&!c.length||(c.constructor==Array?b.merge(d,c):d.push(c))}return d};b.fieldValue=function(a,d){var e=a.name,f=a.type,c=a.tagName.toLowerCase();if(typeof d=="undefined")d=true;if(d&&(!e||a.disabled||f=="reset"||f=="button"||(f=="checkbox"||f=="radio")&&!a.checked||(f=="submit"||f=="image")&&a.form&&a.form.clk!=a||c=="select"&&a.selectedIndex==-1))return null;if(c=="select"){c=a.selectedIndex;if(c<0)return null;d=[];a=a.options;
e=(f=f=="select-one")?c+1:a.length;for(c=f?c:0;c<e;c++){var l=a[c];if(l.selected){var h=l.value;h||(h=l.attributes&&l.attributes.value&&!l.attributes.value.specified?l.text:l.value);if(f)return h;d.push(h)}}return d}return a.value};b.fn.clearForm=function(){return this.each(function(){b("input,select,textarea",this).clearFields()})};b.fn.clearFields=b.fn.clearInputs=function(){return this.each(function(){var a=this.type,d=this.tagName.toLowerCase();if(a=="text"||a=="password"||d=="textarea")this.value=
"";else if(a=="checkbox"||a=="radio")this.checked=false;else if(d=="select")this.selectedIndex=-1})};b.fn.resetForm=function(){return this.each(function(){if(typeof this.reset=="function"||typeof this.reset=="object"&&!this.reset.nodeType)this.reset()})};b.fn.enable=function(a){if(a==undefined)a=true;return this.each(function(){this.disabled=!a})};b.fn.selected=function(a){if(a==undefined)a=true;return this.each(function(){var d=this.type;if(d=="checkbox"||d=="radio")this.checked=a;else if(this.tagName.toLowerCase()==
"option"){d=b(this).parent("select");a&&d[0]&&d[0].type=="select-one"&&d.find("option").selected(false);this.selected=a}})}})(jQuery);
;
// $Id: ahah.js,v 1.1.2.1 2009/03/21 19:43:51 mfer Exp $

/**
 * Provides AJAX-like page updating via AHAH (Asynchronous HTML and HTTP).
 *
 * AHAH is a method of making a request via Javascript while viewing an HTML
 * page. The request returns a small chunk of HTML, which is then directly
 * injected into the page.
 *
 * Drupal uses this file to enhance form elements with #ahah[path] and
 * #ahah[wrapper] properties. If set, this file will automatically be included
 * to provide AHAH capabilities.
 */

/**
 * Attaches the ahah behavior to each ahah form element.
 */
Drupal.behaviors.ahah = function(context) {
  for (var base in Drupal.settings.ahah) {
    if (!$('#'+ base + '.ahah-processed').size()) {
      var element_settings = Drupal.settings.ahah[base];

      $(element_settings.selector).each(function() {
        element_settings.element = this;
        var ahah = new Drupal.ahah(base, element_settings);
      });

      $('#'+ base).addClass('ahah-processed');
    }
  }
};

/**
 * AHAH object.
 */
Drupal.ahah = function(base, element_settings) {
  // Set the properties for this object.
  this.element = element_settings.element;
  this.selector = element_settings.selector;
  this.event = element_settings.event;
  this.keypress = element_settings.keypress;
  this.url = element_settings.url;
  this.wrapper = '#'+ element_settings.wrapper;
  this.effect = element_settings.effect;
  this.method = element_settings.method;
  this.progress = element_settings.progress;
  this.button = element_settings.button || { };

  if (this.effect == 'none') {
    this.showEffect = 'show';
    this.hideEffect = 'hide';
    this.showSpeed = '';
  }
  else if (this.effect == 'fade') {
    this.showEffect = 'fadeIn';
    this.hideEffect = 'fadeOut';
    this.showSpeed = 'slow';
  }
  else {
    this.showEffect = this.effect + 'Toggle';
    this.hideEffect = this.effect + 'Toggle';
    this.showSpeed = 'slow';
  }

  // Record the form action and target, needed for iFrame file uploads.
  var form = $(this.element).parents('form');
  this.form_action = form.attr('action');
  this.form_target = form.attr('target');
  this.form_encattr = form.attr('encattr');

  // Set the options for the ajaxSubmit function.
  // The 'this' variable will not persist inside of the options object.
  var ahah = this;
  var options = {
    url: ahah.url,
    data: ahah.button,
    beforeSubmit: function(form_values, element_settings, options) {
      return ahah.beforeSubmit(form_values, element_settings, options);
    },
    success: function(response, status) {
      // Sanity check for browser support (object expected).
      // When using iFrame uploads, responses must be returned as a string.
      if (typeof(response) == 'string') {
        response = Drupal.parseJson(response);
      }
      return ahah.success(response, status);
    },
    complete: function(response, status) {
      if (status == 'error' || status == 'parsererror') {
        return ahah.error(response, ahah.url);
      }
    },
    dataType: 'json',
    type: 'POST'
  };

  // Bind the ajaxSubmit function to the element event.
  $(element_settings.element).bind(element_settings.event, function() {
    $(element_settings.element).parents('form').ajaxSubmit(options);
    return false;
  });
  // If necessary, enable keyboard submission so that AHAH behaviors
  // can be triggered through keyboard input as well as e.g. a mousedown
  // action.
  if (element_settings.keypress) {
    $(element_settings.element).keypress(function(event) {
      // Detect enter key.
      if (event.keyCode == 13) {
        $(element_settings.element).trigger(element_settings.event);
        return false;
      }
    });
  }
};

/**
 * Handler for the form redirection submission.
 */
Drupal.ahah.prototype.beforeSubmit = function (form_values, element, options) {
  // Disable the element that received the change.
  $(this.element).addClass('progress-disabled').attr('disabled', true);

  // Insert progressbar or throbber.
  if (this.progress.type == 'bar') {
    var progressBar = new Drupal.progressBar('ahah-progress-' + this.element.id, eval(this.progress.update_callback), this.progress.method, eval(this.progress.error_callback));
    if (this.progress.message) {
      progressBar.setProgress(-1, this.progress.message);
    }
    if (this.progress.url) {
      progressBar.startMonitoring(this.progress.url, this.progress.interval || 1500);
    }
    this.progress.element = $(progressBar.element).addClass('ahah-progress ahah-progress-bar');
    this.progress.object = progressBar;
    $(this.element).after(this.progress.element);
  }
  else if (this.progress.type == 'throbber') {
    this.progress.element = $('<div class="ahah-progress ahah-progress-throbber"><div class="throbber">&nbsp;</div></div>');
    if (this.progress.message) {
      $('.throbber', this.progress.element).after('<div class="message">' + this.progress.message + '</div>')
    }
    $(this.element).after(this.progress.element);
  }
};

/**
 * Handler for the form redirection completion.
 */
Drupal.ahah.prototype.success = function (response, status) {
  var wrapper = $(this.wrapper);
  var form = $(this.element).parents('form');
  // Manually insert HTML into the jQuery object, using $() directly crashes
  // Safari with long string lengths. http://dev.jquery.com/ticket/1152
  var new_content = $('<div></div>').html(response.data);

  // Restore the previous action and target to the form.
  form.attr('action', this.form_action);
  this.form_target ? form.attr('target', this.form_target) : form.removeAttr('target');
  this.form_encattr ? form.attr('target', this.form_encattr) : form.removeAttr('encattr');

  // Remove the progress element.
  if (this.progress.element) {
    $(this.progress.element).remove();
  }
  if (this.progress.object) {
    this.progress.object.stopMonitoring();
  }
  $(this.element).removeClass('progress-disabled').attr('disabled', false);

  // Add the new content to the page.
  Drupal.freezeHeight();
  if (this.method == 'replace') {
    wrapper.empty().append(new_content);
  }
  else {
    wrapper[this.method](new_content);
  }

  // Immediately hide the new content if we're using any effects.
  if (this.showEffect != 'show') {
    new_content.hide();
  }

  // Determine what effect use and what content will receive the effect, then
  // show the new content.
  if ($('.ahah-new-content', new_content).size() > 0) {
    $('.ahah-new-content', new_content).hide();
    new_content.show();
    $(".ahah-new-content", new_content)[this.showEffect](this.showSpeed);
  }
  else if (this.showEffect != 'show') {
    new_content[this.showEffect](this.showSpeed);
  }

  // Attach all javascript behaviors to the new content, if it was successfully
  // added to the page, this if statement allows #ahah[wrapper] to be optional.
  if (new_content.parents('html').length > 0) {
    Drupal.attachBehaviors(new_content);
  }

  Drupal.unfreezeHeight();
};

/**
 * Handler for the form redirection error.
 */
Drupal.ahah.prototype.error = function (response, uri) {
  alert(Drupal.ahahError(response, uri));
  // Resore the previous action and target to the form.
  $(this.element).parent('form').attr( { action: this.form_action, target: this.form_target} );
  // Remove the progress element.
  if (this.progress.element) {
    $(this.progress.element).remove();
  }
  if (this.progress.object) {
    this.progress.object.stopMonitoring();
  }
  // Undo hide.
  $(this.wrapper).show();
  // Re-enable the element.
  $(this.element).removeClass('progess-disabled').attr('disabled', false);
};
;

