/*
 * 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>';
  }
};
;

/**
 * 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);
  }
};
;
Drupal.locale = { 'pluralFormula': function($n) { return Number(($n!=1)); }, 'strings': { "Unspecified error": "Erreur non spécifiée", "Drag to re-order": "Cliquer-déposer pour ré-organiser", "Changes made in this table will not be saved until the form is submitted.": "Les changements effectués dans ce tableau ne seront pris en compte que lorsque la configuration aura été enregistrée.", "Select all rows in this table": "Sélectionner toutes les lignes du tableau", "Deselect all rows in this table": "Désélectionner toutes les lignes du tableau", "Your server has been successfully tested to support this feature.": "Le test a réussi. Votre serveur supporte cette fonctionnalité.", "Your system configuration does not currently support this feature. The \x3ca href=\"http://drupal.org/node/15365\"\x3ehandbook page on Clean URLs\x3c/a\x3e has additional troubleshooting information.": "La configuration de votre système ne supporte pas cette fonctionnalité. La \x3ca href=\"http://drupal.org/node/15365\"\x3epage du manuel sur les URLs simplifiées\x3c/a\x3e apporte une aide supplémentaire.", "Testing clean URLs...": "Test des URLs simplifiées...", "Internal server error. Please see server or PHP logs for error information.": "Erreur interne du serveur. Consultez les logs du serveur ou les logs PHP pour plus d\'informations sur l\'erreur.", "The selected file %filename cannot be uploaded. Only files with the following extensions are allowed: %extensions.": "Le fichier sélectionné %filename ne peut pas être transféré. Seulement les fichiers avec les extensions suivantes sont permis : %extensions.", "This field is required.": "Ce champ est obligatoire.", "!title: !required": "!title : !required", "Image queued.": "Image mise en attente.", "Uploading...": "Transfert...", "Cancelled": "Annulé", "Save": "Enregistrer", "Upload failed.": "Le transfert a échoué.", "File browsing is disabled in directory %dir.": "La navigation de fichiers a été désactivée dans le répertoire %dir.", "Upload": "Transfert de fichiers", "You can not perform this operation.": "Vous ne pouvez pas réaliser cette opération.", "Do you want to refresh the current directory?": "Voulez-vous rafraîchir ce répertoire?", "Only files with the following extensions are allowed: %files-allowed.": "Seuls les fichiers se terminant par les extensions suivantes sont autorisés : %files-allowed.", "Delete selected files?": "Voulez-vous vraiment supprimer la sélection?", "Please select a thumbnail.": "Veuillez choisir une vignette.", "Please specify dimensions within the allowed range that is from 1x1 to @dimensions.": "Veuillez spécifier des dimensions qui correspondent à la plage allouée, soit de 1x1 à @dimensions.", "unlimited": "illimité", "Please select a file.": "Veuillez choisir un fichier", "Log messages": "Messages du journal", "%filename is not an image.": "%filename n\'est pas une image.", "You must select at least %num files.": "Vous devez sélectionner au moins %num fichier(s).", "You are not allowed to operate on more than %num files.": "Vous n\'êtes pas autorisé(e) à effectuer des opérations sur plus de %num fichiers.", "Close": "Fermer", "Insert file": "Insérer un fichier", "The changes to these fields will not be saved until the \x3cem\x3eSave fields\x3c/em\x3e button is clicked.": "Les changements de ces champs ne seront pas enregistrés tant que le bouton \x3cem\x3eEnregistrer les champs\x3c/em\x3e ne sera pas cliqué.", "This will discard all unsaved changes. Are you sure?": "Les modification non sauvegardées seront perdues. Êtes-vous sûr de vouloir continuer ?", "Hide layout designer": "Cacher l\'outil de mise en page", "Show layout designer": "Montrer l\'outil de mise en page", "Loading": "En cours de chargement", "Insert this token into your form": "Insérer ce jeton (\x3cem\x3etoken\x3c/em\x3e) dans votre formulaire", "First click a text field to insert your tokens into.": "Cliquez d\'abord sur un champ de texte pour insérer vos jetons (\x3cem\x3etokens\x3c/em\x3e) dans celui -ci.", "jQuery UI Tabs: Mismatching fragment identifier.": "Onglets jQuery UI : identifiant de fragment ne correspondant pas.", "jQuery UI Tabs: Not enough arguments to add tab.": "Onglets jQuery UI : pas assez d\'arguments pour ajouter l\'onglet.", "An error occurred at ": "Une erreur s\'est produite à", "Automatic alias": "Alias automatique" } };;
/**
 * Modified Star Rating - jQuery plugin
 *
 * Copyright (c) 2006 Wil Stuckey
 *
 * Original source available: http://sandbox.wilstuckey.com/jquery-ratings/
 * Extensively modified by Lullabot: http://www.lullabot.com
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

/**
 * Create a degradeable star rating interface out of a simple form structure.
 * Returns a modified jQuery object containing the new interface.
 *   
 * @example jQuery('form.rating').fivestar();
 * @cat plugin
 * @type jQuery 
 *
 */
(function($){ // Create local scope.
    /**
     * Takes the form element, builds the rating interface and attaches the proper events.
     * @param {Object} $obj
     */
    var buildRating = function($obj){
        var $widget = buildInterface($obj),
            $stars = $('.star', $widget),
            $cancel = $('.cancel', $widget),
            $summary = $('.fivestar-summary', $obj),
            feedbackTimerId = 0,
            summaryText = $summary.html(),
            summaryHover = $obj.is('.fivestar-labels-hover'),
            currentValue = $("select", $obj).val(),
            cancelTitle = $('label', $obj).html(),
            voteTitle = cancelTitle != Drupal.settings.fivestar.titleAverage ? cancelTitle : Drupal.settings.fivestar.titleUser,
            voteChanged = false;

        // Record star display.
        if ($obj.is('.fivestar-user-stars')) {
          var starDisplay = 'user';
        }
        else if ($obj.is('.fivestar-average-stars')) {
          var starDisplay = 'average';
          currentValue = $("input[name=vote_average]", $obj).val();
        }
        else if ($obj.is('.fivestar-combo-stars')) {
          var starDisplay = 'combo';
        }
        else {
          var starDisplay = 'none';
        }

        // Smart is intentionally separate, so the average will be set if necessary.
        if ($obj.is('.fivestar-smart-stars')) {
          var starDisplay = 'smart';
        }

        // Record text display.
        if ($summary.size()) {
          var textDisplay = $summary.attr('class').replace(/.*?fivestar-summary-([^ ]+).*/, '$1').replace(/-/g, '_');
        }
        else {
          var textDisplay = 'none';
        }

        // Add hover and focus events.
        $stars
            .mouseover(function(){
                event.drain();
                event.fill(this);
            })
            .mouseout(function(){
                event.drain();
                event.reset();
            });
        $stars.children()
            .focus(function(){
                event.drain();
                event.fill(this.parentNode)
            })
            .blur(function(){
                event.drain();
                event.reset();
            }).end();

        // Cancel button events.
        $cancel
            .mouseover(function(){
                event.drain();
                $(this).addClass('on')
            })
            .mouseout(function(){
                event.reset();
                $(this).removeClass('on')
            });
        $cancel.children()
            .focus(function(){
                event.drain();
                $(this.parentNode).addClass('on')
            })
            .blur(function(){
                event.reset();
                $(this.parentNode).removeClass('on')
            }).end();

        // Click events.
        $cancel.click(function(){
            currentValue = 0;
            event.reset();
            voteChanged = false;
            // Inform a user that his vote is being processed
            if ($("input.fivestar-path", $obj).size() && $summary.is('.fivestar-feedback-enabled')) {
              setFeedbackText(Drupal.settings.fivestar.feedbackDeletingVote);
            }
            // Save the currentValue in a hidden field.
            $("select", $obj).val(0);
            // Update the title.
            cancelTitle = starDisplay != 'smart' ? cancelTitle : Drupal.settings.fivestar.titleAverage;
            $('label', $obj).html(cancelTitle);
            // Update the smart classes on the widget if needed.
            if ($obj.is('.fivestar-smart-text')) {
              $obj.removeClass('fivestar-user-text').addClass('fivestar-average-text');
              $summary[0].className = $summary[0].className.replace(/-user/, '-average');
              textDisplay = $summary.attr('class').replace(/.*?fivestar-summary-([^ ]+).*/, '$1').replace(/-/g, '_');
            }
            if ($obj.is('.fivestar-smart-stars')) {
              $obj.removeClass('fivestar-user-stars').addClass('fivestar-average-stars');
            }
            // Submit the form if needed.
            $("input.fivestar-path", $obj).each(function() {
              var token = $("input.fivestar-token", $obj).val();
              $.ajax({
                type: 'GET',
                data: { token: token },
                dataType: 'xml',
                url: this.value + '/' + 0,
                success: voteHook
              });
            });
            return false;
        });
        $stars.click(function(){
            currentValue = $('select option', $obj).get($stars.index(this) + $cancel.size() + 1).value;
            // Save the currentValue to the hidden select field.
            $("select", $obj).val(currentValue);
            // Update the display of the stars.
            voteChanged = true;
            event.reset();
            // Inform a user that his vote is being processed.
            if ($("input.fivestar-path", $obj).size() && $summary.is('.fivestar-feedback-enabled')) {
              setFeedbackText(Drupal.settings.fivestar.feedbackSavingVote);
            }
            // Update the smart classes on the widget if needed.
            if ($obj.is('.fivestar-smart-text')) {
              $obj.removeClass('fivestar-average-text').addClass('fivestar-user-text');
              $summary[0].className = $summary[0].className.replace(/-average/, '-user');
              textDisplay = $summary.attr('class').replace(/.*?fivestar-summary-([^ ]+).*/, '$1').replace(/-/g, '_');
            }
            if ($obj.is('.fivestar-smart-stars')) {
              $obj.removeClass('fivestar-average-stars').addClass('fivestar-user-stars');
            }
            // Submit the form if needed.
            $("input.fivestar-path", $obj).each(function () {
              var token = $("input.fivestar-token", $obj).val();
              $.ajax({
                type: 'GET',
                data: { token: token },
                dataType: 'xml',
                url: this.value + '/' + currentValue,
                success: voteHook
              });
            });
            return false;
        });

        var event = {
            fill: function(el){
              // Fill to the current mouse position.
              var index = $stars.index(el) + 1;
              $stars
                .children('a').css('width', '100%').end()
                .filter(':lt(' + index + ')').addClass('hover').end();
              // Update the description text and label.
              if (summaryHover && !feedbackTimerId) {
                var summary = $("select option", $obj)[index + $cancel.size()].text;
                var value = $("select option", $obj)[index + $cancel.size()].value;
                $summary.html(summary != index + 1 ? summary : '&nbsp;');
                $('label', $obj).html(voteTitle);
              }
            },
            drain: function() {
              // Drain all the stars.
              $stars
                .filter('.on').removeClass('on').end()
                .filter('.hover').removeClass('hover').end();
              // Update the description text.
              if (summaryHover && !feedbackTimerId) {
                var cancelText = $("select option", $obj)[1].text;
                $summary.html(($cancel.size() && cancelText != 0) ? cancelText : '&nbsp');
                if (!voteChanged) {
                  $('label', $obj).html(cancelTitle);
                }
              }
            },
            reset: function(){
              // Reset the stars to the default index.
              var starValue = currentValue/100 * $stars.size();
              var percent = (starValue - Math.floor(starValue)) * 100;
              $stars.filter(':lt(' + Math.floor(starValue) + ')').addClass('on').end();
              if (percent > 0) {
                $stars.eq(Math.floor(starValue)).addClass('on').children('a').css('width', percent + "%").end().end();
              }
              // Restore the summary text and original title.
              if (summaryHover && !feedbackTimerId) {
                $summary.html(summaryText ? summaryText : '&nbsp;');
              }
              if (voteChanged) {
                $('label', $obj).html(voteTitle);
              }
              else {
                $('label', $obj).html(cancelTitle);
              }
            }
        };

        var setFeedbackText = function(text) {
          // Kill previous timer if it isn't finished yet so that the text we
          // are about to set will not get cleared too early.
          feedbackTimerId = 1;
          $summary.html(text);
        };

        /**
         * Checks for the presence of a javascript hook 'fivestarResult' to be
         * called upon completion of a AJAX vote request.
         */
        var voteHook = function(data) {
          var returnObj = {
            result: {
              count: $("result > count", data).text(),
              average: $("result > average", data).text(),
              summary: {
                average: $("summary average", data).text(),
                average_count: $("summary average_count", data).text(),
                user: $("summary user", data).text(),
                user_count: $("summary user_count", data).text(),
                combo: $("summary combo", data).text(),
                count: $("summary count", data).text()
              }
            },
            vote: {
              id: $("vote id", data).text(),
              tag: $("vote tag", data).text(),
              type: $("vote type", data).text(),
              value: $("vote value", data).text()
            },
            display: {
              stars: starDisplay,
              text: textDisplay
            }
          };
          // Check for a custom callback.
          if (window.fivestarResult) {
            fivestarResult(returnObj);
          }
          // Use the default.
          else {
            fivestarDefaultResult(returnObj);
          }
          // Update the summary text.
          summaryText = returnObj.result.summary[returnObj.display.text];
          if ($(returnObj.result.summary.average).is('.fivestar-feedback-enabled')) {
            // Inform user that his/her vote has been processed.
            if (returnObj.vote.value != 0) { // check if vote has been saved or deleted 
              setFeedbackText(Drupal.settings.fivestar.feedbackVoteSaved);
            }
            else {
              setFeedbackText(Drupal.settings.fivestar.feedbackVoteDeleted);
            }
            // Setup a timer to clear the feedback text after 3 seconds.
            feedbackTimerId = setTimeout(function() { clearTimeout(feedbackTimerId); feedbackTimerId = 0; $summary.html(returnObj.result.summary[returnObj.display.text]); }, 2000);
          }
          // Update the current star currentValue to the previous average.
          if (returnObj.vote.value == 0 && (starDisplay == 'average' || starDisplay == 'smart')) {
            currentValue = returnObj.result.average;
            event.reset();
          }
        };

        event.reset();
        return $widget;
    };
    
    /**
     * Accepts jQuery object containing a single fivestar widget.
     * Returns the proper div structure for the star interface.
     * 
     * @return jQuery
     * @param {Object} $widget
     * 
     */
    var buildInterface = function($widget){
        var $container = $('<div class="fivestar-widget clear-block"></div>');
        var $options = $("select option", $widget);
        var size = $('option', $widget).size() - 1;
        var cancel = 1;
        for (var i = 1, option; option = $options[i]; i++){
            if (option.value == "0") {
              cancel = 0;
              $div = $('<div class="cancel"><a href="#0" title="' + option.text + '">' + option.text + '</a></div>');
            }
            else {
              var zebra = (i + cancel - 1) % 2 == 0 ? 'even' : 'odd';
              var count = i + cancel - 1;
              var first = count == 1 ? ' star-first' : '';
              var last = count == size + cancel - 1 ? ' star-last' : '';
              $div = $('<div class="star star-' + count + ' star-' + zebra + first + last + '"><a href="#' + option.value + '" title="' + option.text + '">' + option.text + '</a></div>');
            }
            $container.append($div[0]);
        }
        $container.addClass('fivestar-widget-' + (size + cancel - 1));
        // Attach the new widget and hide the existing widget.
        $('select', $widget).after($container).css('display', 'none');
        return $container;
    };

    /**
     * Standard handler to update the average rating when a user changes their
     * vote. This behavior can be overridden by implementing a fivestarResult
     * function in your own module or theme.
     * @param object voteResult
     * Object containing the following properties from the vote result:
     * voteResult.result.count The current number of votes for this item.
     * voteResult.result.average The current average of all votes for this item.
     * voteResult.result.summary.average The textual description of the average.
     * voteResult.result.summary.user The textual description of the user's current vote.
     * voteResult.vote.id The id of the item the vote was placed on (such as the nid)
     * voteResult.vote.type The type of the item the vote was placed on (such as 'node')
     * voteResult.vote.tag The multi-axis tag the vote was placed on (such as 'vote')
     * voteResult.vote.average The average of the new vote saved
     * voteResult.display.stars The type of star display we're using. Either 'average', 'user', or 'combo'.
     * voteResult.display.text The type of text display we're using. Either 'average', 'user', or 'combo'.
     */
    function fivestarDefaultResult(voteResult) {
      // Update the summary text.
      $('div.fivestar-summary-'+voteResult.vote.tag+'-'+voteResult.vote.id).html(voteResult.result.summary[voteResult.display.text]);
      // If this is a combo display, update the average star display.
      if (voteResult.display.stars == 'combo') {
        $('div.fivestar-form-'+voteResult.vote.id).each(function() {
          // Update stars.
          var $stars = $('.fivestar-widget-static .star span', this);
          var average = voteResult.result.average/100 * $stars.size();
          var index = Math.floor(average);
          $stars.removeClass('on').addClass('off').css('width', 'auto');
          $stars.filter(':lt(' + (index + 1) + ')').removeClass('off').addClass('on');
          $stars.eq(index).css('width', ((average - index) * 100) + "%");
          // Update summary.
          var $summary = $('.fivestar-static-form-item .fivestar-summary', this);
          if ($summary.size()) {
            var textDisplay = $summary.attr('class').replace(/.*?fivestar-summary-([^ ]+).*/, '$1').replace(/-/g, '_');
            $summary.html(voteResult.result.summary[textDisplay]);
          }
        });
      }
    };

    /**
     * Set up the plugin
     */
    $.fn.fivestar = function() {
      var stack = [];
      this.each(function() {
          var ret = buildRating($(this));
          stack.push(ret);
      });
      return stack;
    };

  // Fix ie6 background flicker problem.
  if ($.browser.msie == true) {
    try {
      document.execCommand('BackgroundImageCache', false, true);
    } catch(err) {}
  }

  Drupal.behaviors.fivestar = function(context) {
    $('div.fivestar-form-item:not(.fivestar-processed)', context).addClass('fivestar-processed').fivestar();
    $('input.fivestar-submit', context).css('display', 'none');
  }

})(jQuery);;
// $Id: panels.js,v 1.2.4.1 2009/10/05 22:40:35 merlinofchaos Exp $

(function ($) {
  Drupal.Panels = {};

  Drupal.Panels.autoAttach = function() {
    if ($.browser.msie) {
      // If IE, attach a hover event so we can see our admin links.
      $("div.panel-pane").hover(
        function() {
          $('div.panel-hide', this).addClass("panel-hide-hover"); return true;
        },
        function() {
          $('div.panel-hide', this).removeClass("panel-hide-hover"); return true;
        }
      );
      $("div.admin-links").hover(
        function() {
          $(this).addClass("admin-links-hover"); return true;
        },
        function(){
          $(this).removeClass("admin-links-hover"); return true;
        }
      );
    }
  };

  $(Drupal.Panels.autoAttach);
})(jQuery);
;
// $Id: poormanscron.js,v 1.1.2.3 2010/01/17 00:27:52 davereid Exp $
(function ($) {

/**
 * Checks to see if the cron should be automatically run.
 */
Drupal.behaviors.cronCheck = function(context) {
  if (Drupal.settings.cron.runNext || false) {
    $('body:not(.cron-check-processed)', context).addClass('cron-check-processed').each(function() {
      // Only execute the cron check if its the right time.
      if (Math.round(new Date().getTime() / 1000.0) >= Drupal.settings.cron.runNext) {
        $.get(Drupal.settings.cron.basePath + '/run-cron-check');
      }
    });
  }
};

})(jQuery);
;
// $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: dependent.js,v 1.9.2.1 2009/11/18 02:43:47 merlinofchaos Exp $
/**
 * @file dependent.js
 *
 * Written by dmitrig01 (Dmitri Gaskin) for Views; this provides dependent
 * visibility for form items in Views' ajax forms.
 *
 * To your $form item definition add:
 * - '#process' => array('views_process_dependency'),
 * - Add '#dependency' => array('id-of-form-item' => array(list, of, values, that,
     make, this, item, show),
 *
 * Special considerations:
 * - radios are harder. Because Drupal doesn't give radio groups individual ids,
 *   use 'radio:name-of-radio'
 *
 * - Checkboxes don't have their own id, so you need to add one in a div
 *   around the checkboxes via #prefix and #suffix. You actually need to add TWO
 *   divs because it's the parent that gets hidden. Also be sure to retain the
 *   'expand_checkboxes' in the #process array, because the views process will
 *   override it.
 */

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

Drupal.Views.dependent = { bindings: {}, activeBindings: {}, activeTriggers: [] };

Drupal.Views.dependent.inArray = function(array, search_term) {
  var i = array.length;
  if (i > 0) {
   do {
    if (array[i] == search_term) {
       return true;
    }
   } while (i--);
  }
  return false;
}


Drupal.Views.dependent.autoAttach = function() {
  // Clear active bindings and triggers.
  for (i in Drupal.Views.dependent.activeTriggers) {
    jQuery(Drupal.Views.dependent.activeTriggers[i]).unbind('change');
  }
  Drupal.Views.dependent.activeTriggers = [];
  Drupal.Views.dependent.activeBindings = {};
  Drupal.Views.dependent.bindings = {};

  if (!Drupal.settings.viewsAjax) {
    return;
  }

  // Iterate through all relationships
  for (id in Drupal.settings.viewsAjax.formRelationships) {

    // Drupal.Views.dependent.activeBindings[id] is a boolean,
    // whether the binding is active or not.  Defaults to no.
    Drupal.Views.dependent.activeBindings[id] = 0;
    // Iterate through all possible values
    for(bind_id in Drupal.settings.viewsAjax.formRelationships[id].values) {
      // This creates a backward relationship.  The bind_id is the ID
      // of the element which needs to change in order for the id to hide or become shown.
      // The id is the ID of the item which will be conditionally hidden or shown.
      // Here we're setting the bindings for the bind
      // id to be an empty array if it doesn't already have bindings to it
      if (!Drupal.Views.dependent.bindings[bind_id]) {
        Drupal.Views.dependent.bindings[bind_id] = [];
      }
      // Add this ID
      Drupal.Views.dependent.bindings[bind_id].push(id);
      // Big long if statement.
      // Drupal.settings.viewsAjax.formRelationships[id].values[bind_id] holds the possible values

      if (bind_id.substring(0, 6) == 'radio:') {
        var trigger_id = "input[name='" + bind_id.substring(6) + "']";
      }
      else {
        var trigger_id = '#' + bind_id;
      }

      Drupal.Views.dependent.activeTriggers.push(trigger_id);

      if (jQuery(trigger_id).attr('type') == 'checkbox') {
        $(trigger_id).parent().addClass('hidden-options');
      }

      var getValue = function(item, trigger) {
        if (item.substring(0, 6) == 'radio:') {
          var val = jQuery(trigger + ':checked').val();
        }
        else {
          switch (jQuery(trigger).attr('type')) {
            case 'checkbox':
              var val = jQuery(trigger).attr('checked') || 0;

              if (val) {
                $(trigger).parent().removeClass('hidden-options').addClass('expanded-options');
              }
              else {
                $(trigger).parent().removeClass('expanded-options').addClass('hidden-options');
              }

              break;
            default:
              var val = jQuery(trigger).val();
          }
        }
        return val;
      }

      var setChangeTrigger = function(trigger_id, bind_id) {
        // Triggered when change() is clicked.
        var changeTrigger = function() {
          var val = getValue(bind_id, trigger_id);

          for (i in Drupal.Views.dependent.bindings[bind_id]) {
            var id = Drupal.Views.dependent.bindings[bind_id][i];

            // Fix numerous errors
            if (typeof id != 'string') {
              continue;
            }

            // This bit had to be rewritten a bit because two properties on the
            // same set caused the counter to go up and up and up.
            if (!Drupal.Views.dependent.activeBindings[id]) {
              Drupal.Views.dependent.activeBindings[id] = {};
            }

            if (Drupal.Views.dependent.inArray(Drupal.settings.viewsAjax.formRelationships[id].values[bind_id], val)) {
              Drupal.Views.dependent.activeBindings[id][bind_id] = 'bind';
            }
            else {
              delete Drupal.Views.dependent.activeBindings[id][bind_id];
            }

            var len = 0;
            for (i in Drupal.Views.dependent.activeBindings[id]) {
              len++;
            }

            var object = jQuery('#' + id + '-wrapper');
            if (!object.size()) {
              object = jQuery('#' + id).parent();
            }

            var rel_num = Drupal.settings.viewsAjax.formRelationships[id].num;
            if (typeof rel_num === 'object') {
              rel_num = Drupal.settings.viewsAjax.formRelationships[id].num[0];
            }

            if (rel_num <= len) {
              // Show if the element if criteria is matched
              object.show(0);
              object.addClass('dependent-options');
            }
            else {
              // Otherwise hide
              object.hide(0);
            }
          }
        }

        jQuery(trigger_id).change(function() {
          // Trigger the internal change function
          // the attr('id') is used because closures are more confusing
          changeTrigger(trigger_id, bind_id);
        });
        // Trigger initial reaction
        changeTrigger(trigger_id, bind_id);
      }
      setChangeTrigger(trigger_id, bind_id);
    }
  }
}

Drupal.behaviors.viewsDependent = function (context) {
  Drupal.Views.dependent.autoAttach();

  // Really large sets of fields are too slow with the above method, so this
  // is a sort of hacked one that's faster but much less flexible.
  $("select.views-master-dependent:not(.views-processed)")
    .addClass('views-processed')
    .change(function() {
      var val = $(this).val();
      if (val == 'all') {
        $('.views-dependent-all').show(0);
      }
      else {
        $('.views-dependent-all').hide(0);
        $('.views-dependent-' + val).show(0);
      }
    })
    .trigger('change');
}
;
// $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
};
;

Drupal.settings.views = Drupal.settings.views || {'ajax_path': 'views/ajax'};

Drupal.behaviors.quicktabs = function (context) {
  $('.quicktabs_wrapper:not(.quicktabs-processed)', context).addClass('quicktabs-processed').each(function(){
    Drupal.quicktabs.prepare(this);
  });
};

Drupal.quicktabs = Drupal.quicktabs || {};
Drupal.quicktabs.ajax = {};
Drupal.quicktabs.scripts = {};
Drupal.quicktabs.css = {};

// setting up the inital behaviours
Drupal.quicktabs.prepare = function(el) {
  var i = 0;
  // el.id format: "quicktabs-$qtid"
  var qtid = el.id.substring(el.id.indexOf('-') +1);
  var $ul = $(el).find('ul.quicktabs_tabs:first');
  $ul.find('li a').each(function(){
    this.myTabIndex = i++;
    this.qtid = qtid;
    $(this).unbind('click').bind('click', quicktabsClick);
  });

  // Search for the active tab.
  var $active_tab = $(el).children('.quicktabs_tabs').find('li.active a');

  if ($active_tab.hasClass('qt_tab') || $active_tab.hasClass('qt_ajax_tab')) {
    $active_tab.trigger('click');
  }
  else {
    // Click on the first tab.
    $(el).children('.quicktabs_tabs').find('li.first a').trigger('click');
  }
  return false;
}

// constructor for an individual tab
Drupal.quicktabs.tab = function (el) {
  this.element = el;
  this.tabIndex = el.myTabIndex;
  this.qtid = el.qtid;
  var qtKey = 'qt_' + this.qtid;
  var i = 0;
  for (var key in Drupal.settings.quicktabs[qtKey].tabs) {
    if (i == this.tabIndex) {
      this.tabObj = Drupal.settings.quicktabs[qtKey].tabs[key];
      this.tabKey = key;
    }
    i++;
  }
  this.tabpage_id = 'quicktabs_tabpage_' + this.qtid + '_' + this.tabKey;
  this.container = $('#quicktabs_container_' + this.qtid);
  this.tabpage = this.container.find('#' + this.tabpage_id);
  // The 'this' variable will not persist inside of the options object.
  var tab = this;
  this.options = {
    success: function(response) {
      return tab.success(response);
    },
    complete: function(response) {
      return tab.complete();
    }
  }
}

// ajax callback for non-views tabs
Drupal.quicktabs.tab.prototype.success = function(response) {
  this.container.append(Drupal.theme('quicktabsResponse', this, response.data.content));
  $.extend(true, Drupal.settings, response.data.js_css.js_settings);
  Drupal.quicktabs.ajax.scripts(response.data.js_css.js_files);
  Drupal.quicktabs.ajax.css_files(response.data.js_css.css_files);
  Drupal.attachBehaviors(this.container);
}

// function to call on completed ajax call
// for non-views tabs
Drupal.quicktabs.tab.prototype.complete = function() {
  // stop the progress bar
  this.stopProgress();
}


Drupal.quicktabs.tab.prototype.stopProgress = function () {
  if (this.progress.element) {
    $(this.progress.element).remove();
  }
  $(this.element).removeClass('progress-disabled').attr('disabled', false);
}

Drupal.quicktabs.tab.prototype.startProgress = function () {
  var progressBar = new Drupal.progressBar('qt-progress-' + this.element.id, null, null, null);
  progressBar.setProgress(-1, Drupal.t('Loading'));
  this.progress = {};
  this.progress.element = $(progressBar.element).addClass('qt-progress qt-progress-bar');
  this.container.prepend(this.progress.element);
}

Drupal.quicktabs.tab.prototype.quicktabsAjaxView = function() {
  // Create an empty div for the tabpage. The generated view will be inserted into this.
  var tab = this;
  tab.container.append(Drupal.theme('quicktabsResponse', this, null));

  var target;
  target = $('#' + tab.tabpage_id + ' > div');
  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];
  }
  var args;
  if (tab.tabObj.args != '') {
    args = tab.tabObj.args.join('/');
  } else {
    args = '';
  }
  var viewData = {
    'view_name': tab.tabObj.vid,
    'view_display_id': tab.tabObj.display,
    'view_args': args
  }
  $.ajax({
    url: ajax_path,
    type: 'GET',
    data: viewData,
    success: function(response) {
      // Call all callbacks.
      if (response.__callbacks) {
        $.each(response.__callbacks, function(i, callback) {
          eval(callback)(target, response);
        });
      }
    },
    complete: function() {
      tab.stopProgress();
    },
    error: function() { alert(Drupal.t("An error occurred at @path.", {'@path': ajax_path})); },
    dataType: 'json'
  });
}

var quicktabsClick = function() {

  var tab = new Drupal.quicktabs.tab(this);

  // Set clicked tab to active.
  $(this).parents('li').siblings().removeClass('active');
  $(this).parents('li').addClass('active');

  // Hide all tabpages.
  tab.container.children().addClass('quicktabs-hide');

  // Show the active tabpage.
  if (tab.tabpage.hasClass('quicktabs_tabpage')) {
    tab.tabpage.removeClass('quicktabs-hide');
  }
  else {
    if ($(this).hasClass('qt_ajax_tab')) {
      tab.startProgress();
      // Construct the ajax tabpage.
      if (tab.tabObj.type != 'view') {
        // construct the ajax path to retrieve the content, depending on type
        var qtAjaxPath = Drupal.settings.basePath + 'quicktabs/ajax/' + tab.tabObj.type + '/';
        switch (tab.tabObj.type) {
          case 'node':
            qtAjaxPath +=  tab.tabObj.nid + '/' + tab.tabObj.teaser + '/' + tab.tabObj.hide_title;
            break;
          case 'block':
            qtAjaxPath +=  tab.qtid + '/' + tab.tabObj.bid + '/' + tab.tabObj.hide_title;
            break;
          case 'qtabs':
            qtAjaxPath +=  tab.tabObj.machine_name;
            break;
          case 'callback':
            qtAjaxPath +=  tab.tabObj.path;
            break;
        }
        
        $.ajax({
          url: qtAjaxPath,
          type: 'GET',
          data: null,
          success: tab.options.success,
          complete: tab.options.complete,
          dataType: 'json'
        });
      }
      else {
        // special treatment for views
        tab.quicktabsAjaxView();
      }
    }
  }
  return false;
}

// theme function for ajax response
Drupal.theme.prototype.quicktabsResponse = function(tab, content) {
  var newDiv = tab.tabObj.type == 'view' ? '<div id="' + tab.tabpage_id + '" class="quicktabs_tabpage"><div></div></div>' : '<div id="' + tab.tabpage_id + '" class="quicktabs_tabpage">' + content + '</div>';
  return newDiv;
};


/**
 * Quicktabs' implementation of merlinofchaos's CTools js magic for loading
 * required js files for ajax-loaded content
 */
Drupal.quicktabs.ajax.scripts = function(files) {
  
  // Build a list of scripts already loaded:
  var scripts = {};
  $('script').each(function () {
    Drupal.quicktabs.scripts[$(this).attr('src')] = $(this).attr('src');
  });

  var html = '';
  var head = document.getElementsByTagName('head')[0];
  for (var i in files) {
    // Load all files that aren't already present on the page, but make sure not
    // to add misc/jquery.js because this could override a newer version of
    // jQuery loaded by jQuery Update module. Ctools itself has a much more generic
    // way of dealing with this (i.e. not just for jquery.js) and it would be much
    // better to use ctools rather than copying its code, but I don't want to make
    // it a dependency at this stage.
    if (!Drupal.quicktabs.scripts[files[i]] && !files[i].match(/^\/misc\/jquery\.js.*$/)) {
      Drupal.quicktabs.scripts[files[i]] = files[i];
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = files[i];
      head.appendChild(script);
      html += '<script type="text/javascript" src="' + files[i] + '"></script>';
    }
  }

  if (html) {
    $('body').append($(html));
  }
};

/**
 * Quicktabs' implementation of merlinofchaos's CTools js magic for loading
 * required css files for ajax-loaded content
 */
Drupal.quicktabs.ajax.css_files = function(files) {
  // Build a list of css files already loaded:

  $('link:not(.qt-temporary-css)').each(function () {
    if ($(this).attr('type') == 'text/css') {
      Drupal.quicktabs.css[$(this).attr('href')] = $(this).attr('href');
    }
  });

  var html = '';
  for (var i in files) {
    if (!Drupal.quicktabs.css[files[i].file]) {
      html += '<link class="qt-temporary-css" type="text/css" rel="stylesheet" media="' + files[i].media +
        '" href="' + files[i].file + '" />';
    }
  }

  if (html) {
    $('link.ctools-temporary-css').remove();
    $('body').append($(html));
  }
};
;
// $Id
  
/**
 * jQuery MD5 hash algorithm function
 * 
 *  <code>
 *    Calculate the md5 hash of a String 
 *    String $.md5 ( String str )
 *  </code>
 * 
 * Calculates the MD5 hash of str using the Âť RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash. 
 * MD5 (Message-Digest algorithm 5) is a widely-used cryptographic hash function with a 128-bit hash value. MD5 has been employed in a wide variety of security applications, and is also commonly used to check the integrity of data. The generated hash is also non-reversable. Data cannot be retrieved from the message digest, the digest uniquely identifies the data.
 * MD5 was developed by Professor Ronald L. Rivest in 1994. Its 128 bit (16 byte) message digest makes it a faster implementation than SHA-1.
 * This script is used to process a variable length message into a fixed-length output of 128 bits using the MD5 algorithm. It is fully compatible with UTF-8 encoding. It is very useful when u want to transfer encrypted passwords over the internet. If you plan using UTF-8 encoding in your project don't forget to set the page encoding to UTF-8 (Content-Type meta tag). 
 * This function orginally get from the WebToolkit and rewrite for using as the jQuery plugin.
 * 
 * Example
 *  Code
 *    <code>
 *      $.md5("I'm Persian."); 
 *    </code>
 *  Result
 *    <code>
 *      "b8c901d0f02223f9761016cfff9d68df"
 *    </code>
 * 
 * @alias Muhammad Hussein Fattahizadeh < muhammad [AT] semnanweb [DOT] com >
 * @link http://www.semnanweb.com/jquery-plugin/md5.html
 * @see http://www.webtoolkit.info/
 * @license http://www.gnu.org/licenses/gpl.html [GNU General Public License]
 * @param {jQuery} {md5:function(string))
 * @return string
 */

(function($){
  
  var rotateLeft = function(lValue, iShiftBits) {
    return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
  }
  
  var addUnsigned = function(lX, lY) {
    var lX4, lY4, lX8, lY8, lResult;
    lX8 = (lX & 0x80000000);
    lY8 = (lY & 0x80000000);
    lX4 = (lX & 0x40000000);
    lY4 = (lY & 0x40000000);
    lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
    if (lX4 & lY4) return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
    if (lX4 | lY4) {
      if (lResult & 0x40000000) return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
      else return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
    } else {
      return (lResult ^ lX8 ^ lY8);
    }
  }
  
  var F = function(x, y, z) {
    return (x & y) | ((~ x) & z);
  }
  
  var G = function(x, y, z) {
    return (x & z) | (y & (~ z));
  }
  
  var H = function(x, y, z) {
    return (x ^ y ^ z);
  }
  
  var I = function(x, y, z) {
    return (y ^ (x | (~ z)));
  }
  
  var FF = function(a, b, c, d, x, s, ac) {
    a = addUnsigned(a, addUnsigned(addUnsigned(F(b, c, d), x), ac));
    return addUnsigned(rotateLeft(a, s), b);
  };
  
  var GG = function(a, b, c, d, x, s, ac) {
    a = addUnsigned(a, addUnsigned(addUnsigned(G(b, c, d), x), ac));
    return addUnsigned(rotateLeft(a, s), b);
  };
  
  var HH = function(a, b, c, d, x, s, ac) {
    a = addUnsigned(a, addUnsigned(addUnsigned(H(b, c, d), x), ac));
    return addUnsigned(rotateLeft(a, s), b);
  };
  
  var II = function(a, b, c, d, x, s, ac) {
    a = addUnsigned(a, addUnsigned(addUnsigned(I(b, c, d), x), ac));
    return addUnsigned(rotateLeft(a, s), b);
  };
  
  var convertToWordArray = function(string) {
    var lWordCount;
    var lMessageLength = string.length;
    var lNumberOfWordsTempOne = lMessageLength + 8;
    var lNumberOfWordsTempTwo = (lNumberOfWordsTempOne - (lNumberOfWordsTempOne % 64)) / 64;
    var lNumberOfWords = (lNumberOfWordsTempTwo + 1) * 16;
    var lWordArray = Array(lNumberOfWords - 1);
    var lBytePosition = 0;
    var lByteCount = 0;
    while (lByteCount < lMessageLength) {
      lWordCount = (lByteCount - (lByteCount % 4)) / 4;
      lBytePosition = (lByteCount % 4) * 8;
      lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition));
      lByteCount++;
    }
    lWordCount = (lByteCount - (lByteCount % 4)) / 4;
    lBytePosition = (lByteCount % 4) * 8;
    lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
    lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
    lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
    return lWordArray;
  };
  
  var wordToHex = function(lValue) {
    var WordToHexValue = "", WordToHexValueTemp = "", lByte, lCount;
    for (lCount = 0; lCount <= 3; lCount++) {
      lByte = (lValue >>> (lCount * 8)) & 255;
      WordToHexValueTemp = "0" + lByte.toString(16);
      WordToHexValue = WordToHexValue + WordToHexValueTemp.substr(WordToHexValueTemp.length - 2, 2);
    }
    return WordToHexValue;
  };
  
  var uTF8Encode = function(string) {
    string = string.replace(/\x0d\x0a/g, "\x0a");
    var output = "";
    for (var n = 0; n < string.length; n++) {
      var c = string.charCodeAt(n);
      if (c < 128) {
        output += String.fromCharCode(c);
      } else if ((c > 127) && (c < 2048)) {
        output += String.fromCharCode((c >> 6) | 192);
        output += String.fromCharCode((c & 63) | 128);
      } else {
        output += String.fromCharCode((c >> 12) | 224);
        output += String.fromCharCode(((c >> 6) & 63) | 128);
        output += String.fromCharCode((c & 63) | 128);
      }
    }
    return output;
  };
  
  $.extend({
    md5: function(string) {
      var x = Array();
      var k, AA, BB, CC, DD, a, b, c, d;
      var S11=7, S12=12, S13=17, S14=22;
      var S21=5, S22=9 , S23=14, S24=20;
      var S31=4, S32=11, S33=16, S34=23;
      var S41=6, S42=10, S43=15, S44=21;
      string = uTF8Encode(string);
      x = convertToWordArray(string);
      a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
      for (k = 0; k < x.length; k += 16) {
        AA = a; BB = b; CC = c; DD = d;
        a = FF(a, b, c, d, x[k+0],  S11, 0xD76AA478);
        d = FF(d, a, b, c, x[k+1],  S12, 0xE8C7B756);
        c = FF(c, d, a, b, x[k+2],  S13, 0x242070DB);
        b = FF(b, c, d, a, x[k+3],  S14, 0xC1BDCEEE);
        a = FF(a, b, c, d, x[k+4],  S11, 0xF57C0FAF);
        d = FF(d, a, b, c, x[k+5],  S12, 0x4787C62A);
        c = FF(c, d, a, b, x[k+6],  S13, 0xA8304613);
        b = FF(b, c, d, a, x[k+7],  S14, 0xFD469501);
        a = FF(a, b, c, d, x[k+8],  S11, 0x698098D8);
        d = FF(d, a, b, c, x[k+9],  S12, 0x8B44F7AF);
        c = FF(c, d, a, b, x[k+10], S13, 0xFFFF5BB1);
        b = FF(b, c, d, a, x[k+11], S14, 0x895CD7BE);
        a = FF(a, b, c, d, x[k+12], S11, 0x6B901122);
        d = FF(d, a, b, c, x[k+13], S12, 0xFD987193);
        c = FF(c, d, a, b, x[k+14], S13, 0xA679438E);
        b = FF(b, c, d, a, x[k+15], S14, 0x49B40821);
        a = GG(a, b, c, d, x[k+1],  S21, 0xF61E2562);
        d = GG(d, a, b, c, x[k+6],  S22, 0xC040B340);
        c = GG(c, d, a, b, x[k+11], S23, 0x265E5A51);
        b = GG(b, c, d, a, x[k+0],  S24, 0xE9B6C7AA);
        a = GG(a, b, c, d, x[k+5],  S21, 0xD62F105D);
        d = GG(d, a, b, c, x[k+10], S22, 0x2441453);
        c = GG(c, d, a, b, x[k+15], S23, 0xD8A1E681);
        b = GG(b, c, d, a, x[k+4],  S24, 0xE7D3FBC8);
        a = GG(a, b, c, d, x[k+9],  S21, 0x21E1CDE6);
        d = GG(d, a, b, c, x[k+14], S22, 0xC33707D6);
        c = GG(c, d, a, b, x[k+3],  S23, 0xF4D50D87);
        b = GG(b, c, d, a, x[k+8],  S24, 0x455A14ED);
        a = GG(a, b, c, d, x[k+13], S21, 0xA9E3E905);
        d = GG(d, a, b, c, x[k+2],  S22, 0xFCEFA3F8);
        c = GG(c, d, a, b, x[k+7],  S23, 0x676F02D9);
        b = GG(b, c, d, a, x[k+12], S24, 0x8D2A4C8A);
        a = HH(a, b, c, d, x[k+5],  S31, 0xFFFA3942);
        d = HH(d, a, b, c, x[k+8],  S32, 0x8771F681);
        c = HH(c, d, a, b, x[k+11], S33, 0x6D9D6122);
        b = HH(b, c, d, a, x[k+14], S34, 0xFDE5380C);
        a = HH(a, b, c, d, x[k+1],  S31, 0xA4BEEA44);
        d = HH(d, a, b, c, x[k+4],  S32, 0x4BDECFA9);
        c = HH(c, d, a, b, x[k+7],  S33, 0xF6BB4B60);
        b = HH(b, c, d, a, x[k+10], S34, 0xBEBFBC70);
        a = HH(a, b, c, d, x[k+13], S31, 0x289B7EC6);
        d = HH(d, a, b, c, x[k+0],  S32, 0xEAA127FA);
        c = HH(c, d, a, b, x[k+3],  S33, 0xD4EF3085);
        b = HH(b, c, d, a, x[k+6],  S34, 0x4881D05);
        a = HH(a, b, c, d, x[k+9],  S31, 0xD9D4D039);
        d = HH(d, a, b, c, x[k+12], S32, 0xE6DB99E5);
        c = HH(c, d, a, b, x[k+15], S33, 0x1FA27CF8);
        b = HH(b, c, d, a, x[k+2],  S34, 0xC4AC5665);
        a = II(a, b, c, d, x[k+0],  S41, 0xF4292244);
        d = II(d, a, b, c, x[k+7],  S42, 0x432AFF97);
        c = II(c, d, a, b, x[k+14], S43, 0xAB9423A7);
        b = II(b, c, d, a, x[k+5],  S44, 0xFC93A039);
        a = II(a, b, c, d, x[k+12], S41, 0x655B59C3);
        d = II(d, a, b, c, x[k+3],  S42, 0x8F0CCC92);
        c = II(c, d, a, b, x[k+10], S43, 0xFFEFF47D);
        b = II(b, c, d, a, x[k+1],  S44, 0x85845DD1);
        a = II(a, b, c, d, x[k+8],  S41, 0x6FA87E4F);
        d = II(d, a, b, c, x[k+15], S42, 0xFE2CE6E0);
        c = II(c, d, a, b, x[k+6],  S43, 0xA3014314);
        b = II(b, c, d, a, x[k+13], S44, 0x4E0811A1);
        a = II(a, b, c, d, x[k+4],  S41, 0xF7537E82);
        d = II(d, a, b, c, x[k+11], S42, 0xBD3AF235);
        c = II(c, d, a, b, x[k+2],  S43, 0x2AD7D2BB);
        b = II(b, c, d, a, x[k+9],  S44, 0xEB86D391);
        a = addUnsigned(a, AA);
        b = addUnsigned(b, BB);
        c = addUnsigned(c, CC);
        d = addUnsigned(d, DD);
      }
      var tempValue = wordToHex(a) + wordToHex(b) + wordToHex(c) + wordToHex(d);
      return tempValue.toLowerCase();
    }
  });
})(jQuery);
;
// $Id: gmaps.js,v 1.2.2.8 2010/03/18 10:52:16 xmarket Exp $

GMAPS_TABS_NAV_TOP = 'top';
GMAPS_TABS_NAV_BOTTOM = 'bottom';
GMAPS_TABS_NAV_LEFT = 'left';
GMAPS_TABS_NAV_RIGHT = 'right';

GMAPS_GRID_ALIGN_HOR = 'hor';
GMAPS_GRID_ALIGN_VER = 'ver';

Drupal.behaviors.gmapsBehaviors = function(context) {
  //Element help
  $('a.gmaps-element-help:not(.gmaps-element-help-processed)', context).each(function (index, a) {
    setTimeout(function() {
      $(a).click(function () {
        var w=window.open(a.href, 'advanced_help_window', 'width='+Drupal.settings.gmaps.elementHelp.width+'px,height='+Drupal.settings.gmaps.elementHelp.height+'px,scrollbars,resizable');
        w.focus();
        return false;
      }).removeAttr('target').addClass('gmaps-element-help-processed');
    }, 5);
  });

  //Accordion element
  $('.form-gmaps-accordion:not(.gmaps-accordion-embedded):not(.gmaps-accordion-processed)', context).each(function (index, element) {
    var handler, init = function() {Drupal.gmaps.accordion.getAccordion(element.id, context, true);};
    if (handler = Drupal.gmaps.getLazyInitHandler('#'+ element.id, context)) {
      handler.attach('#'+ element.id, init, context);
    }
    else {
      setTimeout(init, 5);
    }
  });

  //Tabs element
  $('.form-gmaps-tabs:not(.gmaps-tabs-embedded):not(.gmaps-tabs-processed)', context).each(function (index, element) {
    var handler, init = function() {Drupal.gmaps.tabs.getTabs(element.id, context, true);};
    if (handler = Drupal.gmaps.getLazyInitHandler('#'+ element.id, context)) {
      handler.attach('#'+ element.id, init, context);
    }
    else {
      setTimeout(init, 5);
    }
  });
};

Drupal.attributes = function(attributes) {
  var t = '';
  if (attributes) {
    $.each(attributes, function(key, value) {
      t += ' '+ key +'="'+ Drupal.checkPlain(value) +'"';
    });
  }
  return t;
};

Drupal._formSetClass = function(element, cls) {
  cls = cls || [];
  if (element['#required']) {
    cls.push('required');
  }
  if (element['#attributes'] && element['#attributes']['class']) {
    cls.push(element['#attributes']['class']);
  }
  if (!element['#attributes']) {
    element['#attributes'] = {};
  }
  element['#attributes']['class'] = cls.join(' ');
};

Drupal._themeTableCell = function(cell, header) {
  var data, output = '', attributes = '';

  if (typeof(cell) == 'object') {
    data = typeof(cell['data']) != 'undefined' ? cell['data'] : '';
    header |= typeof(cell['header']) != 'undefined';
    var attr = $.extend(true, {}, cell);
    delete attr['data'];
    delete attr['header'];
    attributes = Drupal.attributes(attr);
  }
  else {
    data = cell;
  }

  if (header) {
    output = '<th'+ attributes +'>'+ data +'</th>';
  }
  else {
    output = '<td'+ attributes +'>'+ data +'</td>';
  }

  return output;
};

Drupal.hooks = Drupal.hooks || {};

Drupal.hooks.elements = Drupal.hooks.elements || {};

Drupal.hooks.elements.fieldset = {'#collapsible': false, '#collapsed': false, '#value': null};
//'#process' => array('form_expand_ahah')
Drupal.hooks.elements.checkbox = {'#return_value': 1};

Drupal._elementInfo = function($type, $refresh) {
  //static $cache;

  var $basic_defaults = {
    '#description': '',
    '#attributes': {},
    '#required': false,
    '#tree': false,
    '#parents': []
  };
  var $cache = $(document).data('_elementInfo.drupal');
  if (!$cache || $refresh) {
    $cache = {};
    $.each(Drupal.hooks.elements, function($element_type, $info) {
      $cache[$element_type] = $.extend(true, {}, $basic_defaults, $info);
    });
    $(document).data('_elementInfo.drupal', $cache);
  }

  return $.extend(true, {}, $cache[$type]);
};

Drupal.elementChild = function($key) {
  return typeof($key) == 'undefined' || $key === null || !$key.length || $key.charAt(0) != '#';
};

Drupal.elementChildren = function($element) {
  var $children = [];
  $.each($element, function($key, $value) {
    if (Drupal.elementChild($key)) {
      $children.push($key);
    }
  });
  return $children;
};

Drupal.render = function($elements) {
  var self = this;
  if ($elements === null || (typeof($elements['#access']) != 'undefined' && !$elements['#access'])) {
    return null;
  }
  
  $elements = $.extend(true, {}, $elements);

  // If the default values for this element haven't been loaded yet, populate
  // them.
  if (typeof($elements['#defaults_loaded']) == 'undefined' || !$elements['#defaults_loaded']) {
    var $info;
    if ((typeof($elements['#type']) != 'undefined' && $elements['#type'] !== null && $elements['#type'].length) && ($info = Drupal._elementInfo($elements['#type']))) {
      $elements = $.extend(true, $info, $elements);
    }
    $elements['#defaults_loaded'] = true;
  }

  // Make any final changes to the element before it is rendered. This means
  // that the $element or the children can be altered or corrected before the
  // element is rendered into the final text.
  if (typeof($elements['#pre_render']) != 'undefined') {
    $.each($elements['#pre_render'], function() {
      $elements = this($elements);
    });
  }
  
  var $content = '';
  $elements = $.extend({'#title': '', '#description': ''}, $elements);
  if (typeof($elements['#children']) == 'undefined') {
    var $children = Drupal.elementChildren($elements);
    // Render all the children that use a theme function.
    if (typeof($elements['#theme']) != 'undefined' && !$elements['#theme_used']) {
      $elements['#theme_used'] = true;

      var $previous = {};
      $.each(['#value', '#type', '#prefix', '#suffix'], function(i, $key) {
        $previous[$key] = typeof($elements[$key]) != 'undefined' ? $elements[$key] : null;
      });
      // If we rendered a single element, then we will skip the renderer.
      if (!$children.length) {
        $elements['#printed'] = true;
      }
      else {
        $elements['#value'] = '';
      }
      $elements['#type'] = 'markup';

      delete $elements['#prefix'];
      delete $elements['#suffix'];
      $content = Drupal.theme($elements['#theme'], $elements);

      $.each(['#value', '#type', '#prefix', '#suffix'], function(i, $key) {
        $elements[$key] = typeof($previous[$key]) != 'undefined' ? $previous[$key] : null;
      });
    }
    // Render each of the children using drupal_render and concatenate them.
    if ($content === null || !$content.length) {
      $.each($children, function(i, $key) {
        $content += Drupal.render($elements[$key]);
      });
    }
  }
  if ($content !== null && $content.length) {
    $elements['#children'] = $content;
  }

  // Until now, we rendered the children, here we render the element itself
  if (typeof($elements['#printed']) == 'undefined') {
    $content = Drupal.theme((typeof($elements['#type']) != 'undefined' && $elements['#type'] !== null && $elements['#type'].length) ? $elements['#type'] : 'markup', $elements);
    $elements['#printed'] = true;
  }

  if ($content !== null && $content.length) {
    // Filter the outputted content and make any last changes before the
    // content is sent to the browser. The changes are made on $content
    // which allows the output'ed text to be filtered.
    if (typeof($elements['#post_render']) != 'undefined') {
      $.each($elements['#post_render'], function(i, fn) {
        $content = fn($content, $elements);
      });
    }
    var $prefix = typeof($elements['#prefix']) != 'undefined' ? $elements['#prefix'] : '';
    var $suffix = typeof($elements['#suffix']) != 'undefined' ? $elements['#suffix'] : '';
    return $prefix + $content + $suffix;
  }
};

Drupal.theme.prototype.box = function(title, content, region) {
  var output = '<h2 class="title">'+ title +'</h2><div>'+ content +'</div>';
  return output;
};

Drupal.theme.prototype.itemList = function(items, title, type, attributes) {
  var output = '<div class="item-list">';
  if (title && title.length) {
    output += '<h3>'+ title +'</h3>';
  }
  
  type = type || 'ul';

  if (items && items.length) {
    output += '<'+ type + Drupal.attributes(attributes) +'>';
    $.each(items, function(i, item) {
      attributes = {};
      var children = [];
      var data = '';
      if (typeof(item) == 'object') {
        $.each(item, function(key, value) {
          if (key == 'data') {
            data = value;
          }
          else if (key == 'children') {
            children = value;
          }
          else {
            attributes[key] = value;
          }
        });
      }
      else {
        data = item;
      }
      if (children.length) {
        data += Drupal.theme.prototype.itemList(children, null, type, attributes); // Render nested list
      }
      if (i == 0) {
        attributes['class'] = (!attributes['class'] || !attributes['class'].length) ? 'first' : (attributes['class'] +' first');
      }
      if (i == (items.length - 1)) {
        attributes['class'] = (!attributes['class'] || !attributes['class'].length) ? 'last' : (attributes['class'] +' last');
      }
      output += '<li'+ Drupal.attributes(attributes) +'>'+ data +"</li>\n";
    });
    output += '</'+ type + '>';
  }
  output += '</div>';
  return output;
};

Drupal.theme.prototype.gmapsGrid = function(items, options, title) {
  if (!items || !items.length) {
    return '';
  }
  
  var cols = options['columns'];
  var attributes = (typeof(options['attributes']) != 'undefined' && options['attributes'] !== null) ? options['attributes'] : {};
  var header = (typeof(options['header']) != 'undefined' && options['header'] !== null) ? options['header'] : false;
  
  attributes['class'] = (typeof(options['class']) == 'undefined' || options['class'] === null) ? 'gmaps-grid' : ('gmaps-grid '+ attributes['class']);
  
  var output = '<table'+ Drupal.attributes(attributes) +">\n";
  
  if (title && title.length) {
    output += '<caption>'+ title +"</caption>\n";
  }
  output += "<tbody>\n";
  
  var rows = new Array();
  
  //set up grid
  if (options['alignment'] == GMAPS_GRID_ALIGN_HOR) {
    var row = new Array();
    var row_count = 0;
    $.each(items, function(count, cell) {
      row.push(cell);
      row_count++;
      if ((count + 1) % cols == 0) {
        rows.push(row);
        row = new Array();
        row_count = 0;
      }
    });
    if (row.length) {
      // Fill up the last line.
      for (var i = 0; i < (cols - row_count); i++) {
        row.push('');
      }
      rows.push(row);
    }
  }
  else {
    var num_rows = Math.floor(items.length) / cols;
    // The remainders are the 'odd' columns that are slightly longer.
    var remainders = items.length % cols;
    var row = 0;
    var col = 0;
    $.each(items, function(count, cell) {
      if (typeof(rows[row]) == 'undefined') {
        rows[row] = new Array();
      }
      rows[row][col] = cell;
      row++;

      if (!remainders && row == num_rows) {
        row = 0;
        col++;
      }
      else if (remainders && row == num_rows + 1) {
        row = 0;
        col++;
        remainders--;
      }
    });
    for (var i = 0; i <= rows[0].length; i++) {
      // This should be string so that's okay :)
      if (typeof(rows[rows.length - 1][i]) == 'undefined') {
        rows[rows.length - 1][i] = '';
      }
    }
  }
  
  var flip = {'even': 'odd', 'odd': 'even'};
  var cls = 'even';
  $.each(rows, function(row_number, row) {
    var row_class = 'row-'+ (row_number + 1) +' row-'+ cls;
    cls = flip[cls];
    if (row_number == 0) {
      row_class += ' row-first';
    }
    if (rows.length == (row_number + 1)) {
      row_class += ' row-last';
    }
    output += '<tr class="'+ row_class +'">';
    
    var flip_col = {'even': 'odd', 'odd': 'even'};
    var class_col = 'even';
    $.each(row, function(col_number, cell) {
      var cell_class = 'col-'+ (col_number + 1) +' col-'+ class_col;
      class_col = flip_col[class_col];
      if (col_number == 0) {
        cell_class += ' col-first';
      }
      if (row.length == (col_number + 1)) {
        cell_class += ' col-last';
      }
      
      if (typeof(cell) == 'object') {
        if (typeof(cell['class']) != 'undefined') {
          cell['class'] += ' '+ cell_class;
        }
        else {
          cell['class'] = cell_class;
        }
      }
      else {
        cell = {'data': cell, 'class': cell_class};
      }
      
      output += Drupal._themeTableCell(cell, header);
    });
    
    output += "</tr>\n";
  });
  
  output += "</tbody></table>\n";
  return output;
}

Drupal.theme.prototype.fieldset = function(element) {
  if (element['#collapsible']) {
    if (typeof(element['#attributes']) == 'undefined') {
      element['#attributes'] = {};
    }
    if (typeof(element['#attributes']['class']) == 'undefined') {
      element['#attributes']['class'] = '';
    }

    element['#attributes']['class'] += ' collapsible';
    if (element['#collapsed']) {
      element['#attributes']['class'] += ' collapsed';
    }
  }

  return '<fieldset'+ Drupal.attributes(element['#attributes']) +'>'+ (element['#title'] ? '<legend>'+ element['#title'] +'</legend>' : '') +
    (typeof(element['#description']) != 'undefined' && element['#description'].length ? '<div class="description">'+ element['#description'] +'</div>' : '') +
    (element['#children'] ? element['#children'] : '') + (typeof(element['#value']) != 'undefined' ? element['#value'] : '') +"</fieldset>\n";
};

Drupal.theme.prototype.form_element = function(element, value) {
  var output = '<div class="form-item"';
  var hasId = typeof(element['#id']) != 'undefined' && element['#id'] !== null && element['#id'].length;
  if (hasId) {
    output += ' id="'+ element['#id'] +'-wrapper"';
  }
  output += ">\n";
  var required = (typeof(element['#required']) != 'undefined' && element['#required'] !== null) ? '<span class="form-required" title="'+ Drupal.t('This field is required.') +'">*</span>' : '';

  if (typeof(element['#title']) != 'undefined' && element['#title'] !== null && element['#title'].length) {
    var title = element['#title'];
    if (hasId) {
      output += ' <label for="'+ element['#id'] +'">'+ Drupal.t('!title: !required', {'!title': title, '!required': required}) +"</label>\n";
    }
    else {
      output += ' <label>'+ Drupal.t('!title: !required', {'!title': title, '!required': required}) +"</label>\n";
    }
  }

  output += ' '+ value +"\n";

  if (typeof(element['#description']) != 'undefined' && element['#description'] !== null && element['#description'].length) {
    output += ' <div class="description">'+ element['#description'] +"</div>\n";
  }

  output += "</div>\n";

  return output;
};

Drupal.theme.prototype.checkbox = function(element) {
  Drupal._formSetClass(element, ['form-checkbox']);
  var checkbox = '<input ';
  checkbox += 'type="checkbox" ';
  checkbox += element['#name'] ? 'name="'+ element['#name'] +'" ' : '';
  checkbox += element['#id'] ? 'id="'+ element['#id'] +'" ' : '';
  checkbox += 'value="'+ element['#return_value'] +'" ';
  checkbox += element['#value'] ? ' checked="checked" ' : ' ';
  checkbox += Drupal.attributes(element['#attributes']) +' />';

  if (element['#title'] != null) {
    checkbox = '<label class="option"'+ (element['#id'] ? ' for="'+ element['#id'] +'"' : '') +'>'+ checkbox +' '+ element['#title'] +'</label>';
  }

  delete element['#title'];
  return Drupal.theme('form_element', element, checkbox);
};

Drupal.theme.prototype.gmaps_accordion = function(element) {
  var hasChildren = typeof(element['#children']) != 'undefined' && element['#children'] !== null && element['#children'].length;
  var output = '<div id="'+ element['#id'] +'" '+ Drupal.attributes(element['#attributes']) +'>' +
    (hasChildren ? ('<div class="gmaps-accordion">'+ element['#children'] +'</div>') : '') +'</div>'+
    (typeof(element['#value']) != 'undefined' && element['#value'] !== null ? element['#value'] : '');

  return Drupal.theme('form_element', element, output);
};

Drupal.theme.prototype.gmaps_accordion_panel = function(element) {
  if (typeof(element['#attributes']) == 'undefined' || element['#attributes'] === null) {
    element['#attributes'] = {};
  }
  if (typeof(element['#attributes']['class']) == 'undefined' || element['#attributes']['class'] === null) {
    element['#attributes']['class'] = '';
  }
  element['#attributes']['class'] = 'gmaps-accordion-header'+ (element['#accordion_id'] ? ' '+ element['#accordion_id'] : '') +
    ((typeof(element['#active_panel']) != 'undefined' && element['#active_panel']) ? ' ui-state-active' : '') +' '+ element['#attributes']['class'];
  var output = '<h3 '+ Drupal.attributes(element['#attributes']) +'><a href="#'+ element['#id'] +'">'+ element['#title'] +"</a></h3>\n";
  output += '<div id="'+ element['#id'] +'" class="gmaps-accordion-panel'+ ((typeof(element['#active_panel']) != 'undefined' && element['#active_panel']) ? ' ui-accordion-content-active' : '') +"\">\n";
  
  if (typeof(element['#description']) != 'undefined' && element['#description'] !== null && element['#description'].length) {
    output += '<div class="description">'+ element['#description'] +"</div>\n";
  }
  output += '<div id="'+ element['#id'] +'-content">';
  output += ((typeof(element['#children']) != 'undefined' && element['#children'] !== null && element['#children'].length) ? element['#children'] : '');
  output += ((typeof(element['#value']) != 'undefined' && element['#value'] !== null) ? element['#value'] : '');
  output += "</div></div>\n";
  
  return output;
};

Drupal.theme.prototype.gmaps_tabs = function(element) {
  var output = '<div id="'+ element['#id'] +'" '+ Drupal.attributes(element['#attributes']) +'><div class="gmaps-tabs">';
  
  //tabs
  var nav = "<ul class=\"gmaps-tabs-nav\">\n";
  var lineend = (element['#nav_position'] == GMAPS_TABS_NAV_TOP || element['#nav_position'] == GMAPS_TABS_NAV_BOTTOM) ? "\n" : '';
  $.each(Drupal.elementChildren(element), function() {
    if (typeof(element[this]['#type']) != 'undefined' && element[this]['#type'] !== null && element[this]['#type'] == 'gmaps_tabs_panel') {
      var panel = element[this];
      nav += '<li class="gmaps-tabs-tab '+ element['#id'] +'-tab'+ (panel['#selected_panel'] ? ' ui-tabs-selected' : '') +'"><a href="#'+ panel['#id'] +'"><span>'+ panel['#title'] +'</span></a></li>'+ lineend;
    }
    
  });
  nav += "</ul>\n";
  
  if (element['#nav_position'] != GMAPS_TABS_NAV_BOTTOM) {
    output += nav;
  }
  output += element['#children'];
  if (element['#nav_position'] == GMAPS_TABS_NAV_BOTTOM) {
    output += nav;
  }
  output += '</div><div class="gmaps-tabs-clear-nav"></div>'+ ((typeof(element['#value']) != 'undefined' && element['#value'] !== null) ? element['#value'] : '') +"</div>\n";
  
  return Drupal.theme('form_element', element, output);
};

Drupal.theme.prototype.gmaps_tabs_panel = function(element) {
  if (typeof(element['#attributes']) == 'undefined' || element['#attributes'] === null) {
    element['#attributes'] = {};
  }
  if (typeof(element['#attributes']['class']) == 'undefined' || element['#attributes']['class'] === null) {
    element['#attributes']['class'] = '';
  }
  element['#attributes']['class'] = 'gmaps-tabs-panel '+ element['#tabs_id'] +'-panel' +
    ((typeof(element['#selected_panel']) == 'undefined' || !element['#selected_panel']) ? ' ui-tabs-hide' : '') +' '+ element['#attributes']['class'];
  var output = '<div id="'+ element['#id'] +'" '+ Drupal.attributes(element['#attributes']) +">\n";

  if (typeof(element['#description']) != 'undefined' && element['#description'] !== null && element['#description'].length) {
    output += ' <div class="description">'+ element['#description'] +"</div>\n";
  }
  output += '<div id="'+ element['#id'] +'-content">';
  output += ((typeof(element['#children']) != 'undefined' && element['#children'] !== null && element['#children'].length) ? element['#children'] : '');
  output += ((typeof(element['#value']) != 'undefined' && element['#value'] !== null) ? element['#value'] : '');
  output += "</div></div>\n";
  
  return output;
};

Drupal.theme.prototype.markup = function(element) {
  return ((typeof(element['#value']) != 'undefined' && element['#value'] !== null) ? element['#value'] : '') +
    ((typeof(element['#children']) != 'undefined' && element['#children'] !== null) ? element['#children'] : '');
}

GMapsLazyInitHandlerFieldset = function() {
  this.check = function(selector, context) {
    var parent = $(selector, context).parents('fieldset.collapsed:first');
    return (parent.length && !$('input.error, textarea.error, select.error', parent).length) ? parent : false;
  };
  
  this.checkContext = function(context, selector) {
    var mostInner = $('fieldset.collapsed:has('+ selector +'):last', context);
    return (mostInner.length && !$('input.error, textarea.error, select.error', mostInner).length) ? mostInner : false;
  };
  
  this.attach = function(selector, callback, context) {
    context = context || document;
    $(selector, context).parents('fieldset.collapsed:first').one('mouseover', function(){
      $('legend a', this).one('click', function() {setTimeout(callback, 300);});
    });
    
  };
};

GMapsLazyInitHandlerAccordion = function() {
  this.check = function(selector, context) {
    var parent = $(selector, context).parents('.gmaps-accordion-panel:not(.ui-accordion-content-active):first');
    return parent.length ? parent : false;
  };
  
  this.checkContext = function(context, selector) {
    var mostInner = $('.gmaps-accordion-panel:not(.ui-accordion-content-active):has('+ selector +'):last', context);
    return mostInner.length ? mostInner : false;
  };
  
  this.attach = function(selector, callback, context) {
    context = context || document;
    var accordion = $('.gmaps-accordion:first', $(selector, context).parents('.gmaps-accordion-panel:not(.ui-accordion-content-active)').parents('.form-gmaps-accordion:first'));
    var fn = function(e, ui) {
      if ($(selector, ui.newContent).length) {
        callback();
        accordion.unbind('accordionchange', fn);
      }
    };
    accordion.bind('accordionchange', fn);
  };
};

GMapsLazyInitHandlerTabs = function() {
  this.check = function(selector, context) {
    var parent = $(selector, context).parents('.gmaps-tabs-panel.ui-tabs-hide:first');
    return parent.length ? parent : false;
  };
  
  this.checkContext = function(context, selector) {
    var mostInner = $('.gmaps-tabs-panel.ui-tabs-hide:has('+ selector +'):last', context);
    return mostInner.length ? mostInner : false;
  };
  
  this.attach = function(selector, callback, context) {
    context = context || document;
    var tabs = $('.gmaps-tabs:first', $(selector, context).parents('.form-gmaps-tabs:first'));
    var fn = function(e, ui) {
      if ($(selector, ui.panel).length) {
        callback();
        tabs.unbind('tabsshow', fn);
      }
    };
    tabs.bind('tabsshow', fn);
  };
};

Drupal.gmaps = Drupal.gmaps || new (function() {
  var self = this, jsre = /=\?(&|$)/g;

  this.globalAjaxParams = {
    'gmaps-async-api': '1'
  };
  var ajaxQueueIndex = 0;
  this.ajaxQueue = {};
  
  this.ajaxTests = {
    'css': {
      'drupal': {
        're': new RegExp('^'+ location.host + Drupal.settings.basePath +'modules'),
        'test': function() {return true;}
      },
      'gmaps': {
        're': /gmaps.*?\/misc\/.+/,
        'test': function() {return true;}
      },
      'gmaps_admin': {
        're': /gmaps\/misc\/gmaps-admin\.css.*$/,
        'test': function() {
          if ($('#gmaps-icon-color-form').length) {
            return true;
          }
        }
      }
    },
    'js': {
      'drupal': {
        're': /\/drupal\.js/,
        'test': function() {return true;}
      },
      'jquery': {
        're': /\/jquery\.js/,
        'test': function(file) {return true;}
      },
      'jqueryForm': {
        're': /\/jquery\.form\.js/,
        'test': function() {return typeof(jQuery.ajaxSubmit) != 'undefined';}
      },
      'jqueryUITabs': {
        're': /\/jquery\.ui\/ui\/ui\.tabs\.js/,
        'test': function() {return $.ui && $.ui.tabs;}
      },
      'jqueryUIAccordion': {
        're': /\/jquery\.ui\/ui\/ui\.accordion\.js/,
        'test': function() {return $.ui && $.ui.accordion;}
      },
      'ahah': {
        're': /\/ahah\.js/,
        'test': function() {return typeof(Drupal.behaviors.ahah) != 'undefined';}
      },
      'fieldset': {
        're': /\/collapse\.js/,
        'test': function() {return typeof(Drupal.behaviors.collapse) != 'undefined';}
      },
      'form': {
        're': /\/form\.js/,
        'test': function() {return typeof(Drupal.behaviors.multiselectSelector) != 'undefined';}
      },
      'autocomplete': {
        're': /\/autocomplete\.js/,
        'test': function() {return typeof(Drupal.behaviors.autocomplete) != 'undefined';}
      },
      'progress': {
        're': /\/progress\.js/,
        'test': function() {return typeof(Drupal.progressBar) != 'undefined';}
      },
      'tabledrag': {
        're': /\/tabledrag\.js/,
        'test': function() {return typeof(Drupal.behaviors.tableDrag) != 'undefined';}
      },
      'tableheader': {
        're': /\/tableheader\.js/,
        'test': function() {return typeof(Drupal.behaviors.tableHeader) != 'undefined';}
      },
      'tableselect': {
        're': /\/tableselect\.js/,
        'test': function() {return typeof(Drupal.behaviors.tableSelect) != 'undefined';}
      },
      'teaser': {
        're': /\/teaser\.js/,
        'test': function() {return typeof(Drupal.behaviors.teaser) != 'undefined';}
      },
      'textarea': {
        're': /\/textarea\.js/,
        'test': function() {return typeof(Drupal.behaviors.textarea) != 'undefined';}
      },
      'farbtastic': {
        're': /\/farbtastic\.js/,
        'test': function() {return typeof(jQuery.farbtastic) != 'undefined';}
      },
      'gmaps': {
        're': /gmaps\/misc\/gmaps\.js/,
        'test': function() {return typeof(Drupal.gmaps) != 'undefined';}
      },
      'gmaps_icon_select': {
        're': /gmaps\/misc\/gmaps-icon-select\.js/,
        'test': function() {return typeof(GMapsIconSelectElement) != 'undefined';}
      },
      'gmaps_geocoder': {
        're': /gmaps\/misc\/gmaps-geocoder-element\.js/,
        'test': function() {return typeof(GMapsGeocoderElement) != 'undefined';}
      },
      'gmaps_address': {
        're': /gmaps\/misc\/gmaps-address-element\.js/,
        'test': function() {return typeof(GMapsAddressElement) != 'undefined';}
      },
      'gmaps_point': {
        're': /gmaps\/misc\/gmaps-point-element\.js/,
        'test': function() {return typeof(GMapsPointElement) != 'undefined';}
      },
      'gmaps_anp': {
        're': /'gmaps\/misc\/gmaps-anp-element\.js'/,
        'test': function() {return typeof(GMapsAnpElement) != 'undefined';}
      },
      'gmaps_map': {
        're': /gmaps\/misc\/gmaps-map\.js/,
        'test': function() {return typeof(GMapsMapItem) != 'undefined';}
      },
      'gmaps_icon': {
        're': /gmaps\/misc\/gmaps-icon\.js/,
        'test': function() {return typeof(Drupal.gmaps.icon) != 'undefined';}
      },
      'gmaps_marker': {
        're': /gmaps\/misc\/gmaps-marker\.js/,
        'test': function() {return typeof(Drupal.gmaps.marker) != 'undefined';}
      },
      'dhtml_menu': {
        're': /\/dhtml_menu\/dhtml_menu\.js/,
        'test': function() {return typeof(Drupal.dhtmlMenu) != 'undefined';}
      },
      'lightbox': {
        're': /\/js\/lightbox\.js/,
        'test': function() {return typeof(Lightbox) != 'undefined';}
      }
    }
  };

  this.lazyInitHandlers = {
    'fieldset': new GMapsLazyInitHandlerFieldset(),
    'tabs': new GMapsLazyInitHandlerTabs(),
    'accordion': new GMapsLazyInitHandlerAccordion()
  };
  
  var getSubLazyInitHandler = function(context, selector, skip) {
    var handler, subcontext;
    $.each(self.lazyInitHandlers, function() {
      if ($.inArray(this, skip) == -1) {
        skip.push(this);
        if (subcontext = this.checkContext(context, selector)) {
          handler = getSubLazyInitHandler(subcontext, selector, skip) || this;
          return false;
        }
      }
    });
    return handler;
  };
  
  this.getLazyInitHandler = function(selector, context) {
    context = context || document;
    var handler, handlerContext, skip = [];
    $.each(self.lazyInitHandlers, function() {
      if ($.inArray(this, skip) == -1) {
        skip.push(this);
        if (handlerContext = this.check(selector, context)) {
          handler = getSubLazyInitHandler(handlerContext, selector, skip) || this;
          return false;
        }
      }
    });
    return handler;
  };
  
  var checkAjaxCSSFiles = function(files, css) {
    var newFiles = {};
    $.each(files, function(file, media) {
      if (typeof(css[file]) == 'undefined') {
        var checked = false;
        $.each(self.ajaxTests.css, function(i, test) {
          if (test.re.test(file)) {
            checked = true;
            //tests should return true, when the 'content' already exists
            if (!test.test()) {
              newFiles[file] = media;
            }
            return false;
          }
        });
        if (!checked) {
          newFiles[file] = media;
        }
      }
    });
    return newFiles;
  };
  
  var processAjaxCSS = function(files, css) {
    var head = document.getElementsByTagName("head")[0] || document.documentElement;
    var link, newFiles = checkAjaxCSSFiles(files, css);
    $.each(newFiles, function(file, media) {
      link = document.createElement('link');
      link.href = file;
      link.type = 'text/css';
      link.rel = 'stylesheet';
      link.media = media;
      head.appendChild(link);
      css[file] = media;
    });
  };
  
  var checkAjaxScriptFiles = function(files, scripts, scriptIds) {
    var newFiles = [];
    var tests = $.extend({}, self.ajaxTests.js);
    $.each(files, function(i, data) {
      if ($.inArray(data.url, scripts) == -1 && (!data.id.length || $.inArray(data.id, scriptIds) == -1)) {
        var checked = false;
        $.each(tests, function(i, test) {
          if (test.re.test(data.url)) {
            checked = true;
            delete tests[i];
            //tests should return true, when the 'content' already exists
            if (!test.test()) {
              newFiles.push(data);
            }
            return false;
          }
        });
        if (!checked) {
          newFiles.push(data);
        }
      }
    });
    return newFiles;
  };
  
  var processAjaxScript = function(files, scripts, scriptIds, cache, callback) {
    if (!files.length) {
      callback();
      return;
    }
    var data = files.shift(), ajaxSuccess;
    if ($.inArray(data.url, scripts) == -1 && (!data.id.length || $.inArray(data.id, scriptIds) == -1)) {
      scripts.push(data.url);
      scriptIds.push(data.id);
      if (data.url.match(jsre)) {
        var id = 'ajax'+ ajaxQueueIndex++;
        data.url = data.url.replace(jsre, "=Drupal.gmaps.ajaxQueue." + id + "$1");
        Drupal.gmaps.ajaxQueue[id] = function(){
          processAjaxScript(files, scripts, scriptIds, cache, callback);
        };
        ajaxSuccess = function(){};
      }
      else {
        ajaxSuccess = function() {processAjaxScript(files, scripts, scriptIds, cache, callback)};
      }
      $.ajax({
        type: "GET",
        'url': data.url,
        data: null,
        'cache': cache,
        success: ajaxSuccess,
        dataType: 'script'
      });
    }
    else {
      processAjaxScript(files, scripts, scriptIds, cache, callback);
    }
  };
  
  var processAjaxInlineCode = function(codes, callback) {
    if (!code.length) {
      callback();
      return;
    }
    var code = codes.shift();
    $.globalEval(code);
    //give some time for script to execute
    setTimeout(function() {processAjaxInlineCode(codes, callback);}, 75);
  };
  
  var processAjax = function(r, cache, callback) {
    var head = document.getElementsByTagName("head")[0] || document.documentElement;
    var css = {}, scripts = [], scriptIds = [], headScripts = [], headInline = [], file, i, data;
    callback = (typeof(callback) == 'undefined' || callback === null || !$.isFunction(callback)) ? function(){} : callback;
    
    //head
    if (typeof(r.head) != 'undefined') {
      var dom = $(r.head);

      $(dom).filter('script').each(function() {
        if (this.src.length) {
          headScripts.push({url: this.src, id: this.id});
        }
        else {
          headInline.push($(this).text());
        }
      });
      if (headScripts.length) {
        if (typeof(r.js) == 'undefined') {
          r.js = {};
        }
        if (typeof(r.js.files) == 'undefined') {
          r.js.files = [];
        }
        $.each(headScripts.reverse(), function(i, data) {
          r.js.files.unshift(data);
        });
      }
      if (headInline.length) {
        if (typeof(r.js) == 'undefined') {
          r.js = {};
        }
        if (typeof(r.js.inline) == 'undefined') {
          r.js.inline = [];
        }
        $.each(headInline.reverse(), function(i, code) {
          r.js.inline.unshift(code);
        });
      }

      $(dom).filter('link[type=text/css]').each(function() {
        if (typeof(r.css) == 'undefined') {
          r.css = {};
        }
        if (typeof(r.css.head) == 'undefined') {
          r.css.head = {};
        }
        r.css.head[this.href] = (this.media != null && this.media.length) ? this.media : 'all';
      });
      $(dom).filter(':not(script):not(link[type=text/css])').each(function() {
        //unlike $.globalEval(), we can use appendChild, because we don't want to remove it.
        head.appendChild(this);
      });
    }

    //css
    if (typeof(r.css) != 'undefined') {
      $('link').each(function() {
        if (this.href.length) {
          css[this.href] = (this.media != null && this.media.length) ? this.media : "all";
        }
      });
      //head
      if (typeof(r.css.head) != 'undefined') {
        processAjaxCSS(r.css.head, css);
      }
      //module
      if (typeof(r.css.module) != 'undefined') {
        processAjaxCSS(r.css.module, css);
      }
      //misc
      if (typeof(r.css.misc) != 'undefined') {
        processAjaxCSS(r.css.misc, css);
      }
      //theme
      if (typeof(r.css.theme) != 'undefined') {
        processAjaxCSS(r.css.theme, css);
      }
    }
    
    //js
    if (typeof(r.js) != 'undefined') {
      //settings
      var extendSettings = function() {
        if (typeof(r.js.setting) != 'undefined') {
          //deep extended
          Drupal.settings = $.extend(true, Drupal.settings, r.js.setting);
        }
        callback();
      };
      
      //inline code
      var inlineCallback = function() {
        if (typeof(r.js.inline) != 'undefined') {
          processAjaxInlineCode(r.js.inline, extendSettings);
        }
        else {
          extendSettings();
        }
      };
  
      //scripts
      if (typeof(r.js.files) != 'undefined') {
        $('script').each(function() {
          if (this.src.length) {
            scripts.push(this.src);
            scriptIds.push(this.id);
          }
        });
        var newFiles = checkAjaxScriptFiles(r.js.files, scripts, scriptIds);
        processAjaxScript(newFiles, scripts, scriptIds, cache, inlineCallback);
      }
      else {
        inlineCallback();
      }
    }
    else {
      callback();
    }
  };
  
  this.prepareAjaxOptions = function(ajax) {
    var callback = ajax.success || function(){};
    
    if (typeof(ajax.type) == 'undefined' || ajax.type === null) {
      ajax.type = (typeof(ajax.data) == 'undefined' || ajax.data === null) ? 'GET' : 'POST';
    }
    ajax.dataType = 'json';
    ajax.cache = (typeof(ajax.cache) == 'undefined' || ajax.cache === null) ? true : ajax.cache;
    
    ajax.success = function(r, s) {
      if (typeof(r.ajax) != 'undefined') {
        processAjax(r.ajax, ajax.cache, function() {callback(r);});
      }
      else {
        callback(r);
      }
    };
    
    ajax.data = $.extend(true, ajax.data ? ajax.data : {}, self.globalAjaxParams);

    ajax.gmapsPrepared = true;
  };
  
  this.loadAjaxContent = function(ajax) {
    if (!ajax.gmapsPrepared) {
      self.prepareAjaxOptions(ajax);
    }

    $.ajax(ajax);
  };
  
  this.flatten = function(obj, parent, ret) {
    ret = ret || {};
    $.each(obj, function(i, val) {
      i = parent ? (parent +'['+ i +']') : i;
      if (val && typeof(val) == "object" && !val.nodeType) {
        self.flatten(val, i, ret);
      }
      else if (typeof(val) == 'undefined' || val === null) {
        ret[i] = '';
      }
      else if (val === true || val === false) {
        ret[i] = val ? 1 : 0;
      }
      else {
        ret[i] = $.isFunction(val) ? val() : val;
      }
    });
    
    return ret;
  };
  
  this.expandAhahOptions = function(o, item) {
    o.wrapper = '#'+ o.wrapper;
    o.effect = o.effect || 'none';
    o.method = o.method || 'replace';
    o.ajax = (typeof(o.ajax) != 'undefined' && o.ajax !== null) ? o.ajax : true;

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

    var form = $(item).parents('form:first');
    if (form.length) {
      o.form = {
        form: form,
        form_action: form.attr('action'),
        form_target: form.attr('target'),
        form_encattr: form.attr('encattr')
      };
    }
  };
})();

Drupal.gmaps.accordion = Drupal.gmaps.accordion || new (function() {
  var self = this;
  this.accordions = {};
  
  this.behaviors= {};
  
  this.attachBehaviors = function(a) {
    if (a) {
      $.each(self.behaviors, function() {
        this(a);
      });
    }
  };
  
  var beforeAhah = function(id, ui, o) {
    $(ui.newHeader).addClass('gmaps-accordion-loading');
    $(ui.newContent).addClass('gmaps-accordion-content-loading');

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

    // Restore the previous action and target to the form.
    if (o.form) {
      o.form.form.attr('action', o.form.form_action);
      o.form.form_target ? o.form.form.attr('target', o.form.form_target) : o.form.form.removeAttr('target');
      o.form.form_encattr ? o.form.form.attr('target', o.form.form_encattr) : o.form.form.removeAttr('encattr');
    }
    
    // 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/>");
    if (o.ajax) {
      r = r.data;
    }
    new_content.html(o.selector ?
      new_content
        .append(r.replace(/<script(.|\s)*?\/script>/g, ""))
        .find(o.selector) :
      r);

    // Remove the progress element.
    if (o.progress.element) {
      $(o.progress.element).remove();
    }
    if (o.progress.object) {
      o.progress.object.stopMonitoring();
    }
    if (o.cache) {
      $(ui.newContent).addClass('gmaps-accordion-ahah-processed');
    }
    $(ui.newHeader).removeClass('gmaps-accordion-loading');
    $(ui.newContent).removeClass('gmaps-accordion-content-loading');

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

    // Immediately hide the new content if we're using any effects.
    if (o.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)[o.showEffect](o.showSpeed);
    }
    else if (o.showEffect != 'show') {
      new_content[o.showEffect](o.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();
    
    $(element).trigger('gmapsaccordionload', [ui]);
  };
  
  var ahahError = function(r, element, ui, o) {
    alert(Drupal.ahahError(r, o.url));

    // Remove the progress element.
    if (o.progress.element) {
      $(o.progress.element).remove();
    }
    if (o.progress.object) {
      o.progress.object.stopMonitoring();
    }
    // Undo hide.
    $(o.wrapper).show();
    
    $(ui.newHeader).removeClass('gmaps-accordion-loading');
    $(ui.newContent).removeClass('gmaps-accordion-content-loading');
  };
  
  this.getAccordion = function(id, context, refresh) {
    if (self.accordions[id]) {
      if (refresh) {
        self.accordions[id] = null;
      }
      else {
        return self.accordions[id];
      }
    }
    context = context || document;
    var item = $('#'+ id, context), element = $('.gmaps-accordion:first', item), s = {options: {}},
      contentSelectedClass = 'ui-accordion-content-active';
    if (typeof(Drupal.settings.gmaps.accordion) != 'undefined' && typeof(Drupal.settings.gmaps.accordion[id]) != 'undefined') {
      s = $.extend(true, s, Drupal.settings.gmaps.accordion[id]);
    }
    if (typeof(s.options.active) != 'undefined' && s.options.active !== false) {
      s.options.active = parseInt(s.options.active);
    }
    //AHAH and AJAX content
    if (typeof(s.ahahPanels) != 'undefined') {
      var contentLoader = function(e, ui) {
        if (typeof(ui.newContent) != 'undefined' && ui.newContent.length && typeof(s.ahahPanels[ui.newContent[0].id]) != 'undefined') {
          var ahahOpts = $.extend(true, {}, s.ahahOptions || {}, s.ahahPanels[ui.newContent[0].id]);

          if (!ahahOpts.cache || !$(ui.newContent).hasClass('gmaps-accordion-ahah-processed')) {
            Drupal.gmaps.expandAhahOptions(ahahOpts, item);
            beforeAhah(item[0].id, ui, ahahOpts);
            
            var ajax = {
              url: ahahOpts.url,
              type: 'POST',
              dataType: ahahOpts.ajax ? 'json' : 'html',
              cache: ahahOpts.cache,
              success: function(r, s) {
                // Sanity check for browser support (object expected).
                // When using iFrame uploads, responses must be returned as a string.
                if (ahahOpts.ajax && typeof(r) == 'string') {
                  r = Drupal.parseJson(r);
                }
                return ahahSuccess(r, element, ui, ahahOpts);
              },
              complete: function(r, s) {
                if (s == 'error' || s == 'parsererror') {
                  return ahahError(r, element, ui, ahahOpts);
                }
              }
            };
            ajax.data = {'#accordion': {id: id, panel_id: ui.newContent[0].id}};
            if (ahahOpts.data) {
              ajax.data['#accordion'].data = ahahOpts.data;
            }
            if (!ahahOpts.ajax && ahahOpts.form) {
              $.each(ahahOpts.form.form.formToArray(), function() {
                ajax.data[this.name] = this.value;
              });
            }
            ajax.data = Drupal.gmaps.flatten(ajax.data);
            
            if (ahahOpts.ajax) {
              if (ahahOpts.form) {
                Drupal.gmaps.prepareAjaxOptions(ajax);
                ahahOpts.form.form.ajaxSubmit(ajax);
              }
              else {
                Drupal.gmaps.loadAjaxContent(ajax);
              }
            }
            else {
              $.ajax(ajax);
            }
          }
        }
      };
      s.options.changestart = contentLoader;
      
      //trigger content loading, if initial page is AHAH enabled
      if (typeof(s.options.active) != 'undefined' && s.options.active !== false) {
        var initialPanel = $('.gmaps-accordion-panel:eq('+ s.options.active +')', element);
        var ahahOpts = s.ahahPanels[initialPanel[0].id];
        if (typeof(ahahOpts) != 'undefined') {
          contentLoader(null, {newContent: initialPanel, newHeader: initialPanel.prev()});
        }
      }
    }
    self.accordions[id] = element.accordion(s.options).addClass('gmaps-accordion-processed');

    //simulate 1.7.1 panel theming
    $(element).bind('accordionchange', function(e, ui) {
      ui.newContent.addClass(contentSelectedClass);
      ui.oldContent.removeClass(contentSelectedClass);
    });

    var activated = false;
    $($(element).accordion('option', 'header'), element).each(function(){
      if ($('.error', $(this).next()).not('div.error').length) {
        $(this).addClass('error');
        if (!activated) {
          $(element).accordion('activate', this);
          activated = true;
        }
      }
    });
    self.attachBehaviors(element);
    
    return self.accordions[id];
  };
  
  this.cleanId = function(id) {
    var seenIds = $().data('seenIds.accordion.gmaps.drupal');
    if (!seenIds) {
      seenIds = {};
      $('.form-gmaps-accordion').each(function() {
        seenIds[this.id] = 1;
        $('.gmaps-accordion-panel', this).each(function() {
          seenIds[this.id] = 1;
        });
      });
    }

    var newid = id.replace(/[\]\[_\s]/g, '-');

    if (typeof(seenIds[newid]) != 'undefined') {
      newid = newid +'-'+ seenIds[newid]++;
    }
    else {
      seenIds[newid] = 1;
    }
    $().data('seenIds.accordion.gmaps.drupal', seenIds);

    return newid;
  };
  
  var preRender = function(element) {
    element['#id'] = self.cleanId('accordion-'+ (element['#id'] ? element['#id'] : 'gmaps'));
    
    element['#required'] = false;
    
    if (typeof(element['#accordion']) == 'undefined' || element['#accordion'] === null) {
      element['#accordion'] = {};
    }
    
    if (typeof(element['#accordion']['active']) == 'undefined') {
      element['#accordion']['active'] = null;
    }

    //drupalized shortcuts
    if (element['#collapsible']) {
      element['#accordion']['collapsible'] = true;
      if (element['#collapsed']) {
        element['#accordion']['active'] = false;
      }
      else if (element['#accordion']['active'] === false || element['#accordion']['active'] === null) {
        element['#accordion']['active'] = 0;
      }
    }
    else {
      element['#collapsed'] = false;
      element['#accordion']['collapsible'] = false;
    }
    //1.6
    element['#accordion']['alwaysOpen'] = !element['#accordion']['collapsible'];
    
    element['#accordion']['header'] = 'h3.'+ element['#id'];
    element['#accordion']['selectedClass'] = 'ui-state-active';
    
    //fieldsets are jumping around in IE6 when set to TRUE
    if (typeof(element['#accordion']['autoHeight']) == 'undefined' || element['#accordion']['autoHeight'] === null) {
      element['#accordion']['autoHeight'] = false;
    }
    if (typeof(element['#accordion']['navigation']) == 'undefined' || element['#accordion']['navigation'] === null) {
      element['#accordion']['navigation'] = false;
    }
      
    var i = 0, panel, firstPanelId;
    $.each(Drupal.elementChildren(element), function() {
      if (typeof(element[this]['#type']) != 'undefined' && element[this]['#type'] !== null && element[this]['#type'] == 'gmaps_accordion_panel') {
        panel = element[this];
        panel['#id'] = self.cleanId(element['#id'] +'-'+ (panel['#id'] ? panel['#id'] : 'panel'));
        panel['#accordion_id'] = element['#id'];
        
        //synchronize CSS and JS
        if (panel['#active_panel']) {
          if (element['#accordion']['active'] === null) {
            element['#accordion']['active'] = i;
          }
          else if (element['#accordion']['active'] === false || element['#accordion']['active'] != i) {
            panel['#active_panel'] = false;
          }
        }
        else if (element['#accordion']['active'] !== null && element['#accordion']['active'] !== false && element['#accordion']['active'] == i) {
          panel['#active_panel'] = true;
        }
        
        if (i == 0) {
          if (typeof(panel['#attributes']) == 'undefined' || panel['#attributes'] === null) {
            panel['#attributes'] = {};
          }
          if (typeof(panel['#attributes']['class']) == 'undefined' || panel['#attributes']['class'] === null) {
            panel['#attributes']['class'] = '';
          }
          panel['#attributes']['class'] += ' first';
          firstPanelId = this;
        }
        
        i++;
      }
    });
    if (element['#accordion']['active'] === null) {
      element['#accordion']['active'] = false;
    }
    if (i > 0) {
      i--;
      if (element['#accordion']['active'] !== false && element['#accordion']['active'] > i) {
        element['#accordion']['active'] = i;
        panel['#active_panel'] = true;
      }
    }
    if (typeof(panel['#attributes']) == 'undefined' || panel['#attributes'] === null) {
      panel['#attributes'] = {};
    }
    if (typeof(panel['#attributes']['class']) == 'undefined' || panel['#attributes']['class'] === null) {
      panel['#attributes']['class'] = '';
    }
    panel['#attributes']['class'] += ' last';
    
    if ((!element['#collapsible'] || !element['#collapsed']) && element['#accordion']['active'] === false) {
      element['#accordion']['active'] = 0;
      element[firstPanelId]['#active_panel'] = true;
    }
    
    if (typeof(Drupal.settings.gmaps.accordion) == 'undefined') {
      Drupal.settings.gmaps.accordion = {};
    }
    Drupal.settings.gmaps.accordion[element['#id']] = {'options': element['#accordion']};
    
    if (typeof(element['#attributes']) == 'undefined' || element['#attributes'] === null) {
      element['#attributes'] = {};
    }
    if (typeof(element['#attributes']['class']) == 'undefined' || element['#attributes']['class'] === null) {
      element['#attributes']['class'] = '';
    }
    var cls = 'form-gmaps-accordion';
    if (element['#embedded_item']) {
      cls += ' gmaps-accordion-embedded';
    }
    element['#attributes']['class'] = cls +' '+ element['#attributes']['class'];
    
    return element;
  };

  Drupal.hooks.elements.gmaps_accordion = {'#pre_render': {'default': preRender}};
})();

Drupal.gmaps.tabs = Drupal.gmaps.tabs || new (function() {
  var self = this;
  this.tabs = {};
  
  this.behaviors= {};
  
  this.attachBehaviors = function(t) {
    if (t) {
      $.each(self.behaviors, function() {
        this(t);
      });
    }
  };
  
  var beforeAhah = function(id, ui, o) {
    $(ui.tab).addClass('gmaps-tabs-loading');
    $(ui.panel).addClass('gmaps-tabs-content-loading');

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

    // Restore the previous action and target to the form.
    if (o.form) {
      o.form.form.attr('action', o.form.form_action);
      o.form.form_target ? o.form.form.attr('target', o.form.form_target) : o.form.form.removeAttr('target');
      o.form.form_encattr ? o.form.form.attr('target', o.form.form_encattr) : o.form.form.removeAttr('encattr');
    }
    
    // Manually insert HTML into the jQuery object, using $() directly crashes
    // Safari with long string lengths. http://dev.jquery.com/ticket/1152
    if (o.ajax) {
      r = r.data;
    }
    var new_content = $("<div/>");
    new_content.html(o.selector ?
      new_content
        .append(r.replace(/<script(.|\s)*?\/script>/g, ""))
        .find(o.selector) :
      r);

    // Remove the progress element.
    if (o.progress.element) {
      $(o.progress.element).remove();
    }
    if (o.progress.object) {
      o.progress.object.stopMonitoring();
    }
    if (o.cache) {
      $(ui.panel).addClass('gmaps-tabs-ahah-processed');
    }
    $(ui.tab).removeClass('gmaps-tabs-loading');
    $(ui.panel).removeClass('gmaps-tabs-content-loading');

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

    // Immediately hide the new content if we're using any effects.
    if (o.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)[o.showEffect](o.showSpeed);
    }
    else if (o.showEffect != 'show') {
      new_content[o.showEffect](o.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();
    
    $(element).trigger('gmapstabsload', [ui]);
  };
  
  var ahahError = function(r, element, ui, o) {
    alert(Drupal.ahahError(r, o.url));

    // Remove the progress element.
    if (o.progress.element) {
      $(o.progress.element).remove();
    }
    if (o.progress.object) {
      o.progress.object.stopMonitoring();
    }
    // Undo hide.
    $(o.wrapper).show();
    
    $(ui.tab).removeClass('gmaps-tabs-loading');
    $(ui.panel).removeClass('gmaps-tabs-content-loading');
  };
  
  this.getTabs = function(id, context, refresh) {
    if (self.tabs[id]) {
      if (refresh) {
        self.tabs[id] = null;
      }
      else {
        return self.tabs[id];
      }
    }
    context = context || document;
    var item = $('#'+ id, context), element = $('.gmaps-tabs:first', item), s = {options: {}};
    if (typeof(Drupal.settings.gmaps.tabs) != 'undefined' && typeof(Drupal.settings.gmaps.tabs[id]) != 'undefined') {
      s = $.extend(true, s, Drupal.settings.gmaps.tabs[id]);
    }
    if (typeof(s.options.selected) != 'undefined' && s.options.selected !== null) {
      s.options.selected = parseInt(s.options.selected);
    }
    if (typeof(s.options.disabled) != 'undefined') {
      var disabled = s.options.disabled;
      s.options.disabled = [];
      $.each(disabled, function(i, e) {if (e !== null) {s.options.disabled.push(parseInt(e, 10));}});
    }

    //AHAH/AJAX
    if (typeof(s.ahahPanels) != 'undefined') {
      var contentLoader = function(e, ui) {
        if (typeof(ui.panel) != 'undefined' && typeof(s.ahahPanels[ui.panel.id]) != 'undefined') {
          var ahahOpts = $.extend(true, {}, s.ahahOptions || {}, s.ahahPanels[ui.panel.id]);
          
          if (!ahahOpts.cache || !$(ui.panel).hasClass('gmaps-tabs-ahah-processed')) {
            Drupal.gmaps.expandAhahOptions(ahahOpts, item);
            beforeAhah(item[0].id, ui, ahahOpts);
            
            var ajax = {
              url: ahahOpts.url,
              type: 'POST',
              dataType: ahahOpts.ajax ? 'json' : 'html',
              cache: ahahOpts.cache,
              success: function(r, s) {
                // Sanity check for browser support (object expected).
                // When using iFrame uploads, responses must be returned as a string.
                if (ahahOpts.ajax && typeof(r) == 'string') {
                  r = Drupal.parseJson(r);
                }
                return ahahSuccess(r, element, ui, ahahOpts);
              },
              complete: function(r, s) {
                if (s == 'error' || s == 'parsererror') {
                  return ahahError(r, element, ui, ahahOpts);
                }
              }
            };
            ajax.data = {'#tabs': {id: id, panel_id: ui.panel.id}};
            if (ahahOpts.data) {
              ajax.data['#tabs'].data = ahahOpts.data;
            }
            if (!ahahOpts.ajax && ahahOpts.form) {
              $.each(ahahOpts.form.form.formToArray(), function() {
                ajax.data[this.name] = this.value;
              });
            }
            ajax.data = Drupal.gmaps.flatten(ajax.data);
            
            if (ahahOpts.ajax) {
              if (ahahOpts.form) {
                Drupal.gmaps.prepareAjaxOptions(ajax);
                ahahOpts.form.form.ajaxSubmit(ajax);
              }
              else {
                Drupal.gmaps.loadAjaxContent(ajax);
              }
            }
            else {
              $.ajax(ajax);
            }
          }
        }
      };
      s.options.show = contentLoader;
    }
    self.tabs[id] = element.tabs(s.options).addClass('gmaps-tabs-processed');

    var selected = false;
    $('.gmaps-tabs-panel', element).each(function(){
      if ($('.error', this).not('div.error').length) {
        $('a[href=#'+ this.id +']', element).addClass('error');
        if (!selected) {
          element.tabs('select', '#'+ this.id);
          selected = true;
        }
      }
    });
    
    self.attachBehaviors(element);
    
    return self.tabs[id];
  };
  
  this.cleanId = function(id) {
    var seenIds = $().data('seenIds.tabs.gmaps.drupal');
    if (!seenIds) {
      seenIds = {};
      $('.form-gmaps-tabs').each(function() {
        seenIds[this.id] = 1;
        $('.gmaps-tabs-panel', this).each(function() {
          seenIds[this.id] = 1;
        });
      });
    }

    var newid = id.replace(/[\]\[_\s]/g, '-');

    if (typeof(seenIds[newid]) != 'undefined') {
      newid = newid +'-'+ seenIds[newid]++;
    }
    else {
      seenIds[newid] = 1;
    }
    $().data('seenIds.tabs.gmaps.drupal', seenIds);

    return newid;
  };
  
  var preRender = function(element) {
    element['#id'] = self.cleanId('tabs-'+ (element['#id'] ? element['#id'] : 'gmaps'));
    
    element['#required'] = false;
    
    if (typeof(element['#nav_position']) == 'undefined' || element['#nav_position'] === null) {
      element['#nav_position'] = GMAPS_TABS_NAV_TOP;
    }
    
    if (typeof(element['#tabs']) == 'undefined' || element['#tabs'] === null) {
      element['#tabs'] = {};
    }
    
    if (typeof(element['#tabs']['selected']) == 'undefined' || !(!isNaN(element['#tabs']['selected']) || element['#tabs']['selected'] === null)) {
      element['#tabs']['selected'] = false;
    }
    
    element['#tabs']['tabSelector'] = 'li.'+ element['#id'] +'-tab';
    element['#tabs']['tabTemplate'] = '<li class="gmaps-tabs-tab '+ element['#id'] +'-tab"><a href="#{href}"><span>#{label}</span></a></li>';
    element['#tabs']['panelTemplate'] = '<div class="gmaps-tabs-panel '+ element['#id'] +'-panel"></div>';
    element['#tabs']['deselectableClass'] = 'ui-tabs-collapsible';
    element['#tabs']['idPrefix'] = element['#id'] +'-tab-';

    if (element['#nav_position'] == GMAPS_TABS_NAV_TOP) {
      if (typeof(element['#collapsible']) == 'undefined') {
        element['#collapsible'] = false;
      }
    }
    else {
      element['#collapsible'] = false;
    }
    element['#tabs']['collapsible'] = element['#tabs']['deselectable'] = element['#collapsible'];
    if (element['#collapsible']) {
      if (element['#collapsed']) {
        element['#tabs']['selected'] = null;
      }
      else if (element['#tabs']['selected'] === null || element['#tabs']['selected'] === false) {
        element['#tabs']['selected'] = 0;
      }
    }
    
    //tabs
    var i = 0, panel, firstPanelId;
    $.each(Drupal.elementChildren(element), function() {
      if (typeof(element[this]['#type']) != 'undefined' && element[this]['#type'] == 'gmaps_tabs_panel') {
        panel = element[this];
        panel['#id'] = self.cleanId(element['#id'] +'-'+ (panel['#id'] ? panel['#id'] : 'panel'));
        panel['#tabs_id'] = element['#id'];
        
        //synchronize CSS and JS
        if (panel['#selected_panel']) {
          if (element['#tabs']['selected'] === false) {
            element['#tabs']['selected'] = i;
          }
          else if (element['#tabs']['selected'] === null || element['#tabs']['selected'] != i) {
            panel['#selected_panel'] = false;
          }
        }
        else if (element['#tabs']['selected'] !== null && element['#tabs']['selected'] !== false && element['#tabs']['selected'] == i) {
          panel['#selected_panel'] = true;
        }
        
        if (i == 0) {
          if (typeof(panel['#attributes']) == 'undefined' || panel['#attributes'] === null) {
            panel['#attributes'] = {};
          }
          if (typeof(panel['#attributes']['class']) == 'undefined' || panel['#attributes']['class'] === null) {
            panel['#attributes']['class'] = '';
          }
          panel['#attributes']['class'] += ' first';
          firstPanelId = this;
        }
        
        i++;
      }
    });
    if (element['#tabs']['selected'] === false) {
      element['#tabs']['selected'] = null;
    }
    if (i > 0) {
      i--;
      if (element['#tabs']['selected'] !== null && element['#tabs']['selected'] > i) {
        element['#tabs']['selected'] = i;
        panel['#selected_panel'] = true;
      }
    }
    if (typeof(panel['#attributes']) == 'undefined' || panel['#attributes'] === null) {
      panel['#attributes'] = {};
    }
    if (typeof(panel['#attributes']['class']) == 'undefined' || panel['#attributes']['class'] === null) {
      panel['#attributes']['class'] = '';
    }
    panel['#attributes']['class'] += ' last';
    
    if ((!element['#collapsible'] || !element['#collapsed']) && element['#tabs']['selected'] === null) {
      element['#tabs']['selected'] = 0;
      element[firstPanelId]['#selected_panel'] = true;
    }
    
    if (typeof(Drupal.settings.gmaps.tabs) == 'undefined') {
      Drupal.settings.gmaps.tabs = {};
    }
    Drupal.settings.gmaps.tabs[element['#id']] = {'options': element['#tabs']};
    
    if (typeof(element['#attributes']) == 'undefined' || element['#attributes'] === null) {
      element['#attributes'] = {};
    }
    if (typeof(element['#attributes']['class']) == 'undefined' || element['#attributes']['class'] === null) {
      element['#attributes']['class'] = '';
    }
    var cls = 'form-gmaps-tabs gmaps-tabs-nav-'+ element['#nav_position'];
    if (element['#embedded_item']) {
      cls += ' gmaps-tabs-embedded';
    }
    element['#attributes']['class'] = cls +' '+ element['#attributes']['class'];
    
    return element;
  };

  Drupal.hooks.elements.gmaps_tabs = {'#pre_render': {'default': preRender}};
})();

/**
 * Cache object.
 */
GMapsCache = function() {
  var cache = {};
  
  this.set = function(cid, data) {
    cache[cid] = data;
  };
  
  this.get = function(cid) {
    if (typeof(cache[cid]) != 'undefined') {
      return cache[cid];
    }
    return null;
  };
  
  this.clearAll = function(cid) {
    if (cid == null) {
      cache = {};
    }
    else {
      delete cache[cid];
    }
  };
};

/**
 * Icon select object
 * 
 * @param select
 *  jQuery object of the "select" dom element
 */
GMapsIconSelectElement = function(select) {
  var gis = this;
  var parent = $(select).parent('div.gis-preview-wrapper');
  var img = $('img.gis-preview', parent);
  
  var preview = function(e) {
    img.hide();
    
    if (typeof(Drupal.settings.gmaps) == 'undefined' || typeof(Drupal.settings.gmaps.iconSelect) == 'undefined' ||
        typeof(Drupal.settings.gmaps.iconSelect[select[0].id]) == 'undefined') {
      return;
    }
    
    var attr = Drupal.settings.gmaps.iconSelect[select[0].id][select.fieldValue()[0]];
    
    if (typeof(attr) == 'undefined' || typeof(attr.src) == 'undefined') {
    }
    else {
      img.attr('src', attr.src);
      img.css({'width': attr.width, 'height': attr.height});
      img.show();
    }
  };
  
  select.change(preview).keyup(preview);
  
  preview();
};


;
// $Id: gmaps-map.js,v 1.1.2.11 2010/03/18 10:52:16 xmarket Exp $

GMAPS_MAP_EARTH = 'earth';

GMAPS_MAP_MIN_HEIGHT = 50;
GMAPS_MAP_DEFAULT_ZOOM = 10;
GMAPS_MAP_LAZY_INIT_TIMEOUT = 500;
GMAPS_MAP_DEFAULT_BOUNDS_SPAN = 1;
GMAPS_MAP_SVU_MIN_HEIGHT = 100;
GMAPS_MAP_MAPTYPE_CONTROL = 'maptype';

GMAPS_MAP_ACZ_MODE_BOTH = 0;
GMAPS_MAP_ACZ_MODE_CENTER = 1;
GMAPS_MAP_ACZ_MODE_ZOOM = 2;

GMAPS_CONTROL_POSITION_DEFAULT = -1;

Drupal.behaviors.gmapsMapItem = function(context) {
  if (GBrowserIsCompatible()) {
    $('.gmaps-map-item span.loading', context).show();
    $('.gmaps-map-item:not(.gmaps-map-item-embedded)', context).each(function(index, element) {
      var handler, init = function() {Drupal.gmaps.map.getMap(element.id, context, true, true);};
      if (handler = Drupal.gmaps.getLazyInitHandler('#'+ element.id, context)) {
        handler.attach('#'+ element.id, init, context);
      }
      else {
        setTimeout(init, 5);
      }
    });
  }
};

Drupal.theme.prototype.gmapsInfoWindowContent = function(title, content) {
  var output = (title ? '<h3 class="gmaps-info-window-title">'+ title +'</h3>' : '');
  output += '<div class="gmaps-info-window-content">'+ content +'</div>';
  return output;
};

/**
 * GMap2 extensions
 */

/**
 * AdsManager method
 * @return
 */
GMap2.prototype.enableAdsManager = function() {
  if (!this.gmaps.adsManager) {
    var opts = this.gmaps.gmi.getOptions().base.method_data.adsmanager;
    var admOpts = {'style': G_ADSMANAGER_STYLE_ADUNIT, 'maxAdsOnMap': parseInt(opts.maxads), 'minZoomLevel': parseInt(opts.minzoom)};
    if (opts.channel.length) {
      admOpts.channel = opts.channel;
    }
    if (opts.position) {
      var anchor = opts.position.anchor ? parseInt(opts.position.anchor, 10) : GMAPS_CONTROL_POSITION_DEFAULT;
      if (anchor > GMAPS_CONTROL_POSITION_DEFAULT && opts.position.offset) {
        var offset = new GSize(parseInt(opts.position.offset.width, 10), parseInt(opts.position.offset.height, 10));
        admOpts.position = new GControlPosition(anchor, offset);
      }
    }
    this.gmaps.adsManager = new GAdsManager(this, opts.client, admOpts);
  }
  if (this.gmaps.adsManager) {
    this.gmaps.adsManager.enable();
  }
};
GMap2.prototype.disableAdsManager = function() {
  if (this.gmaps.adsManager) {
    this.gmaps.adsManager.disable();
  }
};

/**
 * AutoCenterZoom method
 */
GMap2.prototype.enableAutoCenterZoom = function() {
  if (!this.gmaps.gmi.isInitialized()) {
    this.gmaps.aczOverlayListener = GEvent.addListener(this, 'addoverlay', this._gmapsAczAddOverlay);
    
    this.gmaps.aczInitListener = GEvent.addListener(this.gmaps.gmi, 'initialized', this._gmapsAczInitialized);
  }
};

GMap2.prototype._gmapsAczAddOverlay = function(ov) {
  var bounds = Drupal.gmaps.map.getOverlayBounds(ov);
  
  if (bounds) {
    if (!this.gmaps.aczBounds) {
      this.gmaps.aczBounds = bounds;
    }
    else {
      this.gmaps.aczBounds.extend(bounds.getSouthWest());
      this.gmaps.aczBounds.extend(bounds.getNorthEast());
    }
  }
};

GMap2.prototype._gmapsAczInitialized = function() {
  GEvent.removeListener(this.gmap2.gmaps.aczOverlayListener);
  GEvent.removeListener(this.gmap2.gmaps.aczInitListener);
  if (this.gmap2.gmaps.aczBounds) {
    var aczOpts = this.gmap2.gmaps.gmi.getOptions().base.method_data;
    if (!aczOpts) {
      aczOpts = {auto_center_zoom: null};
    }
    var opts = aczOpts.auto_center_zoom;
    if (!opts) {
      opts = {mode: GMAPS_MAP_ACZ_MODE_BOTH};
    }
    var zoom = parseInt(this.gmap2.gmaps.gmi.getOptions().base.zoom, 10);
    if (opts.mode == GMAPS_MAP_ACZ_MODE_CENTER) {
      this.gmap2.setCenter(this.gmap2.gmaps.aczBounds.getCenter());
    }
    else if (opts.mode == GMAPS_MAP_ACZ_MODE_ZOOM) {
      if (zoom == -1) {
        this.gmap2.setZoom(this.gmap2.getBoundsZoomLevel(this.gmap2.gmaps.aczBounds));
      }
    }
    else {
      zoom = (zoom == -1) ? this.gmap2.getBoundsZoomLevel(this.gmap2.gmaps.aczBounds) : this.gmap2.getZoom();
      this.gmap2.setCenter(this.gmap2.gmaps.aczBounds.getCenter(), zoom);
    }
    delete this.gmap2.gmaps.aczMethod;
  }
};

/**
 * KeyboardHandler method
 */
GMap2.prototype.enableKeyboardHandler = function() {
  if (!this.gmaps.keyboardHandler) {
    this.gmaps.keyboardHandler = new GKeyboardHandler(this);
  }
};

/**
 * Layers method
 */
GMap2.prototype.enableLayers = function() {
  if (!this.gmaps.layers.length) {
    var gmap2 = this;
    jQuery.each(this.gmaps.gmi.getOptions().base.method_data.layers.layers, function(index, layerId) {
      var layer = new GLayer(layerId);
      gmap2.gmaps.layers[index] = layer;
      gmap2.addOverlay(layer);
    });
  }
};
GMap2.prototype.disableLayers = function() {
  if (this.gmaps.layers.length) {
    var gmap2 = this;
    jQuery.each(this.gmaps.layers, function() {
      gmap2.removeOverlay(this);
    });
    this.gmaps.layers = {};
  }
};

/**
 * Resize method
 */
GMap2.prototype.enableResize = function() {
  if (!this.gmaps.isAutoCenterZoomEnabled) {
    this.gmaps.isAutoCenterZoomEnabled = true;
    var gmap2 = this;  
    var cont = $('.gmaps-map-container-wrapper', this.gmaps.gmi.getContainer()), staticOffset = null;
  
    $(cont).wrap('<div class="resizable-gmaps-map-container"><span></span></div>')
    .parent().append($('<div class="grippie"></div>').mousedown(startDrag));
  
    var grippie = $('div.grippie', $(cont).parent())[0];
    grippie.style.marginRight = (grippie.offsetWidth - $(cont)[0].offsetWidth) +'px';
  }

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

  function performDrag(e) {
    cont.height(Math.max(32, staticOffset + e.pageY) + 'px');
    $('.gmaps-map-container', cont).height(cont.height() + 'px');
    return false;
  }

  function endDrag(e) {
    $(document).unbind("mousemove", performDrag).unbind("mouseup", endDrag);
    cont.css('opacity', 1);
    var center = gmap2.getCenter();
    gmap2.checkResize();
    gmap2.setCenter(center);
  }
};

/**
 * Street view method
 */
GMap2.prototype.enableStreetView = function() {
  if (!this.gmaps.streetView.overlay) {
    var gmap2 = this;
    this.gmaps.streetView.overlay = new GStreetviewOverlay();
    this.addOverlay(this.gmaps.streetView.overlay);
    
    if (parseInt(this.gmaps.gmi.getOptions().base.method_data.streetview.opensvu)) {
      this.gmaps.streetView.listener = GEvent.addListener(this, 'click', function(ov, ll, ovll) {
        if (!ov && !gmap2.gmaps.streetView.timer) {
          gmap2.gmaps.streetView.timer = setTimeout(function() {
            gmap2.gmaps.streetView.timer = null;
            gmap2.gmaps.gmi.getSVU().setLatLng(ll);
          }, 500);
        }
      });
      if (this.gmaps.gmi.getOptions().base.methods['dblclickzoom']) {
        this.gmaps.streetView.zoomListener = GEvent.addListener(this, 'dblclick', function(ov, ll) {
          if (gmap2.gmaps.streetView.timer) {
            gmap2.gmaps.streetView.timer = clearTimeout(gmap2.gmaps.streetView.timer);
          }
        });
      }
    }
  }
};
GMap2.prototype.disableStreetView = function() {
  if (this.gmaps.streetView.overlay) {
    this.removeOverlay(this.gmaps.streetView.overlay);
    this.gmaps.streetView.overlay = null;
    
    if (this.gmaps.streetView.listener) {
      GEvent.removeListener(this.gmaps.streetView.listener);
      this.gmaps.streetView.listener = null;
    }
    if (this.gmaps.streetView.zoomListener) {
      GEvent.removeListener(this.gmaps.streetView.zoomListener);
      this.gmaps.streetView.zoomListener = null;
    }
  }
};

/**
 * Traffic method
 */
GMap2.prototype.enableTraffic = function() {
  if (!this.gmaps.traffic) {
    this.gmaps.traffic = new GTrafficOverlay({'incidents': parseInt(this.gmaps.gmi.getOptions().base.method_data.traffic.incidents) ? true : false});
    this.addOverlay(this.gmaps.traffic);
  }
};
GMap2.prototype.disableTraffic = function() {
  if (this.gmaps.traffic) {
    this.removeOverlay(this.gmaps.traffic);
    this.gmaps.traffic = null;
  }
};

/**
 * KeyDragZoom method
 */
GMap2.prototype.enableGMapsKeyDragZoom = function() {
  if (this.enableKeyDragZoom) {
    var opts = this.gmaps.gmi.getOptions().base.method_data.keydragzoom;
    this.enableKeyDragZoom({
      key: opts.key,
      border: opts.border
    });
  }
};
GMap2.prototype.disableGMapsKeyDragZoom = function() {
  if (this.disableKeyDragZoom) {
    this.disableKeyDragZoom();
  }
};

/**
 * Reference implementation of MapTypeHandler "interface".
 */
GMapsMapTypeHandler = function() {
  this.createMapType = function(gmi, type) {
    if (type == 'normal') {
      return G_NORMAL_MAP;
    }
    else if (type == 'satellite') {
      return G_SATELLITE_MAP;
    }
    else if (type == 'hybrid') {
      return G_HYBRID_MAP;
    }
    else if (type == 'physical') {
      return G_PHYSICAL_MAP;
    }
    else if (type == 'satellite_3D') {
      return G_SATELLITE_3D_MAP;
    }
    else if (type == 'aerial') {
      return G_AERIAL_MAP;
    }
    else if (type == 'aerial_hybrid') {
      return G_AERIAL_HYBRID_MAP;
    }
    else if (type == 'mapmaker_normal') {
      return G_MAPMAKER_NORMAL_MAP;
    }
    else if (type == 'mapmaker_hybrid') {
      return G_MAPMAKER_HYBRID_MAP;
    }
    else if (type == 'moon_elevation') {
      return G_MOON_ELEVATION_MAP;
    }
    else if (type == 'moon_visible') {
      return G_MOON_VISIBLE_MAP;
    }
    else if (type == 'mars_elevation') {
      return G_MARS_ELEVATION_MAP;
    }
    else if (type == 'mars_visible') {
      return G_MARS_VISIBLE_MAP;
    }
    else if (type == 'mars_infrared') {
      return G_MARS_INFRARED_MAP;
    }
    else if (type == 'sky_visible') {
      return G_SKY_VISIBLE_MAP;
    }
  };
};

/**
 * Reference implementation of ControlHandler "interface".
 */
GMapsControlHandler = function() {
  var extDragZoomOverwritten = false;
  
  var overwriteExtDragZoom = function() {
    if (!extDragZoomOverwritten) {
      extDragZoomOverwritten = true;
      DragZoomControl.prototype.initButton_ = function(buttonContainerDiv) {
        var G = this.globals;
        var buttonDiv = document.createElement('div');
        buttonDiv.innerHTML = G.options.buttonHTML;
        DragZoomUtil.style([buttonDiv], {cursor: 'pointer', zIndex:200});
        $(buttonDiv).addClass('gmaps-map-control-extdragzoom-starting '+ G.gmaps.style.starting);
        $(buttonDiv).addClass('gmaps-map-control-extdragzoom-button '+ G.gmaps.style.button);
        buttonContainerDiv.appendChild(buttonDiv);
        return buttonDiv;
      };
      
      DragZoomControl.prototype.initBackButton_ = function(buttonContainerDiv) {
        var G = this.globals;
        var backButtonDiv = document.createElement('div');
        backButtonDiv.innerHTML = G.options.backButtonHTML;
        DragZoomUtil.style([backButtonDiv], {cursor: 'pointer', zIndex:200});
        $(backButtonDiv).addClass('gmaps-map-control-extdragzoom-starting '+ G.gmaps.style.starting);
        $(backButtonDiv).addClass('gmaps-map-control-extdragzoom-back '+ G.gmaps.style.back);
        buttonContainerDiv.appendChild(backButtonDiv);
        return backButtonDiv;
      };
      
      DragZoomControl.prototype.setButtonMode_ = function(mode){
        var G = this.globals;
        if (mode == 'zooming') {
          G.buttonDiv.innerHTML = G.options.buttonZoomingHTML;
          $(G.buttonDiv).addClass('gmaps-map-control-extdragzoom-zooming '+ G.gmaps.style.zooming);
          $(G.buttonDiv).removeClass('gmaps-map-control-extdragzoom-button '+ G.gmaps.style.button);
        } else {
          G.buttonDiv.innerHTML = G.options.buttonHTML;
          $(G.buttonDiv).addClass('gmaps-map-control-extdragzoom-button '+ G.gmaps.style.button);
          $(G.buttonDiv).removeClass('gmaps-map-control-extdragzoom-zooming '+ G.gmaps.style.zooming);
        }
      };
    }
  };
  
  this.createControl = function(gmi, type) {
    if (type == 'smallzoom') {
      return new GSmallZoomControl();
    }
    else if (type == 'smallmap') {
      return new GSmallMapControl();
    }
    else if (type == 'largemap') {
      return new GLargeMapControl();
    }
    else if (type == 'smallzoom3D') {
      return new GSmallZoomControl3D();
    }
    else if (type == 'largemap3D') {
      return new GLargeMapControl3D();
    }
    else if (type == 'extnav') {
      var opts = gmi.getOptions().base.control_data.extnav;
      var exOpts = {'type': opts.type};
      exOpts.moveEastBtnTitle = opts.title.east;
      exOpts.moveWestBtnTitle = opts.title.west;
      exOpts.moveNorthBtnTitle = opts.title.north;
      exOpts.moveSouthBtnTitle = opts.title.south;
      exOpts.returnBtnTitle = opts.title['return'];
      exOpts.zoomInBtnTitle = opts.title.zoomin;
      exOpts.zoomOutBtnTitle = opts.title.zoomout;
      return new ExtLargeMapControl(exOpts);
    }
    else if (type == 'scale') {
      return new GScaleControl();
    }
    else if (type == 'maptype') {
      return new GMapTypeControl(parseInt(gmi.getOptions().base.control_data.maptype.shortnames) ? true : false);
    }
    else if (type == 'menumaptype') {
      return new GMenuMapTypeControl(parseInt(gmi.getOptions().base.control_data.menumaptype.shortnames) ? true : false);
    }
    else if (type == 'hierarchical_maptype') {
      return new GHierarchicalMapTypeControl();
    }
    else if (type == 'extmaptype') {
      var opts = gmi.getOptions().base.control_data.extmaptype;
      var opt_opts = {
        'showTraffic': parseInt(opts.traffic) ? true : false,
        'showTrafficKey': parseInt(opts.traffickey) ? true : false,
        'showMore': parseInt(opts.more) ? true : false,
        'showSave': parseInt(opts.save) ? true : false
      };
      if (typeof(opts.maptype) == 'undefined' || !opts.maptype || opts.maptype == 'extmaptype') {
        opt_opts.useMapTypes = true;
      }
      else {
        var ct_opts = $.extend(true, {}, gmi.getOptions().base.controls.maptype);
        ct_opts.control = opts.maptype;
        if (typeof(opts.control_data) != 'undefined') {
          gmi.getOptions().base.control_data[opts.maptype] = opts.control_data;
        }
        gmi.addControl('extmaptype_maptype', ct_opts);
        opt_opts.posRight = opts.pos_right ? parseInt(opts.pos_right) : 100;
      }
        
      var control = new ExtMapTypeControl(opt_opts);
      
      if (!opt_opts.useMapTypes) {
        control.gmaps = {'maptype': gmi.controls['extmaptype_maptype']};
      }
      
      return control;
    }
    else if (type == 'overview') {
      return new GOverviewMapControl();
    }
    else if (type == 'extdragzoom') {
      var opts = gmi.getOptions().base.control_data.extdragzoom;
      var boxStyle = {
        'fillColor': opts.boxstyle.fillcolor,
        'border': opts.boxstyle.border,
        'opacity': parseFloat(opts.boxstyle.opacity)
      };
      var others = {
        'buttonHTML': opts.other.button_html,
        'buttonZoomingHTML': opts.other.zooming_html,
        'backButtonHTML': opts.other.back_html,
        'backButtonEnabled': parseInt(opts.other.back_button),
        'overlayRemoveTime': parseInt(opts.other.overlay_time),
        'stickyZoomEnabled': parseInt(opts.other.sticky_zoom),
        'rightMouseZoomOutEnabled': parseInt(opts.other.zoom_out),
        'minDragSize': parseInt(opts.other.dragsize)
      };

      overwriteExtDragZoom();
      
      var control = new DragZoomControl(boxStyle, others);
      control.globals.gmaps = {'style': opts.other.style};

      return control;
    }
    else if (type == 'breadcrumb') {
      var opts = gmi.getOptions().base.control_data.breadcrumb;
      if (!opts) {
        opts = {level: 0};
      }
      opts.level = parseInt(opts.level);
      
      var control = new GNavLabelControl();
      
      if (opts.level > 0) {
        control.setMinAddressLinkLevel(opts.level);
      }
      
      return control;
    }
  };
};

/**
 * Reference implementation of interface "InfoWindowHandler"
 * for API info window
 */
GMapsInfoWindowHandlerGoogle = function(gmi) {
  var self = this, opts = {};
  
  var parseOpts = function(gmapsOpts) {
    var o = {};
    o.maxWidth = parseInt(gmapsOpts.maxwidth, 10);
    o.noCloseOnClick = parseInt(gmapsOpts.nocloseonclick, 10);
    o.pixelOffset = new GSize(parseInt(gmapsOpts.offset.x, 10), parseInt(gmapsOpts.offset.y, 10));
    o.maximized = parseInt(gmapsOpts.maximized, 10);
    if (gmapsOpts.blowup.type && gmapsOpts.blowup.type.length && typeof(gmi.maptypes[gmapsOpts.blowup.type]) != 'undefined') {
      o.mapType = gmi.maptypes[gmapsOpts.blowup.type];
    }
    if (parseInt(gmapsOpts.blowup.zoom, 10) > -1) {
      o.zoomLevel = parseInt(gmapsOpts.blowup.zoom, 10);
    }
    return o;
  };
  
  var initialize = function() {
    opts = parseOpts(gmi.getOptions().base.iw_data.google);
  };
  
  this.openInfoWindow = function(latlng, content, iwOpts) {
    var currentOpts = $.extend(true, {}, opts, iwOpts ? iwOpts : {});
    var minContent, maxContent, tabs = [], opened = false;
    if (typeof(content.max) != 'undefined' && content.max !== null && content.max.length) {
      maxContent = $('<div/>').html(content.max)[0];
      Drupal.attachBehaviors(maxContent);
      currentOpts.maxContent = maxContent;
    }
    if (!currentOpts.maxTitle && content.title) {
      currentOpts.maxTitle = content.title;
    }
    
    if (typeof(content.tabs) != 'undefined') {
      $.each(content.tabs, function(label, tabContent) {
        tabContent = $('<div/>').html(tabContent)[0];
        Drupal.attachBehaviors(tabContent);
        tabs.push(new GInfoWindowTab(label, tabContent));
      });
      if (tabs.length) {
        gmi.gmap2.openInfoWindowTabs(latlng, tabs, currentOpts);
        if (maxContent) opened = true;
      }
    }
    else if (typeof(content.min) != 'undefined' && content.min !== null && content.min.length) {
      delete currentOpts.selectedTab;
      minContent = $('<div/>').html(Drupal.theme('gmapsInfoWindowContent', content.title, content.min))[0];
      Drupal.attachBehaviors(minContent);
      gmi.gmap2.openInfoWindow(latlng, minContent, currentOpts);
      if (maxContent) opened = true;
    }
    else if (maxContent) {
      delete currentOpts.maxContent;
      if (currentOpts.maxTitle) {
        maxContent = $('<div/>').html(Drupal.theme('gmapsInfoWindowContent', currentOpts.maxTitle, content.max))[0];
        delete currentOpts.maxTitle;
      }
      gmi.gmap2.openInfoWindow(latlng, maxContent, currentOpts);
    }
    
    if (opened && currentOpts.maximized) {
      var iw = gmi.gmap2.getInfoWindow();
      var m = GEvent.addListener(gmi.gmap2, 'infowindowopen', function () {
        GEvent.removeListener(m);
        iw.maximize();
      });
    }
  };
  
  this.openMarkerInfoWindow = function(marker, content) {
    var currentOpts;
    if (marker.gmaps.options.iw_data && marker.gmaps.options.iw_data[marker.gmaps.options.basic.info_window]) {
      currentOpts = $.extend(true, {}, opts, parseOpts(marker.gmaps.options.iw_data[marker.gmaps.options.basic.info_window]));
    }
    else {
      currentOpts = $.extend(true, {}, opts);
    }
    var minContent, maxContent, tabs = [], opened = false;
    if (typeof(content.max) != 'undefined' && content.max !== null && content.max.length) {
      maxContent = $('<div/>').html(content.max)[0];
      Drupal.attachBehaviors(maxContent);
      currentOpts.maxContent = maxContent;
    }
    if (!currentOpts.maxTitle && content.title) {
      currentOpts.maxTitle = content.title;
    }
    
    if (typeof(content.tabs) != 'undefined') {
      $.each(content.tabs, function(label, tabContent) {
        tabContent = $('<div/>').html(tabContent)[0];
        Drupal.attachBehaviors(tabContent);
        tabs.push(new GInfoWindowTab(label, tabContent));
      });
      if (tabs.length) {
        marker.openInfoWindowTabs(tabs, currentOpts);
        if (maxContent) opened = true;
      }
    }
    else if (typeof(content.min) != 'undefined' && content.min !== null && content.min.length) {
      delete currentOpts.selectedTab;
      minContent = $('<div/>').html(Drupal.theme('gmapsInfoWindowContent', content.title, content.min))[0];
      Drupal.attachBehaviors(minContent);
      marker.openInfoWindow(minContent, currentOpts);
      if (maxContent) opened = true;
    }
    else if (maxContent) {
      delete currentOpts.maxContent;
      if (currentOpts.maxTitle) {
        maxContent = $('<div/>').html(Drupal.theme('gmapsInfoWindowContent', currentOpts.maxTitle, content.max))[0];
        delete currentOpts.maxTitle;
      }
      marker.openInfoWindow(maxContent, currentOpts);
    }
    
    if (opened && currentOpts.maximized) {
      var iw = marker.gmaps.gmi.gmap2.getInfoWindow();
      var m = GEvent.addListener(marker.gmaps.gmi.gmap2, 'infowindowopen', function () {
        GEvent.removeListener(m);
        iw.maximize();
      });
    }
  };
  
  initialize();
};

/**
 * Reference implementation of interface "InfoWindowHandler"
 * for Bulletin board info window
 */
GMapsInfoWindowHandlerBulletinBoard = function(gmi) {
  var self = this, opts;
  
  var parseOpts = function(gmapsOpts) {
    var o = $.extend(true, {}, gmapsOpts);
    o.collapsible = parseInt(o.collapsible, 10);
    o.collapsed = parseInt(o.collapsed, 10);
    o.tabs_state = o.tabs_state || 'max';
    o.maximized = o.maximized ? parseInt(o.maximized, 10) : 0;
    return o;
  };
  
  var initialize = function() {
    opts = parseOpts(gmi.getOptions().base.iw_data.bb);
  };
  
  var showContent = function(content, currentOpts) {
    gmi.gmap2.closeInfoWindow();

    var minContent, maxTitle, maxContent, tabs, hasMin, hasMax;
    
    hasMin = typeof(content.min) != 'undefined' && content.min !== null && content.min.length;
    hasMax = typeof(content.max) != 'undefined' && content.max !== null && content.max.length;
    
    if (!hasMin && hasMax) {
      content.min = content.max;
      currentOpts.tabs_state = 'min';
      delete content.max;
    }
    
    if (typeof(content.tabs) != 'undefined') {
      if (currentOpts.style == 'plain') {
        tabs = Drupal.gmaps.map.renderTabsPlain(content.tabs);
      }
      else if (currentOpts.style == 'list') {
        tabs = Drupal.gmaps.map.renderTabsList(content.tabs);
      }
      else if (currentOpts.style == 'grid') {
        tabs = Drupal.gmaps.map.renderTabsList(content.tabs, currentOpts);
      }
      else if (currentOpts.style == 'box') {
        tabs = Drupal.gmaps.map.renderTabsBox(content.tabs);
      }
      else if (currentOpts.style == 'fieldset') {
        tabs = Drupal.gmaps.map.renderTabsFieldset(content.tabs, currentOpts);
      }
      else if (currentOpts.style == 'accordion') {
        tabs = Drupal.gmaps.map.renderTabsAccordion(content.tabs, currentOpts);
      }
      else if (currentOpts.style == 'tabs') {
        tabs = Drupal.gmaps.map.renderTabsTabs(content.tabs, currentOpts);
      }
      
      if (tabs) {
        currentOpts.tabs = true;
      }
    }
    
    if (hasMin) {
      minContent = Drupal.theme('gmapsInfoWindowContent', content.title, content.min);
      if (tabs && currentOpts.tabs_state == 'min') {
        minContent += tabs;
      }
      if (hasMax) {
        minContent = '<div class="gmaps-bbinfowindow-minimize"></div><div class="gmaps-bbinfowindow-maximize"></div><div id="'+ gmi.getContainer()[0].id +'-bbinfowindow-mincontent">'+ minContent +'</div>';
      }
    }
    
    if (hasMax) {
      maxTitle = currentOpts.maxTitle || content.title;
      maxContent = Drupal.theme('gmapsInfoWindowContent', maxTitle, content.max);
      if (tabs && currentOpts.tabs_state == 'max') {
        maxContent += tabs;
      }
      maxContent = '<div id="'+ gmi.getContainer()[0].id +'-bbinfowindow-maxcontent">'+ maxContent +'</div>';
    }
    else {
      currentOpts.maximized = 0;
    }
    
    var c = (minContent || '') + (maxContent || '');
    if (c.length) {
      c = $('<div/>').html(c)[0];
      gmi.bulletinBoardShow(c);
      var bb = gmi.getBulletinBoard();
      if (hasMax) {
        addStateListeners(bb);
        switchState(currentOpts.maximized ? 'max' : 'min', bb);
      }
      if (gmi.gmap2.gmaps.bbInfoWindowListener == null) {
        gmi.gmap2.gmaps.bbInfoWindowListener = GEvent.addListener(gmi.gmap2, 'infowindowopen', function() {
          gmi.bulletinBoardHide();
        });
      }
      //GEvent.trigger(gmi.gmap2, 'bbinfowindowopen');
    }
  };
  
  var switchState = function(toState, c) {
    var id = '#'+ gmi.getContainer()[0].id;
    if (toState == 'min') {
      $('.gmaps-bbinfowindow-minimize', c).hide();
      $('.gmaps-bbinfowindow-maximize', c).show();
      $(id +'-bbinfowindow-mincontent', c).show();
      $(id +'-bbinfowindow-maxcontent', c).hide();
    }
    else if (toState == 'max') {
      $('.gmaps-bbinfowindow-minimize', c).show();
      $('.gmaps-bbinfowindow-maximize', c).hide();
      $(id +'-bbinfowindow-mincontent', c).hide();
      $(id +'-bbinfowindow-maxcontent', c).show();
    }
  };
  
  var addStateListeners = function(c) {
    $('.gmaps-bbinfowindow-minimize', c).click(function() {
      switchState('min', c);
    });
    $('.gmaps-bbinfowindow-maximize', c).click(function() {
      switchState('max', c);
    });
  };
  
  this.openInfoWindow = function(latlng, content, iwOpts) {
    var currentOpts = $.extend(true, {}, opts, iwOpts ? iwOpts : {});
    showContent(content, currentOpts);
  };
  
  this.openMarkerInfoWindow = function(marker, content) {
    var currentOpts;
    if (marker.gmaps.options.iw_data && marker.gmaps.options.iw_data[marker.gmaps.options.basic.info_window]) {
      currentOpts = $.extend(true, {}, opts, parseOpts(marker.gmaps.options.iw_data[marker.gmaps.options.basic.info_window]));
    }
    else {
      currentOpts = $.extend(true, {}, opts);
    }
    showContent(content, currentOpts);
  };
  
  initialize();
};

/**
 * Reference implementation of interface "InfoWindowHandler"
 * for Extended info window
 */
GMapsInfoWindowHandlerExtended = function(gmi) {
  var self = this, opts;
  
  var parseOpts = function(gmapsOpts) {
    var o = $.extend(true, {}, gmapsOpts);
    o.collapsible = parseInt(o.collapsible, 10);
    o.collapsed = parseInt(o.collapsed, 10);
    o.beakOffset = parseInt(o.beak_offset, 10);
    delete o.beak_offset;
    if (o.padding) {
      o.paddingX = parseInt(o.padding.x, 10);
      o.paddingY = parseInt(o.padding.y, 10);
      delete o.padding;
    }
    if (o.max_panning != null) {
      o.maxPanning = parseInt(o.max_panning, 10);
      delete o.max_panning;
    }
    if (o.nocloseonclick != null) {
      o.noCloseOnClick = parseInt(o.nocloseonclick, 10) ? true : false;
      delete o.nocloseonclick;
    }
    return o;
  };
  
  var initialize = function() {
    opts = parseOpts(gmi.getOptions().base.iw_data.extended);
    
    GEvent.addListener(gmi.gmap2, 'extinfowindowopen', function() {
      var iw = gmi.gmap2.getExtInfoWindow();
      var cssClass = opts['class'] ? opts['class'] : 'gmaps-extinfowindow';
      $('#'+ iw.container_.id).addClass(cssClass);
      iw.container_.style.width = '';
      var containerWidth  = iw.getStyle_(document.getElementById(iw.container_.id), 'width');
      iw.container_.style.width = (containerWidth == null ? iw.defaultStyles.containerWidth : containerWidth);
      iw.contentWidth = iw.getDimensions_(iw.container_).width;
      iw.contentDiv_.style.width = iw.contentWidth + 'px';
      $(iw.contentDiv_).addClass(cssClass + '-contents');
      
      for (var i in iw.wrapperParts ) {
        var tempElement = document.createElement('div');
        tempElement.id = 'gmaps_'+ iw.infoWindowId_ + '_' + i;
        tempElement.style.visibility = 'hidden';
        $(tempElement).addClass(cssClass + '-' + i);
        document.body.appendChild(tempElement);
        tempElement = document.getElementById('gmaps_'+ iw.infoWindowId_ + '_' + i);
        var tempWrapperPart = iw.wrapperParts[i];    
        tempWrapperPart.w = parseInt(iw.getStyle_(tempElement, 'width'), 10);
        tempWrapperPart.h = parseInt(iw.getStyle_(tempElement, 'height'), 10);
        document.body.removeChild(tempElement);
      }
      
      for (var i in iw.wrapperParts) {
        var wrapperPartsDiv = iw.wrapperParts[i].domElement;
        $(wrapperPartsDiv).addClass(cssClass +'-'+ i);
        iw.wrapperParts[i].domElement = wrapperPartsDiv;
      }
      
      var trigger = iw.triggerWindowOpenEvent;
      iw.triggerWindowOpenEvent = false;
      iw.redraw(true);
      iw.redraw(true);
      iw.triggerWindowOpenEvent = trigger;
    });
  };
  
  var showContent = function(content, currentOpts, marker, ll) {
    var minContent, maxTitle, maxContent, tabs, hasMin, hasMax;
    currentOpts.tabs_state = currentOpts.tabs_state == null ? 'max' : currentOpts.tabs_state;
    
    hasMin = typeof(content.min) != 'undefined' && content.min !== null && content.min.length;
    hasMax = typeof(content.max) != 'undefined' && content.max !== null && content.max.length;
    
    if (!hasMin && hasMax) {
      content.min = content.max;
      currentOpts.tabs_state = 'min';
      delete content.max;
    }
    
    if (typeof(content.tabs) != 'undefined') {
      if (currentOpts.style == 'plain') {
        tabs = Drupal.gmaps.map.renderTabsPlain(content.tabs);
      }
      else if (currentOpts.style == 'list') {
        tabs = Drupal.gmaps.map.renderTabsList(content.tabs);
      }
      else if (currentOpts.style == 'grid') {
        tabs = Drupal.gmaps.map.renderTabsList(content.tabs, currentOpts);
      }
      else if (currentOpts.style == 'box') {
        tabs = Drupal.gmaps.map.renderTabsBox(content.tabs);
      }
      else if (currentOpts.style == 'fieldset') {
        tabs = Drupal.gmaps.map.renderTabsFieldset(content.tabs, currentOpts);
      }
      else if (currentOpts.style == 'accordion') {
        tabs = Drupal.gmaps.map.renderTabsAccordion(content.tabs, currentOpts);
      }
      else if (currentOpts.style == 'tabs') {
        tabs = Drupal.gmaps.map.renderTabsTabs(content.tabs, currentOpts);
      }
      
      if (tabs) {
        currentOpts.tabs = true;
      }
    }
    
    if (hasMin) {
      minContent = Drupal.theme('gmapsInfoWindowContent', content.title, content.min);
      if (tabs && currentOpts.tabs_state == 'min') {
        minContent += tabs;
      }
    }
    
    if (hasMax) {
      maxTitle = currentOpts.maxTitle || content.title;
      maxContent = Drupal.theme('gmapsInfoWindowContent', maxTitle, content.max);
      if (tabs && currentOpts.tabs_state == 'max') {
        maxContent += tabs;
      }
      currentOpts.maxContent = maxContent;
    }
    
    if (minContent) {
      if (gmi.gmap2.ClickListener_ != null) {
        GEvent.removeListener(gmi.gmap2.ClickListener_);
      }
      if (ll) {
        gmi.gmap2.openExtInfoWindow(marker, currentOpts.cssId, '', currentOpts);
      }
      else {
        marker.openExtInfoWindow(gmi.gmap2, currentOpts.cssId, '', currentOpts);
      }
      
      var iw = gmi.gmap2.getExtInfoWindow();
      if (iw) {
        iw.ajaxUrl_ = minContent;
        
        iw.ajaxRequest_ = function(content) {
          content = content || iw.ajaxUrl_;
          var thisMap = iw.map_;
          var infoWindow = document.getElementById(iw.infoWindowId_ + '_contents');
          var curentState = iw.isMaximized_ ? 'min' : 'max';
          
          var currentContent = $('<div/>').html(content)[0];

          $(infoWindow).empty().append(currentContent);

          Drupal.attachBehaviors(currentContent);
          if (tabs && currentOpts.tabs_state == curentState) {
            addContentListeners(currentContent, currentOpts);
          }

          iw.redraw(true);
          iw.resize();
          GEvent.trigger(thisMap, 'extinfowindowupdate');
        };
        
        iw.ajaxRequest_(iw.ajaxUrl_);
      }
    }
  };
  
  var addContentListeners = function(c, currentOpts) {
    if (currentOpts.style == 'fieldset' && currentOpts.collapsible) {
      $('fieldset.collapsible > legend a', c).click(function() {
        setTimeout(function() {
          gmi.gmap2.getExtInfoWindow().resize();
          gmi.gmap2.getExtInfoWindow().redraw(true);
        },200);
      });
    }
    else if (currentOpts.style == 'accordion') {
      $('.gmaps-accordion', c).bind('accordionchange', function() {
        gmi.gmap2.getExtInfoWindow().resize();
        gmi.gmap2.getExtInfoWindow().redraw(true);
      });
    }
    else if (currentOpts.style == 'tabs') {
      $('.gmaps-tabs', c)
        .bind('tabsshow', function() {
          gmi.gmap2.getExtInfoWindow().resize();
          gmi.gmap2.getExtInfoWindow().redraw(true);
        })
        .bind('tabsselect', function(e, ui) {
          if (!$(ui.panel).hasClass('ui-tabs-hide')) {
            setTimeout(function() {
              gmi.gmap2.getExtInfoWindow().resize();
              gmi.gmap2.getExtInfoWindow().redraw(true);
            }, 200);
          }
        });
    }
  };
  
  this.openInfoWindow = function(latlng, content, iwOpts) {
    var currentOpts = $.extend(true, {}, opts, iwOpts ? iwOpts : {});
    currentOpts.cssId = currentOpts.cssId || gmi.getOptions().id +'-extinfowindow';
    showContent(content, currentOpts, latlng, true);
  };
  
  this.openMarkerInfoWindow = function(marker, content) {
    var currentOpts;
    if (marker.gmaps.options.iw_data && marker.gmaps.options.iw_data[marker.gmaps.options.basic.info_window]) {
      currentOpts = $.extend(true, {}, opts, parseOpts(marker.gmaps.options.iw_data[marker.gmaps.options.basic.info_window]));
    }
    else {
      currentOpts = $.extend(true, {}, opts);
    }
    currentOpts.cssId = currentOpts.cssId || gmi.getOptions().id +'-'+ marker.gmaps.options.id +'-extinfowindow';
    showContent(content, currentOpts, marker);
  };
  
  initialize();
};

/**
 * Reference implementation of interface "InfoWindowHandler"
 * for Tabbed Max Content info window
 */
GMapsInfoWindowHandlerTabbedMax = function(gmi) {
  var self = this;
  var opts = {};
  
  var createEl = function (tag, attrs, content, style, parent) {
    var node = content;
    if (!content || (content && typeof content === 'string')) {
      node = document.createElement(tag);
      node.innerHTML = content || ''; 
    }
    if (style) {
      $.extend(true, node.style, style);
    }
    if (attrs) {
      $.extend(true, node, attrs);
    }
    if (parent) {
      parent.appendChild(node);
    }
    return node;
  };
  
  var overwriteTabbedMaxContent = function(tmc) {
    if (tmc.gmapsOverwritten) return;
    tmc.gmapsOverwritten = true;
    
    var callback = function(obj, method, arg){
      return function() {method.call(obj, arg)};
    };
    tmc.onMaximizeClick_ = function () {
      for (var i = 0, ct = this.tabs_.length; i < ct; i++) {
        if (this.tabs_[i].navNode_.clickListener_ == null) {
          this.tabs_[i].navNode_.clickListener_ = callback(tmc, tmc.selectTab, i);
          $(this.tabs_[i].navNode_).click(this.tabs_[i].navNode_.clickListener_);
        }
      }
    };

    tmc.initialize_ = function (sumNode, tabs, opt_maxOptions) {
      GEvent.clearListeners(this.infoWindow_, 'maximizeclick');
      GEvent.clearListeners(this.infoWindow_, 'restoreclick');
      GEvent.bind(this.infoWindow_, 'maximizeclick', this, this.onMaximizeClick_);
      this.tabs_ = tabs;
      this.selectedTab_ = -1;

      opt_maxOptions = opt_maxOptions || {};
      var selectedTab = opt_maxOptions.selectedTab || 0;
      this.cssClass = opt_maxOptions['class'] || 'gmaps-tmcinfowindow';
      var cssId = opt_maxOptions.cssId || 'gmaps-tmc-maxcontent';

      if (this.maxNode_) {
        GEvent.clearNode(this.maxNode_);
        this.maxNode_.innerHTML = '';
      } else {
        this.maxNode_ = createEl('div');
      }
      this.maxNode_.id = cssId;
      $(this.maxNode_).addClass(this.cssClass);
      
      this.summaryNode_ = createEl('div', null, sumNode, null, this.maxNode_);
      $(this.summaryNode_).addClass(this.cssClass +'-summary');
      
      this.navsNode_ = createEl('div', null, null, null, this.maxNode_);
      $(this.navsNode_).addClass(this.cssClass +'-tabbar');
      
      this.contentsNode_ = createEl('div', null, null, null, this.maxNode_);
      var left, node, right;
      if (tabs && tabs.length) {
        // left
        left = createEl('span', null, null, null, this.navsNode_);
        $(left).addClass(this.cssClass +'-tableft');
        for (var i = 0, ct = tabs.length; i < ct; i++) {
          if (i === selectedTab || tabs[i].getLabel() === selectedTab) {
            this.selectedTab_ = i;
          }
          tabs[i].navNode_ = createEl('span', null, tabs[i].getLabel(), this.style_.tabOff, this.navsNode_);//);
          $(tabs[i].navNode_).addClass(this.cssClass +'-taboff');
          node = createEl('div', null, tabs[i].getContentNode(), null, this.contentsNode_);
          $(node).addClass(this.cssClass +'-content');
          node.style.display = 'none';
        }
        // right
        right = createEl('span', null, null, null, this.navsNode_);
        $(right).addClass(this.cssClass +'-tabright');
      }
    };
    
    tmc.selectTab = function (identifier) {
      var trigger = false;
      var hasVisibleTab = false;
      var tab;
      for (var i = 0, ct = this.tabs_.length; i < ct; i++) {
        tab = this.tabs_[i];
        if (i === identifier || tab.getLabel() === identifier) {
          if (tab.getContentNode().style.display === 'none') {
            $(tab.navNode_).addClass(this.cssClass +'-tabon');
            tab.getContentNode().style.display = 'block';
            this.selectedTab_ = i;  
            trigger = true;
          }
          hasVisibleTab = true; 
        } else {
          $(tab.navNode_).removeClass(this.cssClass +'-tabon');
          tab.getContentNode().style.display = 'none';
        }
      }
      // avoid excessive event if clicked on a selected tab.
      if (trigger) {
        /**
         * This event is fired after a tab is selected,
         * passing the selected {@link MaxContentTab} into the callback.
         * @name TabbedMaxContent#selecttab
         * @param {MaxContentTab} selected tab
         * @event
         */
        GEvent.trigger(this, 'selecttab', this.tabs_[this.selectedTab_]);
      }
      if (!hasVisibleTab) {
        this.selectTab(0);
      }
    };
    
    tmc.checkResize = function () {};
  };
  
  
  var parseOpts = function(gmapsOpts) {
    var o = {};
    o.maxWidth = parseInt(gmapsOpts.maxwidth, 10);
    o.noCloseOnClick = parseInt(gmapsOpts.nocloseonclick, 10);
    o.pixelOffset = new GSize(parseInt(gmapsOpts.offset.x, 10), parseInt(gmapsOpts.offset.y, 10));
    o.maximized = parseInt(gmapsOpts.maximized, 10);
    o.maximized = parseInt(gmapsOpts.maximized, 10);
    o['class'] = gmapsOpts['class'];
    return o;
  };
  
  var initialize = function() {
    opts = parseOpts(gmi.getOptions().base.iw_data.tmc);
  };
  
  var prepareContent = function(content, currentOpts, c) {
    if (typeof(content.min) != 'undefined' && content.min !== null && content.min.length) {
      c.minContent = $('<div/>').html(Drupal.theme('gmapsInfoWindowContent', content.title, content.min))[0];
      Drupal.attachBehaviors(c.minContent);
    }
    
    if (typeof(content.max) != 'undefined' && content.max !== null && content.max.length) {
      c.maxContent = $('<div/>').html(content.max)[0];
      Drupal.attachBehaviors(c.maxContent);
    }
    if (!currentOpts.maxTitle && content.title) {
      currentOpts.maxTitle = content.title;
    }
    
    if (typeof(content.tabs) != 'undefined') {
      $.each(content.tabs, function(label, tabContent) {
        tabContent = $('<div/>').html(tabContent)[0];
        Drupal.attachBehaviors(tabContent);
        c.tabs.push(c.minContent ? new MaxContentTab(label, tabContent) : new GInfoWindowTab(label, tabContent));
      });
    }
  };
  
  var maximize = function(currentOpts) {
    if (currentOpts.maxContent && currentOpts.maximized) {
      var iw = gmi.gmap2.getInfoWindow();
      var m = GEvent.addListener(gmi.gmap2, 'infowindowopen', function () {
        GEvent.removeListener(m);
        iw.maximize();
      });
    }
  };
  
  this.openInfoWindow = function(latlng, content, iwOpts) {
    var currentOpts = $.extend(true, {}, opts, iwOpts ? iwOpts : {});
    var c = {minContent: null, maxContent: null, tabs: []};

    prepareContent(content, currentOpts, c);
    
    if (c.tabs.length) {
      if (c.minContent) {
        overwriteTabbedMaxContent(gmi.gmap2.getTabbedMaxContent());
        currentOpts.cssId = currentOpts.cssId || gmi.getOptions().id +'-tmcinfowindow';
        gmi.gmap2.openMaxContentTabs(latlng, c.minContent, c.maxContent, c.tabs, currentOpts);
      }
      else {
        if (c.maxContent) {
          currentOpts.maxContent = c.maxContent;
        }
        gmi.gmap2.openInfoWindowTabs(latlng, c.tabs, currentOpts);
      }
    }
    else if (c.maxContent) {
      if (c.minContent) {
        currentOpts.maxContent = c.maxContent;
        gmi.gmap2.openInfoWindow(latlng, c.minContent, currentOpts);
      }
      else {
        delete currentOpts.maxTitle;
        gmi.gmap2.openInfoWindow(latlng, c.maxContent, currentOpts);
      }
    }
    else {
      delete currentOpts.maxTitle;
      gmi.gmap2.openInfoWindow(latlng, c.minContent, currentOpts);
    }
    maximize(currentOpts);
  };
  
  this.openMarkerInfoWindow = function(marker, content) {
    var currentOpts;
    if (marker.gmaps.options.iw_data && marker.gmaps.options.iw_data[marker.gmaps.options.basic.info_window]) {
      currentOpts = $.extend(true, {}, opts, parseOpts(marker.gmaps.options.iw_data[marker.gmaps.options.basic.info_window]));
    }
    else {
      currentOpts = $.extend(true, {}, opts);
    }
    var c = {minContent: null, maxContent: null, tabs: []};

    prepareContent(content, currentOpts, c);
    
    if (c.tabs.length) {
      if (c.minContent) {
        overwriteTabbedMaxContent(gmi.gmap2.getTabbedMaxContent());
        currentOpts.cssId = currentOpts.cssId || gmi.getOptions().id +'-'+ marker.gmaps.options.id +'-tmcinfowindow';
        marker.openMaxContentTabs(gmi.gmap2, c.minContent, c.maxContent, c.tabs, currentOpts);
      }
      else {
        if (c.maxContent) {
          currentOpts.maxContent = c.maxContent;
        }
        marker.openInfoWindowTabs(c.tabs, currentOpts);
      }
    }
    else if (c.maxContent) {
      if (c.minContent) {
        currentOpts.maxContent = c.maxContent;
        marker.openInfoWindow(c.minContent, currentOpts);
      }
      else {
        delete currentOpts.maxTitle;
        marker.openInfoWindow(c.maxContent, currentOpts);
      }
    }
    else {
      delete currentOpts.maxTitle;
      marker.openInfoWindow(c.minContent, currentOpts);
    }
    maximize(currentOpts);
  };
  
  initialize();
};

Drupal.gmaps.map = Drupal.gmaps.map || new (function() {
  var self = this, svuClient, loadedContents = {};
  this.maps = {};
  
  this.hooks = {
    'maptype': {},
    'method': {
      'adsmanager': ['disableAdsManager', 'enableAdsManager'],
      'auto_center_zoom': [false, 'enableAutoCenterZoom'],
      'continuouszoom': ['disableContinuousZoom', 'enableContinuousZoom'],
      'dblclickzoom': ['disableDoubleClickZoom', 'enableDoubleClickZoom'],
      'dragging': ['disableDragging', 'enableDragging'],
      'googlebar': ['disableGoogleBar', 'enableGoogleBar'],
      'keyboardhandler': [false, 'enableKeyboardHandler'],
      'layers': ['disableLayers', 'enableLayers'],
      'resize': [false, 'enableResize'],
      'rotation': ['disableRotation', 'enableRotation'],
      'scrollwheelzoom': ['disableScrollWheelZoom', 'enableScrollWheelZoom'],
      'streetview': ['disableStreetView', 'enableStreetView'],
      'traffic': ['disableTraffic', 'enableTraffic'],
      'infowindow': ['disableInfoWindow', 'enableInfoWindow'],
      'keydragzoom': ['disableGMapsKeyDragZoom', 'enableGMapsKeyDragZoom']
    },
    'control': {},
    'info_window': {
      'google': GMapsInfoWindowHandlerGoogle,
      'bb': GMapsInfoWindowHandlerBulletinBoard,
      'extended': GMapsInfoWindowHandlerExtended,
      'tmc': GMapsInfoWindowHandlerTabbedMax
    },
    'overlay': {}
  };
  
  this.hooks.maptype.normal = new GMapsMapTypeHandler();
  this.hooks.maptype = {
    'normal': this.hooks.maptype.normal,
    'satellite': this.hooks.maptype.normal,
    'hybrid': this.hooks.maptype.normal,
    'physical': this.hooks.maptype.normal,
    'satellite_3D': this.hooks.maptype.normal,
    'aerial': this.hooks.maptype.normal,
    'aerial_hybrid': this.hooks.maptype.normal,
    'mapmaker_normal': this.hooks.maptype.normal,
    'mapmaker_hybrid': this.hooks.maptype.normal,
    'moon_elevation': this.hooks.maptype.normal,
    'moon_visible': this.hooks.maptype.normal,
    'mars_elevation': this.hooks.maptype.normal,
    'mars_visible': this.hooks.maptype.normal,
    'mars_infrared': this.hooks.maptype.normal,
    'sky_visible': this.hooks.maptype.normal
  };
  
  this.hooks.control.smallzoom = new GMapsControlHandler();
  this.hooks.control = {
    'smallzoom': this.hooks.control.smallzoom,
    'smallmap': this.hooks.control.smallzoom,
    'largemap': this.hooks.control.smallzoom,
    'smallzoom3D': this.hooks.control.smallzoom,
    'largemap3D': this.hooks.control.smallzoom,
    'extnav': this.hooks.control.smallzoom,
    'scale': this.hooks.control.smallzoom,
    'maptype': this.hooks.control.smallzoom,
    'menumaptype': this.hooks.control.smallzoom,
    'hierarchical_maptype': this.hooks.control.smallzoom,
    'extmaptype': this.hooks.control.smallzoom,
    'overview': this.hooks.control.smallzoom,
    'extdragzoom': this.hooks.control.smallzoom,
    'breadcrumb': this.hooks.control.smallzoom
  };
  
  this.behaviors = {};

  this.getMap = function(id, context, lazy, refresh) {
    if (self.maps[id]) {
      if (refresh) {
        self.maps[id] = null;
      }
      else {
        return self.maps[id];
      }
    }
    
    if (GBrowserIsCompatible()) {
      context = context || document;
      var element = $('#'+ id +':not(.gmaps-map-item-processed)', context);
      if (element.length) {
        element = $(element[0]);
        element.addClass('gmaps-map-item-processed');
        self.maps[id] = new GMapsMapItem(element, null, lazy);
      }
    }
    return self.maps[id];
  };
  
  this.setGoogleBarOptions = function(gmi, mapOpts) {
    var opts = gmi.getOptions();
    if (opts.base.method_data && opts.base.method_data.googlebar) {
      var gb = opts.base.method_data.googlebar; 
    }
    else {
      return;
    }
    mapOpts.googleBarOptions = {};
    var gbOpts = mapOpts.googleBarOptions;
    
    gbOpts.showOnLoad = parseInt(gb.showonload) ? true : false;
    
    gbOpts.style = "old";
    //disabled, because bogus
    /*if (parseInt(gb.newstyle)) {
      gbOpts.style = "new";
    }*/
    
    if (gb.ads && gb.ads.client && gb.ads.client.length) {
      gbOpts.adsOptions = {};
      gbOpts.adsOptions.client = gb.client;
      gbOpts.adsOptions.channel = gb.channel;
      gbOpts.adsOptions.adsafe = gb.safety;
    }
    
    gbOpts.linkTarget = gb.link_target;
    gbOpts.listingTypes = gb.listing_types;
    gbOpts.resultList = gb.result_list == 'bb' ? gmi.getBulletinBoard()[0] : gb.result_list;
    gbOpts.suppressInitialResultSelection = parseInt(gb.suppress_selection) ? true : false;
    gbOpts.suppressZoomToBounds = parseInt(gb.suppress_zoom) ? true : false;
  };
  
  this.createThrobber = function(gmi) {
    var markerOpts = {
      'icon': Drupal.gmaps.icon.getIcon(gmi.getOptions().base.map_data.throbber),
      'clickable': false,
      'draggable': false
    };
    return new GMarker(gmi.gmap2.getCenter(), markerOpts);
  };
  
  this.attachBehaviors = function(gmi) {
    if (gmi) {
      $.each(self.behaviors, function() {
        this(gmi);
      });
    }
  };
  
  this.getStreetviewClient = function() {
    if (!svuClient) {
      svuClient = new GStreetviewClient();
    }
    
    return svuClient;
  };
  
  this.loadContent = function(content, callback, gmi, latlng) {
    if (typeof(content.ajax) == 'undefined' || content.ajax === null || typeof(content.ajax.url) == 'undefined' || content.ajax.url === null || !content.ajax.url.length) {
      delete content.url;
      callback(content);
      return;
    }
    
    var cid = $.md5(content.ajax.url + (content.ajax.data ? (content.ajax.url.match(/\?/) ? "&" : "?") + $.param(content.ajax.data) : ''));
    if (loadedContents[cid]) {
      callback(loadedContents[cid]);
      return;
    }
    
    if (gmi) {
      var ll = latlng || gmi.gmap2.getCenter();
      gmi.showThrobber(ll);
    }
    
    var ajax = {
      type: "POST",
      url: content.ajax.url,
      data: content.ajax.data,
      success: function (response) {
        if (typeof(response.status) != 'undefined' && response.status == 0) {
          if (typeof(response.data) != 'undefined') {
            callback({'title': 'Internal server error', 'min': response.data});
          }
        }
        else {
          //avoid infinite loops
          delete response.data.ajax;
          loadedContents[cid] = response.data;
          callback(loadedContents[cid]);
        }
        if (gmi) {
          gmi.hideThrobber();
        }
      },
      error: function (xmlhttp) {
        callback({'title': 'AJAX/HTTP error', 'min': Drupal.ahahError(xmlhttp, content.ajax.url)});
        if (gmi) {
          gmi.hideThrobber();
        }
      }
    };
    
    Drupal.gmaps.loadAjaxContent(ajax);
  };
  
  this.renderTabsPlain = function(tabs) {
    var output = '';
    $.each(tabs, function(title, content) {
      output += content;
    });
    return '<div class="gmaps-info-window-tabs gmaps-info-window-tabs-box">'+ output +'</div>';
  };
  
  this.renderTabsList = function(tabs) {
    var items = [];
    $.each(tabs, function(title, content) {
      items.push({data: content, title: title, alt: title});
    });
    return items.length ? '<div class="gmaps-info-window-tabs gmaps-info-window-tabs-box">'+ Drupal.theme('itemList', items) +'</div>' : '';
  };
  
  this.renderTabsGrid = function(tabs, opts) {
    var items = [];
    $.each(tabs, function(title, content) {
      items.push({data: content, title: title, alt: title});
    });
    return items.length ? '<div class="gmaps-info-window-tabs gmaps-info-window-tabs-box">'+ Drupal.theme('gmapsGrid', items, opts.grid) +'</div>' : '';
  };
  
  this.renderTabsBox = function(tabs) {
    var output = '';
    $.each(tabs, function(title, content) {
      output += Drupal.theme('box', title, content);
    });
    return '<div class="gmaps-info-window-tabs gmaps-info-window-tabs-box">'+ output +'</div>';
  };
  
  this.renderTabsFieldset = function(tabs, opts) {
    var output = '';
    $.each(tabs, function(title, content) {
      var fs = {
        '#type': 'fieldset',
        '#title': title,
        '#value': content,
        '#collapsible': opts.collapsible,
        '#collapsed': opts.collapsed
      };
      output += Drupal.render(fs);
    });
    return '<div class="gmaps-info-window-tabs gmaps-info-window-tabs-fieldset">'+ output +'</div>';
  };
  
  this.renderTabsAccordion = function(tabs, opts) {
    var accordion = {
      '#type': 'gmaps_accordion',
      '#collapsible': opts.collapsible,
      '#collapsed': opts.collapsed,
      '#attributes': {'class': 'gmaps-info-window-tabs gmaps-info-window-tabs-accordion'}
    };
    var i = 0;
    $.each(tabs, function(title, content) {
      accordion[i] = {
        '#type': 'gmaps_accordion_panel',
        '#title': title,
        '#value': content
      };
      i++;
    });
    return i > 0 ? Drupal.render(accordion) : '';
  };
  
  this.renderTabsTabs = function(tabs, opts) {
    var gmapsTabs = {
      '#type': 'gmaps_tabs',
      '#collapsible': opts.collapsible,
      '#collapsed': opts.collapsed,
      '#nav_position': opts.tabs_nav,
      '#attributes': {'class': 'gmaps-info-window-tabs gmaps-info-window-tabs-tabs'}
    };
    var i = 0;
    $.each(tabs, function(title, content) {
      gmapsTabs[i] = {
        '#type': 'gmaps_tabs_panel',
        '#title': title,
        '#value': content
      };
      i++;
    });
    return i > 0 ? Drupal.render(gmapsTabs) : '';
  };

  this.getOverlayBounds = function(ov, boundsOnly) {
    var bounds, ll, sw, ne, iconSize;
    if (ov.gmaps && ov.gmaps.point) {
      if (ov.gmaps.point.bounds && (sw = ov.gmaps.point.bounds.southwest) && (ne = ov.gmaps.point.bounds.northeast)) {
        if (sw.latitude && sw.longitude && ne.latitude && ne.longitude) {
          bounds = new GLatLngBounds(new GLatLng(sw.latitude, sw.longitude), new GLatLng(ne.latitude, ne.longitude));
        }
      }
      if (!bounds && !boundsOnly) {
        ll = new GLatLng(ov.gmaps.point.latitude, ov.gmaps.point.longitude);
      }
    }
    else if (ov.getLatLng && !boundsOnly) {
      iconSize = ov.getIcon ? ov.getIcon().iconSize : {width: 0, height: 0}
      if (iconSize.width != 0 && iconSize.height != 0 && (!ov.isHidden || !ov.isHidden())) {
        ll = ov.getLatLng();
      }
    }
    
    if (ll) {
      bounds = new GLatLngBounds(new GLatLng(ll.lat() - GMAPS_MAP_DEFAULT_BOUNDS_SPAN, ll.lng() - GMAPS_MAP_DEFAULT_BOUNDS_SPAN), new GLatLng(ll.lat() + GMAPS_MAP_DEFAULT_BOUNDS_SPAN, ll.lng() + GMAPS_MAP_DEFAULT_BOUNDS_SPAN));
    }
    
    return bounds;
  };
  
  //GUnload();
  $(document).unload(function(){GUnload();});
})();

GMapsMapItem = function(container, opts, lazyInit) {
  var self = this;
  opts = opts || Drupal.settings.gmaps.map[container[0].id];
  lazyInit = lazyInit != null ? lazyInit : false;
  
  var bb, i, maptype, throbber, progressbar, initialized = false, svu;
  
  this.gmaps = {};
  this.gmap2 = null;
  this.maptypes = {};
  this.controls = {};
  this.iwHandlers = {};
  this.overlays = {};
  
  this.getOptions = function(){
    return opts;
  };
  
  this.getContainer = function(){
    return container;
  };
  
  this.isInitialized = function(){
    return initialized;
  };
  
  this.getBulletinBoard = function() {
    if (bb == null) {
      bb = $('.gmaps-map-bb:eq(0)', container).hide();
    }
    return bb;
  };
  
  this.bulletinBoardShow = function(content) {
    if (!bb) {
      self.getBulletinBoard();
    }
    if (bb) {
      var c;
      if (content.constructor == 'String') {
        c = $('<div/>').html(content).children();
      }
      else {
        c = $(content).clone();
      }
      bb.hide().empty().append(c);
      bb.show();
      Drupal.attachBehaviors(c);
      $(c).before('<div class="gmaps-map-bb-close"></div>');
      $('.gmaps-map-bb-close', bb).click(function() {self.bulletinBoardHide();});
    }
  };
  
  this.bulletinBoardHide = function() {
    if (bb) {
      bb.html('').hide();
    }
  };
  
  this.getSVU = function(initOpts) {
    if (svu == null && opts.base.type == GMAPS_MAP_EARTH && opts.base.map_data.svu && parseInt(opts.base.map_data.svu.enabled)) {
      svu = new GMapsStreetviewItem(self, initOpts);
    }
    return svu;
  };
  
  this.showThrobber = function(p) {
    if (!throbber) {
      throbber = Drupal.gmaps.map.createThrobber(self);
    }
    if (throbber) {
      if (p instanceof GLatLng) {
        throbber.setLatLng(p);
      }
      else if (p instanceof GLatLngBounds) {
        throbber.setLatLng(p.getCenter());
      }
      else {
        throbber.setLatLng(new GLatLng(p.latitude, p.longitude));
      }
      this.gmap2.addOverlay(throbber);
    }
  };
  
  this.hideThrobber = function() {
    if (throbber) {
      this.gmap2.removeOverlay(throbber);
    }
  };
  
  var createProgressbar = function() {
    if (self.gmap2 && opts.base.map_data.progressbar && parseInt(opts.base.map_data.progressbar.enabled)) {
      var pbOpts = {'loadstring': opts.base.map_data.progressbar.loadstring, 'width': parseInt(opts.base.map_data.progressbar.width)};
      progressbar = new ProgressbarControl(self.gmap2, pbOpts);
    }
  }
  
  this.startProgress = function(ops) {
    if (!progressbar) {
      createProgressbar();
    }
    if (progressbar) {
      progressbar.start(ops);
    }
  };
  
  this.updateProgress = function(step) {
    if (progressbar) {
      progressbar.updateLoader(step);
    }
  };
  
  this.stopProgress = function() {
    if (progressbar) {
      progressbar.remove();
    }
  };
  
  this.openInfoWindow = function(type, latlng, content, iwOpts) {
    self.bulletinBoardHide();
    if (self.gmap2.infoWindowEnabled() && typeof(self.iwHandlers[type]) != 'undefined') {
      if (content.ajax != null && content.ajax.url != null && content.ajax.url.length) {
        var mapOpts = $.extend(true, {}, opts);
        delete mapOpts.overlays;
        var data = $.extend(true, {'info_window': type, 'gmi': mapOpts}, content.ajax.data ? content.ajax.data : {});
        content.ajax.data = Drupal.gmaps.flatten(data);
        Drupal.gmaps.map.loadContent(content, function(c){content = c; self.iwHandlers[type].openInfoWindow(latlng, c, iwOpts);}, self);
      }
      else {
        self.iwHandlers[type].openInfoWindow(latlng, content, iwOpts);
      }
    }
  };
  
  this.addControl = function(id, options) {
    if (options.control.length && Drupal.gmaps.map.hooks.control[options.control]) {
      var control = Drupal.gmaps.map.hooks.control[options.control].createControl(self, options.control);
      if (control) {
        var ctrlPosition = control.getDefaultPosition();
        var anchor = typeof(options.position) != 'undefined' ? parseInt(options.position.anchor, 10) : GMAPS_CONTROL_POSITION_DEFAULT;
        if (anchor > GMAPS_CONTROL_POSITION_DEFAULT) {
          ctrlPosition.anchor = anchor;
          if (typeof(options.position.offset) == 'object' && typeof(options.position.offset.width) != 'undefined') {
            ctrlPosition.offset = new GSize(parseInt(options.position.offset.width, 10), parseInt(options.position.offset.height, 10));
          }
        }
        self.gmap2.addControl(control, ctrlPosition);
        self.controls[id] = control;
      }
    }
  }
  
  this.initialize = function(wereLazy) {
    if (self.gmap2) {
      return;
    }
    
    var cont = $('.gmaps-map-container', container);
    
    //GMap2 options
    var mapOpts = {'mapTypes': []};
    
    //size
    var height = parseInt(opts.base.size.height);
    height = height || Math.max(cont.height(), GMAPS_MAP_MIN_HEIGHT);
    cont.height(height);
    if (parseInt(opts.base.size.width)) {
      container.width(parseInt(opts.base.size.width));
    }
    
    $(opts.base.maptypes).each(function() {
      if (typeof(Drupal.gmaps.map.hooks.maptype[this]) != 'undefined') {
        maptype = Drupal.gmaps.map.hooks.maptype[this].createMapType(self, this);
        if (maptype) {
          mapOpts.mapTypes.push(maptype);
          self.maptypes[this] = maptype;
        }
      }
    });
    
    if (!mapOpts.mapTypes.length) {
      throw Drupal.t('No valid map types had been configured.');
    }
    
    if (opts.base.map_data.draggable_cursor) {
      mapOpts.draggableCursor = opts.base.map_data.draggable_cursor;
    }
    if (opts.base.map_data.dragging_cursor) {
      mapOpts.draggingCursor = opts.base.map_data.dragging_cursor;
    }
    if (opts.base.map_data.bgcolor) {
      mapOpts.backgroundColor = opts.base.map_data.bgcolor;
    }
    
    if (opts.base.methods && opts.base.methods.googlebar) {
      Drupal.gmaps.map.setGoogleBarOptions(self, mapOpts);
    }
    
    //The map
    self.gmap2 = new GMap2(cont[0], mapOpts);
    self.gmap2.gmaps = {'gmi': self, 'adsManager': null, 'isAutoCenterZoomEnabled': false, 'keyboardHandler': null, 'layers': {}, 'streetView': {'overlay': null, 'listener': null, 'timer': null, 'zoomListener': null}, 'traffic': null};
    
    if (typeof(self.maptypes[opts.base.default_maptype]) != 'undefined') {
      self.gmap2.setMapType(self.maptypes[opts.base.default_maptype]);
    }
    var zoom = parseInt(opts.base.zoom, 10);
    if (zoom == -1) {
      if (typeof(opts.base.center.bounds) != 'undefined') {
        zoom = self.gmap2.getBoundsZoomLevel(new GLatLngBounds(new GLatLng(opts.base.center.bounds.southwest.latitude, opts.base.center.bounds.southwest.longitude), new GLatLng(opts.base.center.bounds.northeast.latitude, opts.base.center.bounds.northeast.longitude)));
      }
      else {
        zoom = GMAPS_MAP_DEFAULT_ZOOM;
      }
    }
    self.gmap2.setCenter(new GLatLng(opts.base.center.latitude, opts.base.center.longitude), zoom);
    
    //non-lazy init
    if (!wereLazy) {
      var handler;
      if (handler = Drupal.gmaps.getLazyInitHandler('#'+ container[0].id)) {
        handler.attach('#'+ container[0].id, function() {
          var center = self.gmap2.getCenter();
          self.gmap2.checkResize();
          self.gmap2.setCenter(center);
          //initCenter(self.gmap2);
        });
      }
    }

    //Methods
    if (opts.base.methods) {
      $.each(Drupal.gmaps.map.hooks.method, function(index, callbacks){
        if (opts.base.methods.constructor == Array) {
          index = $.inArray(index, opts.base.methods);
        }
        var cb = opts.base.methods[index] ? callbacks[1] : callbacks[0];
        if (cb && self.gmap2[cb]) {
          self.gmap2[cb]();
        }
      });
    }
    
    //Controls
    if (opts.base.controls) {
      $.each(opts.base.controls, function(index, ct) {
        self.addControl(index, ct)
      });
    }
    
    //Info windows
    if (opts.info_windows) {
      for (var i in opts.info_windows) {
        if (typeof(Drupal.gmaps.map.hooks.info_window[i]) != 'undefined') {
          self.iwHandlers[i] = new (Drupal.gmaps.map.hooks.info_window[i])(self);
        }
      }
    }
    
    //Overlays
    if (opts.overlays) {
      var ovHandler, overlays;
      $.each(opts.overlays, function(type, content) {
        if (ovHandler = Drupal.gmaps.map.hooks.overlay[type]) {
          ovHandler.addContent(self, content);
        }
      });
    }
    
    //TOC map
    if (opts.base.map_data.toc_map && parseInt(opts.base.map_data.toc_map.enabled, 10)) {
      var toc_style = opts.base.map_data.toc_map.style;
      if (toc_style == 'accordion' || toc_style == 'tabs') {
        var toc_gmi = $.extend(true, {}, opts);
        delete toc_gmi.overlays;
        
        if (toc_style == 'tabs' && $('.form-gmaps-tabs:first', container).length) {
          var toc_id = $('.form-gmaps-tabs:first', container)[0].id;
          if (!Drupal.settings.gmaps.tabs[toc_id].ahahOptions) {
            Drupal.settings.gmaps.tabs[toc_id].ahahOptions = {};
          }
          if (!Drupal.settings.gmaps.tabs[toc_id].ahahOptions.data) {
            Drupal.settings.gmaps.tabs[toc_id].ahahOptions.data = {};
          }
          Drupal.settings.gmaps.tabs[toc_id].ahahOptions.data.gmi = toc_gmi;
          self.toc = Drupal.gmaps.tabs.getTabs(toc_id, container);
        }
        else if ($('.form-gmaps-accordion:first', container).length) {
          var toc_id = $('.form-gmaps-accordion:first', container)[0].id;
          if (!Drupal.settings.gmaps.accordion[toc_id].ahahOptions) {
            Drupal.settings.gmaps.accordion[toc_id].ahahOptions = {};
          }
          if (!Drupal.settings.gmaps.accordion[toc_id].ahahOptions.data) {
            Drupal.settings.gmaps.accordion[toc_id].ahahOptions.data = {};
          }
          Drupal.settings.gmaps.accordion[toc_id].ahahOptions.data.gmi = toc_gmi;
          self.toc = Drupal.gmaps.accordion.getAccordion(toc_id, container);
        }
      }
    }
    
    //Behaviors
    Drupal.gmaps.map.attachBehaviors(self);
    
    GEvent.trigger(self, 'initialized');
    initialized = true;
  };
  
  if (GBrowserIsCompatible()) {
    self.initialize(lazyInit);
  }

};

GMapsStreetviewItem = function(gmi, initOpts, client) {
  var self = this, staticOffset, marker, dynamicMarker, isHidden = true, tracker, flashAvailable = true;
  client = client || Drupal.gmaps.map.getStreetviewClient();
  this.wrapper = $($('.gmaps-map-svu-wrapper', gmi.getContainer())[0]);
  this.container = $($('.gmaps-map-svu', gmi.getContainer())[0]);
  this.panorama;
  
  var startDrag = function(e) {
    staticOffset = self.container.height() - e.pageY;
    self.container.css('opacity', 0.25);
    $(document).mousemove(performDrag).mouseup(endDrag);
    return false;
  };

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

  var endDrag = function(e) {
    $(document).unbind("mousemove", performDrag).unbind("mouseup", endDrag);
    self.container.css('opacity', 1);
    self.panorama.checkResize();
  };
  
  var handleError = function(errorCode) {
    if (errorCode == 603) {
      flashAvailable = false;
      self.hide();
      if (marker) {
        gmi.gmap2.removeOverlay(marker);
        if (marker.gmaps.svu.dragendListener) {
          GEvent.removeListener(marker.gmaps.svu.dragendListener);
        }
        if (marker.gmaps.svu.clickListener) {
          GEvent.removeListener(marker.gmaps.svu.clickListener);
        }
        if (marker.gmaps.svu.rightclickListener) {
          GEvent.removeListener(marker.gmaps.svu.rightclickListener);
        }
        if (tracker) {
          tracker.disable();
          delete tracker;
        }
        marker = null;
      }
      if (self.panorama) {
        self.panorama.remove();
        GEvent.removeListener(self.panorama.gmaps.errorListener);
        GEvent.removeListener(self.panorama.gmaps.initListener);
        GEvent.removeListener(self.panorama.gmaps.yawListener);
        self.panorama = null;
      }
      self.wrapper.html('');
      GEvent.trigger(self, 'gmapssvunoflash');
    }
    else if (errorCode == 600) {
      GEvent.trigger(self, 'gmapssvunosvu');
    }
  };
  
  var getYawBearing = function(yaw) {
    var compass = ['n','nne','ne','ene','e','ese','se','sse','s','ssw','sw','wsw','w','wnw','nw','nnw'];
    var SVUMAN_NUM_ICONS = 16;
    var SVUMAN_ANGULAR_RES = 360/SVUMAN_NUM_ICONS;
    if (yaw < 0) {
      yaw += 360;
    }
    var guyImageNum = Math.round(yaw/SVUMAN_ANGULAR_RES) % SVUMAN_NUM_ICONS;
    return compass[guyImageNum];
  };
  
  var getYawIcon = function(yaw) {
    if (dynamicMarker) {
      return Drupal.gmaps.icon.getIcon(gmi.getOptions().base.map_data.svu.icon[getYawBearing(yaw)]);
    }
    else {
      return Drupal.gmaps.icon.getIcon(gmi.getOptions().base.map_data.svu.icon.n);
    }
  };

  var onYawChange = function(newYaw) {
    if (marker) {
      marker.setImage(getYawIcon(newYaw).image);
    }
  };
  
  var prepareInitOpts = function(initOpts) {
    initOpts = initOpts || {};
    
    var opts = gmi.getOptions().base.map_data.svu;
    
    if (typeof(opts.fullscreen) != 'undefined' && opts.fullscreen != null && (typeof(initOpts.enableFullScreen) == 'undefined' || initOpts.enableFullScreen == null)) {
      initOpts.enableFullScreen = parseInt(opts.fullscreen, 10) ? true : false;
    }
    
    initOpts.features = initOpts.features || {};
    if (typeof(opts.userphotos) != 'undefined' && opts.userphotos != null && (typeof(initOpts.features.userPhotos) == 'undefined' || initOpts.features.userPhotos == null)) {
      initOpts.features.userPhotos = parseInt(opts.userphotos) ? true : false;
      
      if (typeof(opts.photorepos) != 'undefined' && opts.photorepos != null && (typeof(initOpts.userPhotosOptions) == 'undefined' || initOpts.userPhotosOptions == null)) {
        var photorepos = new Array();
        $.each(opts.photorepos, function(k, v) {
          photorepos.push(k);
        });
        if (photorepos.length) {
          initOpts.userPhotosOptions = {photoRepositories: photorepos};
        }
      }
    }
    
    if (initOpts.features.userPhotos) {
      initOpts.features.streetView = true;
    }
    
    return initOpts;
  };
  
  var initialize = function() {
    self.container.height(Math.max(parseInt(gmi.getOptions().base.map_data.svu.height), GMAPS_MAP_SVU_MIN_HEIGHT));
    
    self.panorama = new GStreetviewPanorama(self.container[0], prepareInitOpts(initOpts));
    self.panorama.gmaps = {};
    self.panorama.gmaps.errorListener = GEvent.addListener(self.panorama, "error", handleError); 
    self.panorama.gmaps.initListener = GEvent.addListener(self.panorama, "initialized", function(loc) {updateMarker(loc.latlng)}); 
    self.panorama.gmaps.yawListener = GEvent.addListener(self.panorama, "yawchanged", onYawChange); 
    
    if (self.panorama && parseInt(gmi.getOptions().base.map_data.svu.resize)) {
      $(self.container).wrap('<div class="resizable-gmaps-svu-container"><span></span></div>')
      .parent().append($('<div class="grippie"></div>').mousedown(startDrag));
    
      var grippie = $('div.grippie', $(self.container).parent())[0];
      grippie.style.marginRight = (grippie.offsetWidth - $(self.container)[0].offsetWidth) +'px';
    }
  };
  
  var createMarker = function(point, pov) {
    if (!marker) {
      dynamicMarker = parseInt(gmi.getOptions().base.map_data.svu.icon.type);
      var icon = getYawIcon(pov.yaw);
      var markerOpts = {
        'icon': icon,
        'clickable': true,
        'draggable': true,
        'autoPan': true
      };
      marker = new  GMarker(point, markerOpts);
      marker.gmaps = marker.gmaps || {};
      marker.gmaps.svu = {'blowup': false, 'dragendListener': null, 'clickListener': null, 'rightclickListener': null};
      
      marker.gmaps.svu.dragendListener = GEvent.addListener(marker, 'dragend', function(ll) {
        self.setLatLng(ll);
      });
      
      if (parseInt(gmi.getOptions().base.map_data.svu.blowup)) {
        marker.gmaps.svu.clickListener = GEvent.addListener(marker, 'click', function(ll) {
          marker.showMapBlowup();
          marker.gmaps.svu.blowup = true;
        });
      }
      
      if (parseInt(gmi.getOptions().base.map_data.svu.hide)) {
        marker.gmaps.svu.rightclickListener = GEvent.addListener(gmi.gmap2, 'singlerightclick', function(p, dom, ov) {
          if (ov === marker) {
            self.hide();
          }
        });
      }
      
      gmi.gmap2.addOverlay(marker);
      
      if (parseInt(gmi.getOptions().base.map_data.svu.track)) {
        tracker = new MarkerTracker(marker, gmi.gmap2, {'updateEvent': 'moveend'});
      }
    }
  };
  
  var updateMarker = function(point, pov) {
    if (parseInt(gmi.getOptions().base.map_data.svu.marker)) {
      createMarker(point, pov);
      if (marker) {
        if (marker.gmaps.svu.blowup) {
          gmi.gmap2.closeInfoWindow();
          marker.gmaps.svu.blowup = false;
        }
        marker.setLatLng(point);
        marker.setImage(getYawIcon(pov.yaw).image);
      }
    }
  };
  
  var setLatLngCallback = function(ll, point, pov) {
    if (ll) {
      self.show();
      self.panorama.setLocationAndPOV(ll, pov);
      //setTimeout(function() {self.show();}, 1000);
      GEvent.trigger(self, 'gmapssvulocationset', ll);
    }
    else {
      GEvent.trigger(self, 'gmapssvunosvu');
      self.hide();
    }
    updateMarker(point, pov);
  };
  
  this.setLatLng = function(point, pov) {
    if (flashAvailable) {
      self.show();
      var p;
      if (point instanceof GLatLng) {
        p = new GLatLng(point.lat(), point.lng());
      }
      else {
        p = new GLatLng(point.latitude, point.longitude);
        if (!pov && point.pov) pov = $.extend(true, {}, point.pov); 
      }
      client.getNearestPanoramaLatLng(p, function (ll) {setLatLngCallback(ll, p, pov);});
    }
  };
  
  this.show = function() {
    if (flashAvailable && isHidden) {
      self.wrapper.show();
      isHidden = false;
    }
  };
  
  this.hide = function() {
    if (!isHidden) {
      self.wrapper.hide();
      isHidden = true;
    }
  };
  
  this.setMarker = function(m) {
    marker = m;
  };
  
  this.getClient = function() {
    return client;
  };
  
  initialize();
};
;
// $Id: gmaps-marker.js,v 1.1.4.6 2010/03/18 10:52:17 xmarket Exp $

GMapsMarkerActionHandlerLink = function(marker) {
  var toc, fs, acc, accHeader, accPanel, tabs, tabsPanel;
  
  var initialize = function() {
    if (marker.gmaps.options.link) {
      if (marker.gmaps.options.link.substr(0, 1) == '#') {
        toc = marker.gmaps.gmi.getOptions().base.map_data.toc_map;
        if (toc && parseInt(toc.enabled, 10)) {
          if (toc.style == 'fieldset') {
            var fs = $('#'+ marker.gmaps.options.link.substr(1), marker.gmaps.gmi.getContainer()).next().eq(0);
          }
          else if (toc.style == 'accordion') {
            acc = $('.gmaps-accordion', marker.gmaps.gmi.getContainer());
            var toc_id = acc.parent()[0].id;
            
            accHeader = Drupal.settings.gmaps.accordion[toc_id].options.header;
            accPanel = $('#'+ marker.gmaps.options.link.substr(1), acc).nextAll(accHeader).eq(0);
            var panel_id = accPanel.next()[0].id;
            
            if (Drupal.settings.gmaps.accordion[toc_id].ahahPanels && Drupal.settings.gmaps.accordion[toc_id].ahahPanels[panel_id]) {
              if (!Drupal.settings.gmaps.accordion[toc_id].ahahPanels[panel_id].data) {
                Drupal.settings.gmaps.accordion[toc_id].ahahPanels[panel_id].data = {};
              }
              Drupal.settings.gmaps.accordion[toc_id].ahahPanels[panel_id].data.marker = $.extend(true, Drupal.settings.gmaps.accordion[toc_id].ahahPanels[panel_id].data.marker || {}, marker.gmaps.options);
            }
          }
          else if (toc.style == 'tabs') {
            tabs = $('.gmaps-tabs', marker.gmaps.gmi.getContainer());
            var toc_id = tabs.parent()[0].id;
            
            tabsPanel = $('#'+ marker.gmaps.options.link.substr(1), tabs).next().eq(0);
            var panel_id = tabsPanel[0].id;
            
            if (Drupal.settings.gmaps.tabs[toc_id].ahahPanels && Drupal.settings.gmaps.tabs[toc_id].ahahPanels[panel_id]) {
              if (!Drupal.settings.gmaps.tabs[toc_id].ahahPanels[panel_id].data) {
                Drupal.settings.gmaps.tabs[toc_id].ahahPanels[panel_id].data = {};
              }
              Drupal.settings.gmaps.tabs[toc_id].ahahPanels[panel_id].data.marker = $.extend(true, Drupal.settings.gmaps.tabs[toc_id].ahahPanels[panel_id].data.marker || {}, marker.gmaps.options);
            }
          }
        }
      }
    }
  };
  
  var click = function() {
    if (marker.gmaps.options.link) {
      if (marker.gmaps.options.link.substr(0, 1) == '#') {
        if (toc && parseInt(toc.enabled, 10)) {
          if (toc.style == 'fieldset') {
            if (fs.hasClass('collapsed')) {
              $('legend a', fs).click();
            }
            if (!window.location.hash || window.location.hash != marker.gmaps.options.link) {
              window.location.hash = marker.gmaps.options.link;
            }
          }
          else if (toc.style == 'accordion') {
            if (!accPanel.hasClass('ui-state-active')) {
              if (!window.location.hash || window.location.hash != marker.gmaps.options.link) {
                acc.one('accordionchange', function() {
                  window.location.hash = marker.gmaps.options.link;
                });
              }
              acc.accordion('activate', $(accHeader, acc).index(accPanel));
            }
            else if (!window.location.hash || window.location.hash != marker.gmaps.options.link) {
              window.location.hash = marker.gmaps.options.link;
            }
          }
          else if (toc.style == 'tabs') {
            if (tabsPanel.hasClass('ui-tabs-hide')) {
              if (!window.location.hash || window.location.hash != marker.gmaps.options.link) {
                tabs.one('tabsshow', function() {
                  window.location.hash = marker.gmaps.options.link;
                });
              }
              tabs.tabs('select', tabsPanel[0].id);
            }
            else if (!window.location.hash || window.location.hash != marker.gmaps.options.link) {
              window.location.hash = marker.gmaps.options.link;
            }
          }
          //plain box
          else if (!window.location.hash || window.location.hash != marker.gmaps.options.link) {
            window.location.hash = marker.gmaps.options.link;
          }
        }
        else if (!window.location.hash || window.location.hash != marker.gmaps.options.link) {
          window.location.hash = marker.gmaps.options.link;
        }
      }
      else if (marker.gmaps.options.link_target == '_blank') {
        window.open(marker.gmaps.options.link);
      }
      else {
        window.location.href = marker.gmaps.options.link;
      }
    }
  };
  
  this.hover = function(ll) {
    click();
  };

  this.click = function(ll) {
    click();
  };

  this.dblclick = function(ll) {
    click();
  };

  this.rightclick = function(p, dom) {
    click();
  };
  
  initialize();
};

GMapsMarkerActionHandlerSvu = function(marker) {
  var pov = marker.gmaps.point.pov;
  var svu = marker.gmaps.gmi.getSVU();
  
  var showSvu = function() {
    if (svu && pov && parseInt(pov.has_svu, 10) && parseInt(pov.enabled, 10)) {
      svu.setLatLng(marker.gmaps.options.point);
    }
    else {
      $.each(marker.gmaps.action, function(e, refs) {
        if (refs.handler instanceof GMapsMarkerActionHandlerSvu) {
          GEvent.removeListener(marker.gmaps.action[e].listener);
          delete marker.gmaps.action[e];
        }
      });
    }
  };
  
  this.hover = function(ll) {
    showSvu();
  };

  this.click = function(ll) {
    showSvu();
  };

  this.dblclick = function(ll) {
    showSvu();
  };

  this.rightclick = function(p, dom) {
    showSvu();
  };
};

GMapsMarkerActionHandlerBlowup = function(marker) {
  var opts = {};
  
  var initialize = function() {
    var gmapsOpts = (marker.gmaps.options.iw_data && marker.gmaps.options.iw_data.google) || {};
    gmapsOpts.blowup = gmapsOpts.blowup || {};
    if (gmapsOpts.blowup.type && typeof(marker.gmaps.gmi.maptypes[gmapsOpts.blowup.type]) != 'undefined') {
      opts.mapType = marker.gmaps.gmi.maptypes[gmapsOpts.blowup.type];
    }
    if (parseInt(gmapsOpts.blowup.zoom) > -1) {
      opts.zoomLevel = parseInt(gmapsOpts.blowup.zoom);
    }
  };
  
  var showBlowup = function() {
    marker.showMapBlowup(opts);
  };
  
  this.hover = function(ll) {
    showBlowup();
  };

  this.click = function(ll) {
    showBlowup();
  };

  this.dblclick = function(ll) {
    showBlowup();
  };

  this.rightclick = function(p, dom) {
    showBlowup();
  };
  
  initialize();
};

GMapsMarkerActionHandlerContent = function(marker) {
  var iwHandler, content;
  
  var initialize = function() {
    if (marker.gmaps.gmi.gmap2.infoWindowEnabled() && marker.gmaps.gmi.iwHandlers[marker.gmaps.options.basic.info_window]) {
      iwHandler = marker.gmaps.gmi.iwHandlers[marker.gmaps.options.basic.info_window];
      content = $.extend(true, {}, marker.gmaps.options.content);
    }
  };
  
  var showContent = function() {
    marker.gmaps.gmi.bulletinBoardHide();
    if (iwHandler) {
      if (content.ajax != null && content.ajax.url != null && content.ajax.url.length) {
        var mapOpts = $.extend(true, {}, marker.gmaps.gmi.getOptions());
        delete mapOpts.overlays;
        var data = $.extend(true, {'marker': marker.gmaps.options, 'gmi': mapOpts}, content.ajax.data ? content.ajax.data : {});
        content.ajax.data = Drupal.gmaps.flatten(data);
        Drupal.gmaps.map.loadContent(content, function(c){content = c; iwHandler.openMarkerInfoWindow(marker, content);}, marker.gmaps.gmi, marker.getLatLng());
      }
      else {
        iwHandler.openMarkerInfoWindow(marker, content);
      }
    }
  };
  
  this.hover = function(ll) {
    showContent();
  };

  this.click = function(ll) {
    showContent();
  };

  this.dblclick = function(ll) {
    showContent();
  };

  this.rightclick = function(p, dom) {
    showContent();
  };
  
  initialize();
};

Drupal.gmaps.marker = Drupal.gmaps.marker || new (function() {
  var self = this;
  
  this.hooks = {
    action: {
      hover: {
        link: GMapsMarkerActionHandlerLink,
        svu: GMapsMarkerActionHandlerSvu,
        blowup: GMapsMarkerActionHandlerBlowup,
        content: GMapsMarkerActionHandlerContent
      },
      click: {
        link: GMapsMarkerActionHandlerLink,
        svu: GMapsMarkerActionHandlerSvu,
        blowup: GMapsMarkerActionHandlerBlowup,
        content: GMapsMarkerActionHandlerContent
      },
      dblclick: {
        link: GMapsMarkerActionHandlerLink,
        svu: GMapsMarkerActionHandlerSvu,
        blowup: GMapsMarkerActionHandlerBlowup,
        content: GMapsMarkerActionHandlerContent
      },
      rightclick: {
        link: GMapsMarkerActionHandlerLink,
        svu: GMapsMarkerActionHandlerSvu,
        blowup: GMapsMarkerActionHandlerBlowup,
        content: GMapsMarkerActionHandlerContent
      }
    }
  };
  
  var parseOpts = function(gmapsOpts) {
    gmapsOpts = gmapsOpts || {};
    var o = {};
    o.clickable = parseInt(gmapsOpts.clickable, 10);
    o.draggable = parseInt(gmapsOpts.draggable, 10);
    o.hide = parseInt(gmapsOpts.hide, 10);
    o.autoPan = parseInt(gmapsOpts.autopan, 10);
    o.dragCrossMove = parseInt(gmapsOpts.dcmove, 10);
    o.bouncy = parseInt(gmapsOpts.bouncy, 10);
    o.bounceGravity = parseFloat(gmapsOpts.gravity, 10);
    return o;
  };
  
  var parseTrackerOpts = function(gmapsOpts) {
    var o = {};
    o.iconScale = parseFloat(gmapsOpts.scale, 10);
    o.padding = parseInt(gmapsOpts.padding, 10);
    o.color = gmapsOpts.color;
    o.weight = parseInt(gmapsOpts.weight, 10);
    o.length = parseInt(gmapsOpts.length, 10);
    o.opacity = parseFloat(gmapsOpts.opacity, 10);
    o.updateEvent = gmapsOpts.update_event;
    o.quickPanEnabled = parseInt(gmapsOpts.quick_pan, 10) ? true : false;
    o.panEvent = gmapsOpts.pan_event;
    return o;
  };
  
  var createClusterer = function(gmi, markers, opts) {
    var o = {
      gridSize: parseInt(opts.gridsize, 10),
      styles: []
    };
    if (parseInt(opts.maxzoom, 10) > -1) {
      o.maxZoom = parseInt(opts.maxzoom, 10);
    }
    $.each(opts.styles, function() {
      if (parseInt(this.icon, 10)) {
        var s = {};
        var icon = Drupal.gmaps.icon.getIcon(this.icon);
        if (icon) {
          s.url = icon.image;
          s.width = icon.iconSize.width;
          s.height = icon.iconSize.height;
          if (this.color && this.color.length) {
            s.opt_textColor = this.color;
          }
          if (this.anchor) {
            s.opt_anchor = this.anchor;
          }
          o.styles.push(s);
        }
      }
    });
    
    return new MarkerClusterer(gmi.gmap2, markers, o);
  };
  
  this.createMarker = function(gmi, opts) {
    var o = parseOpts(opts.options), marker, point;
    
    o.icon = parseInt(opts.basic.icon, 10) ? Drupal.gmaps.icon.getIcon(parseInt(opts.basic.icon, 10)) : G_DEFAULT_ICON;
    
    if (opts.title) {
      o.title = opts.title;
    }
    
    point = new GLatLng(parseFloat(opts.point.latitude), parseFloat(opts.point.longitude));
    if (opts.labeled && opts.labeled.enabled) {
      o.labelText = opts.labeled.label;
      o.labelClass = opts.labeled['class'];
      o.labelOffset = new GSize(parseInt(opts.labeled.offset.x, 10), parseInt(opts.labeled.offset.y, 10));
      marker = new LabeledMarker(point, o);
    }
    else {
      marker = new GMarker(point, o);
    }
    
    return marker;
  };
  
  this.prepareMarker = function(marker, gmi, opts) {
    marker.gmaps = {
      gmi: gmi,
      options: $.extend(true, {}, opts)
    };
    marker.gmaps.point = marker.gmaps.options.point;
    
    if (opts.action) {
      marker.gmaps.action = {};
      $.each(opts.action, function(e, todo) {
        if (todo && Drupal.gmaps.marker.hooks.action[e][todo]) {
          marker.gmaps.action[e] = {handler: new (Drupal.gmaps.marker.hooks.action[e][todo])(marker)};
          if (e == 'rightclick') {
            marker.gmaps.action[e].listener = GEvent.addListener(gmi.gmap2, 'singlerightclick', function(p, dom, ov) {
              if (ov === marker) {
                if (marker.gmaps.rightclickTimer) {
                  marker.gmaps.rightclickTimer = clearTimeout(marker.gmaps.rightclickTimer);
                }
                marker.gmaps.rightclickTimer = setTimeout(function() {
                  marker.gmaps.rightclickTimer = clearTimeout(marker.gmaps.rightclickTimer);
                  marker.gmaps.action[e].handler[e](p, dom);
                }, 300);
              }
            });
          }
          else if (e == 'click') {
            marker.gmaps.action[e].listener = GEvent.addListener(marker, e, function(ll) {
              if (marker.gmaps.clickTimer) {
                marker.gmaps.clickTimer = clearTimeout(marker.gmaps.clickTimer);
              }
              marker.gmaps.clickTimer = setTimeout(function() {
                marker.gmaps.clickTimer = clearTimeout(marker.gmaps.clickTimer);
                marker.gmaps.action[e].handler[e](ll);
              }, 300);
            });
          }
          else if (e == 'dblclick') {
            marker.gmaps.action[e].listener = GEvent.addListener(marker, e, function(ll) {
              if (marker.gmaps.clickTimer) {
                marker.gmaps.clickTimer = clearTimeout(marker.gmaps.clickTimer);
              }
              marker.gmaps.action[e].handler[e](ll);
            });
          }
          else if (e == 'hover') {
            marker.gmaps.action[e].listener = GEvent.addListener(marker, 'mouseover', function(ll) {
              marker.gmaps.action[e].handler[e](ll);
            });
          }
        }
      });
    }
    
    if (opts.tracker && parseInt(opts.tracker.enabled, 10)) {
      marker.gmaps.tracker = new MarkerTracker(marker, gmi.gmap2, parseTrackerOpts(opts.tracker));
      marker.gmaps.trackerListener = GEvent.addListener(marker, 'visibilitychanged', function (isVisible) {
        if (isVisible) {
          marker.gmaps.tracker.enable();
        }
        else {
          marker.gmaps.tracker.disable();
        }
      });
    }
    
    return marker;
  };
  
  this.addContent = function(gmi, content) {
    if (!content);
    
    var markers = [];
    $.each(content, function(id, opts) {
      var marker = self.createMarker(gmi, opts);
      markers.push(self.prepareMarker(marker, gmi, opts));
    });
    
    if (markers.length) {
      if (!gmi.overlays.marker) {
        gmi.overlays.marker = {};
      }
      var ovData = gmi.getOptions().base.ov_data || {};
      var opts = ovData.marker || {}, route = [], b;
      var first_zoomed = false;
      
      if (!gmi.gmaps.marker) {
        gmi.gmaps.marker = {};
      }
      
      var clustered = [], managed = [];
      $.each(markers, function() {
        if (gmi.overlays.marker[this.gmaps.options.id]) {
          gmi.gmap2.removeOverlay(gmi.overlays.marker[this.gmaps.options.id]);
        }
        gmi.overlays.marker[this.gmaps.options.id] = this;
        
        if (opts && opts.route && parseInt(opts.route.enabled, 10) && (!this.gmaps.options.manager || !parseInt(this.gmaps.options.manager.skip_route, 10))) {
          route.push(this.getLatLng());
        }
        
        var direct = false;
        if (opts && opts.manager && opts.manager.manager && opts.manager.manager.length && (!this.gmaps.options.manager || !parseInt(this.gmaps.options.manager.skip_manager, 10))) {
          if (opts.manager.manager == 'clusterer') {
            clustered.push(this);
          }
          else {
            managed.push(this);
          }
          if (gmi.getOptions().base.methods.auto_center_zoom || (gmi.getOptions().base.methods.constructor == Array && $.inArray('auto_center_zoom', gmi.getOptions().base.methods.methods))) {
            var bounds = Drupal.gmaps.map.getOverlayBounds(this);
            
            if (bounds) {
              if (!gmi.gmap2.gmaps.aczBounds) {
                gmi.gmap2.gmaps.aczBounds = bounds;
              }
              else {
                gmi.gmap2.gmaps.aczBounds.extend(bounds.getSouthWest());
                gmi.gmap2.gmaps.aczBounds.extend(bounds.getNorthEast());
              }
            }
          }
        }
        else {
          gmi.gmap2.addOverlay(this);
        }
        
        //zoom to first
        if (!first_zoomed) {
          first_zoomed = true;
          if (opts.misc && parseInt(opts.misc.zoom_first, 10) && (b = Drupal.gmaps.map.getOverlayBounds(this, true))) {
            gmi.gmap2.setZoom(gmi.gmap2.getBoundsZoomLevel(b))
          }
        }
        
        if (this.gmaps.tracker) {
          if (this.isHidden()) {
            this.gmaps.tracker.disable();
          }
          else {
            this.gmaps.tracker.enable();
          }
        }
      });
      
      if (route.length) {
        if (gmi.gmaps.marker.route) {
          var i = gmi.gmaps.marker.route.getVertexCount();
          $.each(route, function(j, latlng) {
            gmi.gmaps.marker.route.insertVertex(i+j, latlng);
          });
        }
        else {
          gmi.gmaps.marker.route = new GPolyline(route, opts.route.color, parseInt(opts.route.weight, 10), parseFloat(opts.route.opacity, 10), {clickable: false, geodesic: parseInt(opts.route.geodesic, 10)});
          gmi.gmap2.addOverlay(gmi.gmaps.marker.route);
        }
      }
      
      if (clustered.length) {
        if (gmi.gmaps.marker.clusterer) {
          gmi.gmaps.marker.clusterer.addMarkers(clustered);
        }
        else {
          gmi.gmaps.marker.clusterer = createClusterer(gmi, clustered, opts.manager.clusterer);
        }
      }

      if (managed.length) {
        if (!gmi.gmaps.marker.manager) {
          var o = {
              trackMarkers: parseInt(opts.manager.mm.trackmarkers, 10),
              borderPadding: parseInt(opts.manager.mm.padding, 10),
              maxZoom: parseInt(opts.manager.mm.maxzoom, 10)
          };
          if (o.maxZoom < 0) delete o.maxZoom;
          gmi.gmaps.marker.manager = opts.manager.manager == 'google' ? new GMarkerManager(gmi.gmap2, o) : new MarkerManager(gmi.gmap2, o);
        }
        $.each(managed, function(i, marker) {
          var min, max;
          if (marker.gmaps.options.manager) {
            min = parseInt(marker.gmaps.options.manager.minzoom, 10);
            max = parseInt(marker.gmaps.options.manager.maxzoom, 10);
          }
          min = min || 0;
          max = (max && max > -1) ? max : null;
          gmi.gmaps.marker.manager.addMarker(this, min, max);
        });
        gmi.gmaps.marker.manager.refresh();
      }
    }
  };
})();

Drupal.gmaps.map.hooks.overlay.marker = Drupal.gmaps.marker;
;
// $Id: gmaps-icon.js,v 1.1.2.4 2010/03/18 10:52:16 xmarket Exp $

/**
 * Credits
 * The original createMarkerIcon(), createLabeledMarkerIcon() and createFlatIcon()
 * were written by Pamela Fox as part of the MapIconMaker project.
 * See: http://code.google.com/p/gmaps-utility-library/
 */

/**
 * Required when used on admin pages.
 */
Drupal.gmaps = Drupal.gmaps || {};

Drupal.gmaps.icon = Drupal.gmaps.icon || new (function(){
  var self = this;
  this.icons = {};

  this.createIcon = function(opts) {
    if (this.hooks[opts.type]) {
      var icon = this.hooks[opts.type](opts);
      return icon || G_DEFAULT_ICON;
    }
  };
  
  this.getIcon = function(id, refresh) {
    id = 'icon_'+ id;
    if (self.icons[id]) {
      if (refresh) {
        self.icons[id] = null;
      }
      else {
        return self.icons[id];
      }
    }
    if (Drupal.settings.gmaps.icon && Drupal.settings.gmaps.icon[id]) {
      self.icons[id] = self.createIcon(Drupal.settings.gmaps.icon[id]);
    }
    return self.icons[id];
  };
  
  this.escapeLabel = function (text) {
    if (text === undefined) {
      return "";
    }
    text = text.replace(/@/, "@@");
    text = text.replace(/\\/, "@\\");
    text = text.replace(/'/, "@'");
    text = text.replace(/\[/, "@[");
    text = text.replace(/\]/, "@]");
    return Drupal.encodeURIComponent(text);
  };
  
  this.setDragCross = function(icon, opts) {
    if (opts.maxheight && opts.maxheight.length) {
      icon.maxHeight = opts.maxheight;
    }
    
    if (opts.drag_cross_image && opts.drag_cross_image.length) {
      icon.dragCrossImage = opts.drag_cross_image;
      icon.dragCrossSize = new GSize(opts.drag_cross_size.width, opts.drag_cross_size.height);
      icon.dragCrossAnchor = new GPoint(opts.drag_cross_anchor.x, opts.drag_cross_anchor.y);
    }
  };
  
  this.createCustomIcon = function(opts) {
    var icon = new GIcon(G_DEFAULT_ICON, opts.icon);
    
    if (opts.icon_size) {
      icon.iconSize = new GSize(opts.icon_size.width, opts.icon_size.height);
    }
    if (opts.icon_anchor) {
      icon.iconAnchor = new GPoint(opts.icon_anchor.x, opts.icon_anchor.y);
    }

    if (opts.shadow && opts.shadow.length) {
      icon.shadow = opts.shadow;
    }
    if (opts.shadow_size) {
      icon.shadowSize = new GSize(opts.shadow_size.width, opts.shadow_size.height);
    }

    if (opts.info_window_anchor) {
      icon.infoWindowAnchor = new GPoint(opts.info_window_anchor.x, opts.info_window_anchor.y);
    }

    if (opts.print_image && opts.print_image.length) {
      icon.printImage = opts.print_image;
    }
    if (opts.moz_print_image && opts.moz_print_image.length) {
      icon.mozPrintImage = opts.moz_print_image;
    }
    if (opts.print_shadow && opts.print_shadow.length) {
      icon.printShadow = opts.print_shadow;
    }
    if (opts.transparent && opts.transparent.length) {
      icon.transparent = opts.transparent;
    }

    if (opts.imagemap && opts.imagemap.length) {
      var imap = opts.imagemap.split(/\s*,\s*/);
      for (var i = 0; i < imap.length; i++) {
        imap[i] = parseInt(imap[i]);
      }
      icon.imageMap = imap;
    }
    
    self.setDragCross(icon, opts);
    
    return icon;
  };
  
  this.createMarkerIcon = function(opts) {
    if (opts.data.cache && !opts.throttle) {
      return self.createCustomIcon(opts);
    }  
    
    var icon = new GIcon(G_DEFAULT_ICON);
    
    var width = opts.icon_size.width || 32;
    var height = opts.icon_size.height || 32;
    var primaryColor = opts.data.primary_color || "#ff0000";
    var strokeColor = opts.data.stroke_color || "#000000";
    var cornerColor = opts.data.corner_color || "#ffffff";
     
    var baseUrl = "http://chart.apis.google.com/chart?cht=mm";
    var iconUrl = baseUrl + "&chs=" + width + "x" + height + 
        "&chco=" + cornerColor.replace("#", "") + "," + 
        primaryColor.replace("#", "") + "," + 
        strokeColor.replace("#", "");
    
    icon.image = iconUrl + "&ext=.png";
    icon.iconSize = new GSize(width, height);
    icon.shadowSize = new GSize(Math.floor(width * 1.6), height);
    icon.iconAnchor = new GPoint(width / 2, height);
    icon.infoWindowAnchor = new GPoint(width / 2, Math.floor(height / 12));
    icon.printImage = iconUrl + "&chof=gif";
    icon.mozPrintImage = iconUrl + "&chf=bg,s,ECECD8" + "&chof=gif";
    icon.transparent = iconUrl + "&chf=a,s,ffffff11&ext=.png";

    icon.imageMap = [
      width / 2, height,
      (7 / 16) * width, (5 / 8) * height,
      (5 / 16) * width, (7 / 16) * height,
      (7 / 32) * width, (5 / 16) * height,
      (5 / 16) * width, (1 / 8) * height,
      (1 / 2) * width, 0,
      (11 / 16) * width, (1 / 8) * height,
      (25 / 32) * width, (5 / 16) * height,
      (11 / 16) * width, (7 / 16) * height,
      (9 / 16) * width, (5 / 8) * height
    ];
    for (var i = 0; i < icon.imageMap.length; i++) {
      icon.imageMap[i] = parseInt(icon.imageMap[i]);
    }

    self.setDragCross(icon, opts);
    
    return icon;
  };
  
  this.createLabeledMarkerIcon = function (opts) {
    if (opts.data.cache && !opts.throttle) {
      return self.createCustomIcon(opts);
    }  
    
    var icon = new GIcon(G_DEFAULT_ICON);
    
    var pinStyle = opts.data.pin_style || 'pin';
    var label = self.escapeLabel(opts.label) || "";
    var labelCut = opts.data.label_cut || 2;
    var width = 21;
    var height = 34;
    if (pinStyle == 'pin_star') {
      width = 23;
      height = 39;
    }  
    else if (pinStyle == 'pin_sleft' || pinStyle == 'pin_sright') {
      width = 23;
      height = 33;
    }  
    var primaryColor = opts.data.primary_color || "#FF0000";
    var strokeColor = opts.data.stroke_color || "#000000";
    var labelColor = opts.data.label_color || "#000000";
    var starPrimaryColor = opts.data.star_primary_color || "#FFFF00";
    var starStrokeColor = opts.data.star_stroke_color || "#0000FF";
    
    var baseUrl = "http://chart.apis.google.com/chart?cht=d&chdp=mapsapi&chl=";
    var iconUrl = baseUrl + pinStyle + "'i\\" + "'[" + label + 
        "'-" + labelCut + "'f\\"  + "hv'a\\]" + "h\\]o\\" + 
        primaryColor.replace("#", "")  + "'fC\\" + 
        labelColor.replace("#", "")  + "'tC\\" + 
        strokeColor.replace("#", "")  + "'eC\\";
    if (pinStyle == 'pin_star') {
      iconUrl += starPrimaryColor.replace("#", "") + "'1C\\" + 
          starStrokeColor.replace("#", "") + "'0C\\";
    }

    icon.image = iconUrl + "Lauto'f\\&ext=.png";
    icon.iconSize = new GSize(width, height);
    icon.shadowSize = new GSize(Math.floor(width * 1.6), height);
    icon.iconAnchor = new GPoint(width / 2, height);
    icon.infoWindowAnchor = new GPoint(width / 2, Math.floor(height / 12));
    icon.printImage = iconUrl + "&chof=gif";
    icon.mozPrintImage = iconUrl + "&chf=bg,s,ECECD8" + "&chof=gif";
    icon.transparent = iconUrl + "Lauto'f\\&chf=a,s,ffffff11&ext=.png";

    icon.imageMap = [
      width / 2, height,
      (7 / 16) * width, (5 / 8) * height,
      (5 / 16) * width, (7 / 16) * height,
      (7 / 32) * width, (5 / 16) * height,
      (5 / 16) * width, (1 / 8) * height,
      (1 / 2) * width, 0,
      (11 / 16) * width, (1 / 8) * height,
      (25 / 32) * width, (5 / 16) * height,
      (11 / 16) * width, (7 / 16) * height,
      (9 / 16) * width, (5 / 8) * height
    ];
    for (var i = 0; i < icon.imageMap.length; i++) {
      icon.imageMap[i] = parseInt(icon.imageMap[i]);
    }

    self.setDragCross(icon, opts);
    
    return icon;
  };
  
  this.createFlatIcon = function (opts) {
    if (opts.data.cache && !opts.throttle) {
      return self.createCustomIcon(opts);
    }  
    
    var icon = new GIcon(G_DEFAULT_ICON);
    
    var width = opts.icon_size.width || 32;
    var height = opts.icon_size.height || 32;
    var labelColor = opts.data.label_color || "#000000";
    var primaryColor = opts.data.primary_color || "#FF0000";
    var shadowFromColor = opts.data.shadow_from_color || "#000000";
    var shadowToColor = opts.data.shadow_to_color || "#000000";
    var labelSize = opts.data.label_size || 0;
    var shadowFromTransparency = opts.data.shadow_from_transparency || "FF";
    var shadowToTransparency = opts.data.shadow_to_transparency || "01";
    var shape = opts.data.shape ||  "circle";
    var shapeCode = (shape === "circle") ? "it" : "itr";
    var label = Drupal.encodeURIComponent(opts.label) || "";

    var baseUrl = "http://chart.apis.google.com/chart?cht=" + shapeCode;
    var iconUrl = baseUrl + "&chs=" + width + "x" + height + 
        "&chco=" + primaryColor.replace("#", "") + "," + 
        shadowFromColor.replace("#", "") + shadowFromTransparency + "," + shadowToColor.replace("#", "") + shadowToTransparency +
        "&chl=" + label + "&chx=" + labelColor.replace("#", "") + 
        "," + labelSize;

    icon.image = iconUrl + "&chf=bg,s,00000000&ext=.png";
    icon.iconSize = new GSize(width, height);
    icon.shadowSize = new GSize(0, 0);
    icon.iconAnchor = new GPoint(width / 2, height / 2);
    icon.infoWindowAnchor = new GPoint(width / 2, height / 2);
    icon.printImage = iconUrl + "&chof=gif";
    icon.mozPrintImage = iconUrl + "&chf=bg,s,ECECD8&chof=gif";
    icon.transparent = iconUrl + "&chf=a,s,ffffff01&ext=.png";
    icon.imageMap = []; 
    if (shapeCode === "itr") {
      icon.imageMap = [0, 0, width, 0, width, height, 0, height];
    } else {
      var polyNumSides = 8;
      var polySideLength = 360 / polyNumSides;
      var polyRadius = Math.min(width, height) / 2;
      for (var a = 0; a < (polyNumSides + 1); a++) {
        var aRad = polySideLength * a * (Math.PI / 180);
        var pixelX = polyRadius + polyRadius * Math.cos(aRad);
        var pixelY = polyRadius + polyRadius * Math.sin(aRad);
        icon.imageMap.push(parseInt(pixelX), parseInt(pixelY));
      }
    }

    self.setDragCross(icon, opts);
    
    return icon;
  };
  
  this.createIconicMarkerIcon = function (opts) {
    if (opts.data.cache && !opts.throttle) {
      return self.createCustomIcon(opts);
    }  
    
    var icon = new GIcon(G_DEFAULT_ICON);
    
    var pinStyle = opts.data.pin_style || 'pin';
    var pinIcon = opts.data.pin_icon || 'home';
    var width = 21;
    var height = 34;
    if (pinStyle == 'pin_star') {
      width = 23;
      height = 39;
    }  
    else if (pinStyle == 'pin_sleft' || pinStyle == 'pin_sright') {
      width = 23;
      height = 33;
    }  
    var primaryColor = opts.data.primary_color || "#FF0000";
    var starColor = opts.data.star_color || "#FFFF00";
    
    var baseUrl = "http://chart.apis.google.com/chart?chst=d_map_xpin_icon&chld=";
    var shadowBaseUrl = "http://chart.apis.google.com/chart?chst=d_map_xpin_shadow&chld=";
    var iconUrl = baseUrl + pinStyle + "|" + pinIcon + "|" +
        primaryColor.replace("#", "") + "|" + starColor.replace("#", "");

    icon.image = iconUrl + "&ext=.png";
    icon.iconSize = new GSize(width, height);
    icon.shadow = shadowBaseUrl + pinStyle + "&ext=.png";
    icon.shadowSize = new GSize(Math.floor(width * 1.6), height);
    icon.iconAnchor = new GPoint(width / 2, height);
    icon.infoWindowAnchor = new GPoint(width / 2, Math.floor(height / 12));
    icon.printImage = iconUrl + "&chof=gif";
    icon.mozPrintImage = iconUrl + "&chf=bg,s,ECECD8" + "&chof=gif";
    icon.transparent = iconUrl + "&chf=a,s,ffffff11&ext=.png";

    icon.imageMap = [
      width / 2, height,
      (7 / 16) * width, (5 / 8) * height,
      (5 / 16) * width, (7 / 16) * height,
      (7 / 32) * width, (5 / 16) * height,
      (5 / 16) * width, (1 / 8) * height,
      (1 / 2) * width, 0,
      (11 / 16) * width, (1 / 8) * height,
      (25 / 32) * width, (5 / 16) * height,
      (11 / 16) * width, (7 / 16) * height,
      (9 / 16) * width, (5 / 8) * height
    ];
    for (var i = 0; i < icon.imageMap.length; i++) {
      icon.imageMap[i] = parseInt(icon.imageMap[i]);
    }

    self.setDragCross(icon, opts);
    
    return icon;
  };
  
  this.createScaledMarkerIcon = function (opts) {
    if (opts.data.cache && !opts.throttle) {
      return self.createCustomIcon(opts);
    }  
    
    var icon = new GIcon(G_DEFAULT_ICON);
    
    var scale = opts.data.scale || 0.5;
    var rotation = opts.data.rotation || 0;
    var labelSize = opts.data.label_size || 10;
    var labelStyle = opts.data.label_style || '_';

    var iconSize = opts.icon_size || {'width': null, 'height': null};
    var width = iconSize.width || Math.ceil(37 * scale);
    var height = iconSize.height || Math.ceil(66 * scale);

    var primaryColor = opts.data.primary_color || "#FF0000";
    var label = "";
    if (opts.label) {
      var labels = opts.label.split('|');
      for(var i in labels) {
        labels[i] = Drupal.encodeURIComponent(labels[i]);
      }
      label = labels.join('|');
    }

    
    var baseUrl = "http://chart.apis.google.com/chart?chst=d_map_spin&chld=";
    var iconUrl = baseUrl + scale + "|" + rotation + "|" +
        primaryColor.replace("#", "") + "|" + labelSize + "|" + labelStyle + "|" + label;

    icon.image = iconUrl + "&ext=.png";
    icon.iconSize = new GSize(width, height);
    icon.shadowSize = new GSize(0, 0);
    icon.iconAnchor = new GPoint(width / 2, height);
    icon.infoWindowAnchor = new GPoint(width / 2, Math.floor(height / 12));
    icon.printImage = iconUrl + "&chof=gif";
    icon.mozPrintImage = iconUrl + "&chf=bg,s,ECECD8" + "&chof=gif";
    icon.transparent = iconUrl + "&chf=a,s,ffffff11&ext=.png";

    icon.imageMap = [
      width / 2, height,
      (7 / 16) * width, (5 / 8) * height,
      (5 / 16) * width, (7 / 16) * height,
      (7 / 32) * width, (5 / 16) * height,
      (5 / 16) * width, (1 / 8) * height,
      (1 / 2) * width, 0,
      (11 / 16) * width, (1 / 8) * height,
      (25 / 32) * width, (5 / 16) * height,
      (11 / 16) * width, (7 / 16) * height,
      (9 / 16) * width, (5 / 8) * height
    ];
    for (var i = 0; i < icon.imageMap.length; i++) {
      icon.imageMap[i] = parseInt(icon.imageMap[i]);
    }

    self.setDragCross(icon, opts);
    
    return icon;
  };

  this.hooks = {
    'custom': this.createCustomIcon,
    'marker': this.createMarkerIcon,
    'labeled_marker': this.createLabeledMarkerIcon,
    'flat': this.createFlatIcon,
    'iconic_marker': this.createIconicMarkerIcon,
    'scaled_marker': this.createScaledMarkerIcon
  };

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

/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-06-19 20:25:28 -0500 (Tue, 19 Jun 2007) $
 * $Rev: 2111 $
 *
 * Version 2.1
 */
;(function($){$.fn.bgIframe=$.fn.bgiframe=function(s){if($.browser.msie&&parseInt($.browser.version)<=6){s=$.extend({top:'auto',left:'auto',width:'auto',height:'auto',opacity:true,src:'javascript:false;'},s||{});var prop=function(n){return n&&n.constructor==Number?n+'px':n;},html='<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+'style="display:block;position:absolute;z-index:-1;'+(s.opacity!==false?'filter:Alpha(Opacity=\'0\');':'')+'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+'"/>';return this.each(function(){if($('> iframe.bgiframe',this).length==0)this.insertBefore(document.createElement(html),this.firstChild);});}return this;};if(!$.browser.version)$.browser.version=navigator.userAgent.toLowerCase().match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)[1];})(jQuery);;

;(function($){
	/* hoverIntent by Brian Cherne */
	$.fn.hoverIntent = function(f,g) {
		// default configuration options
		var cfg = {
			sensitivity: 7,
			interval: 100,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
			var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
			while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
			if ( p == this ) { return false; }

			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// else e.type == "onmouseover"
			if (e.type == "mouseover") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "onmouseout"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.mouseover(handleHover).mouseout(handleHover);
	};
	
})(jQuery);;

/*
 * Supposition v0.2 - an optional enhancer for Superfish jQuery menu widget
 *
 * Copyright (c) 2008 Joel Birch - based mostly on work by Jesse Klaasse and credit goes largely to him.
 * Special thanks to Karl Swedberg for valuable input.
 *
 * Dual licensed under the MIT and GPL licenses:
 * 	http://www.opensource.org/licenses/mit-license.php
 * 	http://www.gnu.org/licenses/gpl.html
 */

(function($){

	$.fn.supposition = function(){
		var $w = $(window), /*do this once instead of every onBeforeShow call*/
			_offset = function(dir) {
				return window[dir == 'y' ? 'pageYOffset' : 'pageXOffset']
				|| document.documentElement && document.documentElement[dir=='y' ? 'scrollTop' : 'scrollLeft']
			    || document.body[dir=='y' ? 'scrollTop' : 'scrollLeft'];
			},
			onInit = function(){
				/* I haven't touched this bit - needs work as there are still z-index issues */
				$topNav = $('li',this);
				var cZ=parseInt($topNav.css('z-index')) + $topNav.length;
				$topNav.each(function() {
					$(this).css({zIndex:--cZ});
				});
			},
			onHide = function(){
				this.css({marginTop:'',marginLeft:''});
			},
			onBeforeShow = function(){
				this.each(function(){
					var $u = $(this);
					$u.css('display','block');
					var menuWidth = $u.width(),
						parentWidth = $u.parents('ul').width(),
						totalRight = $w.width() + _offset('x'),
						menuRight = $u.offset().left + menuWidth;
					if (menuRight > totalRight) {
						$u.css('margin-left', ($u.parents('ul').length == 1 ? totalRight - menuRight : -(menuWidth + parentWidth)) + 'px');
					}

					var windowHeight = $w.height(),
						offsetTop = $u.offset().top,
						menuHeight = $u.height(),
						baseline = windowHeight + _offset('y');
					var expandUp = (offsetTop + menuHeight > baseline);
					if (expandUp) {
						$u.css('margin-top',baseline - (menuHeight + offsetTop));
					}
					$u.css('display','none');
				});
			};
		
		return this.each(function() {
			var o = $.fn.superfish.o[this.serial]; /* get this menu's options */
			
			/* if callbacks already set, store them */
			var _onInit = o.onInit,
				_onBeforeShow = o.onBeforeShow,
				_onHide = o.onHide;
				
			$.extend($.fn.superfish.o[this.serial],{
				onInit		: function() {
					onInit.call(this); /* fire our Supposition callback */
					_onInit.call(this); /* fire stored callbacks */
				},
				onBeforeShow: function() {
					onBeforeShow.call(this); /* fire our Supposition callback */
					_onBeforeShow.call(this); /* fire stored callbacks */
				},
				onHide		: function() {
					onHide.call(this); /* fire our Supposition callback */
					_onHide.call(this); /* fire stored callbacks */
				}
			});
		});
	};

})(jQuery);;

/*
 * Supersubs v0.2b - jQuery plugin
 * Copyright (c) 2008 Joel Birch
 *
 * Dual licensed under the MIT and GPL licenses:
 * 	http://www.opensource.org/licenses/mit-license.php
 * 	http://www.gnu.org/licenses/gpl.html
 *
 *
 * This plugin automatically adjusts submenu widths of suckerfish-style menus to that of
 * their longest list item children. If you use this, please expect bugs and report them
 * to the jQuery Google Group with the word 'Superfish' in the subject line.
 *
 */

;(function($){ // $ will refer to jQuery within this closure

	$.fn.supersubs = function(options){
		var opts = $.extend({}, $.fn.supersubs.defaults, options);
		// return original object to support chaining
		return this.each(function() {
			// cache selections
			var $$ = $(this);
			// support metadata
			var o = $.meta ? $.extend({}, opts, $$.data()) : opts;
			// get the font size of menu.
			// .css('fontSize') returns various results cross-browser, so measure an em dash instead
			var fontsize = $('<li id="menu-fontsize">&#8212;</li>').css({
				'padding' : 0,
				'position' : 'absolute',
				'top' : '-999em',
				'width' : 'auto'
			}).appendTo($$).width(); //clientWidth is faster, but was incorrect here
			// remove em dash
			$('#menu-fontsize').remove();
			// cache all ul elements
			$ULs = $$.find('ul');
			// loop through each ul in menu
			$ULs.each(function(i) {	
				// cache this ul
				var $ul = $ULs.eq(i);
				// get all (li) children of this ul
				var $LIs = $ul.children();
				// get all anchor grand-children
				var $As = $LIs.children('a');
				// force content to one line and save current float property
				var liFloat = $LIs.css('white-space','nowrap').css('float');
				// remove width restrictions and floats so elements remain vertically stacked
				var emWidth = $ul.add($LIs).add($As).css({
					'float' : 'none',
					'width'	: 'auto'
				})
				// this ul will now be shrink-wrapped to longest li due to position:absolute
				// so save its width as ems. Clientwidth is 2 times faster than .width() - thanks Dan Switzer
				.end().end()[0].clientWidth / fontsize;
				// add more width to ensure lines don't turn over at certain sizes in various browsers
				emWidth += o.extraWidth;
				// restrict to at least minWidth and at most maxWidth
				if (emWidth > o.maxWidth)		{ emWidth = o.maxWidth; }
				else if (emWidth < o.minWidth)	{ emWidth = o.minWidth; }
				emWidth += 'em';
				// set ul to width in ems
				$ul.css('width',emWidth);
				// restore li floats to avoid IE bugs
				// set li width to full width of this ul
				// revert white-space to normal
				$LIs.css({
					'float' : liFloat,
					'width' : '100%',
					'white-space' : 'normal'
				})
				// update offset position of descendant ul to reflect new width of parent
				.each(function(){
					var $childUl = $('>ul',this);
					var offsetDirection = $childUl.css('left')!==undefined ? 'left' : 'right';
					$childUl.css(offsetDirection,emWidth);
				});
			});
			
		});
	};
	// expose defaults
	$.fn.supersubs.defaults = {
		minWidth		: 9,		// requires em unit.
		maxWidth		: 25,		// requires em unit.
		extraWidth		: 0			// extra width can ensure lines don't sometimes turn over due to slight browser differences in how they round-off values
	};
	
})(jQuery); // plugin code ends
;

/*
 * Superfish v1.4.8 - jQuery menu widget
 * Copyright (c) 2008 Joel Birch
 *
 * Dual licensed under the MIT and GPL licenses:
 * 	http://www.opensource.org/licenses/mit-license.php
 * 	http://www.gnu.org/licenses/gpl.html
 *
 * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
 */

;(function($){
	$.fn.superfish = function(op){

		var sf = $.fn.superfish,
			c = sf.c,
			$arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')),
			over = function(){
				var $$ = $(this), menu = getMenu($$);
				clearTimeout(menu.sfTimer);
				$$.showSuperfishUl().siblings().hideSuperfishUl();
			},
			out = function(){
				var $$ = $(this), menu = getMenu($$), o = sf.op;
				clearTimeout(menu.sfTimer);
				menu.sfTimer=setTimeout(function(){
					o.retainPath=($.inArray($$[0],o.$path)>-1);
					$$.hideSuperfishUl();
					if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);}
				},o.delay);	
			},
			getMenu = function($menu){
				var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
				sf.op = sf.o[menu.serial];
				return menu;
			},
			addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };
			
		return this.each(function() {
			var s = this.serial = sf.o.length;
			var o = $.extend({},sf.defaults,op);
			o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){
				$(this).addClass([o.hoverClass,c.bcClass].join(' '))
					.filter('li:has(ul)').removeClass(o.pathClass);
			});
			sf.o[s] = sf.op = o;
			
			$('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
				if (o.autoArrows) addArrow( $('>a:first-child',this) );
			})
			.not('.'+c.bcClass)
				.hideSuperfishUl();
			
			var $a = $('a',this);
			$a.each(function(i){
				var $li = $a.eq(i).parents('li');
				$a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});
			});
			o.onInit.call(this);
			
		}).each(function() {
			menuClasses = [c.menuClass];
			if (sf.op.dropShadows  && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass);
			$(this).addClass(menuClasses.join(' '));
		});
	};

	var sf = $.fn.superfish;
	sf.o = [];
	sf.op = {};
	sf.IE7fix = function(){
		var o = sf.op;
		if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined)
			this.toggleClass(sf.c.shadowClass+'-off');
		};
	sf.c = {
		bcClass     : 'sf-breadcrumb',
		menuClass   : 'sf-js-enabled',
		anchorClass : 'sf-with-ul',
		arrowClass  : 'sf-sub-indicator',
		shadowClass : 'sf-shadow'
	};
	sf.defaults = {
		hoverClass	: 'sfHover',
		pathClass	: 'overideThisToUse',
		pathLevels	: 1,
		delay		: 800,
		animation	: {opacity:'show'},
		speed		: 'normal',
		autoArrows	: true,
		dropShadows : true,
		disableHI	: false,		// true disables hoverIntent detection
		onInit		: function(){}, // callback functions
		onBeforeShow: function(){},
		onShow		: function(){},
		onHide		: function(){}
	};
	$.fn.extend({
		hideSuperfishUl : function(){
			var o = sf.op,
				not = (o.retainPath===true) ? o.$path : '';
			o.retainPath = false;
			var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
					.find('>ul').hide().css('visibility','hidden');
			o.onHide.call($ul);
			return this;
		},
		showSuperfishUl : function(){
			var o = sf.op,
				sh = sf.c.shadowClass+'-off',
				$ul = this.addClass(o.hoverClass)
					.find('>ul:hidden').css('visibility','visible');
			sf.IE7fix.call($ul);
			o.onBeforeShow.call($ul);
			$ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); });
			return this;
		}
	});

})(jQuery);
;

Drupal.behaviors.fusionEqualheights = function (context) {
  if (jQuery().equalHeights) {
    $("#header-top-wrapper div.equal-heights div.content").equalHeights();
    $("#header-group-wrapper div.equal-heights div.content").equalHeights();
    $("#preface-top-wrapper div.equal-heights div.content").equalHeights();
    $("#preface-bottom div.equal-heights div.content").equalHeights();
    $("#sidebar-first div.equal-heights div.content").equalHeights();
    $("#content-top div.equal-heights div.content").equalHeights();
    $("#content-region div.equal-heights div.content").equalHeights();
    $("#content-bottom div.equal-heights div.content").equalHeights();
    $("#node-top div.equal-heights div.content").equalHeights();
    $("#node-bottom div.equal-heights div.content").equalHeights();
    $("#sidebar-last div.equal-heights div.content").equalHeights();
    $("#postscript-top div.equal-heights div.content").equalHeights();
    $("#postscript-bottom-wrapper div.equal-heights div.content").equalHeights();
    $("#footer-wrapper div.equal-heights div.content").equalHeights();
  }
};

Drupal.behaviors.fusionIE6fixes = function (context) {
  // IE6 & less-specific functions
  // Add hover class to primary menu li elements on hover
  if ($.browser.msie && ($.browser.version < 7)) {
    $('form input.form-submit').hover(function() {
      $(this).addClass('hover');
      }, function() {
        $(this).removeClass('hover');
    });
    $('#primary-menu ul.sf-menu li.expanded').hover(function() {
      $(this).addClass('hover');
      }, function() {
        $(this).removeClass('hover');
    });
    $('.sf-menu li').hover(function() {
      $(this).addClass('hover');
      }, function() {
        $(this).removeClass('hover');
    });
    $('#search input#search_header').hover(function() {
      $(this).addClass('hover');
      }, function() {
        $(this).removeClass('hover');
    });
  };
};

Drupal.behaviors.fusionOverlabel = function (context) {
  if (jQuery().overlabel) {
    $("div.fusion-horiz-login label").overlabel();
  }
};

Drupal.behaviors.fusionSuperfish = function (context) {
  $("#primary-menu ul.sf-menu").superfish({
    hoverClass:  'sfHover',
    delay:       250,
    animation:   {opacity:'show',height:'show'},
    speed:       'fast',
    autoArrows:  false,
    dropShadows: false,
    disableHI:   true
  }).supposition();
};

Drupal.behaviors.fusionSuperfishBlocks = function (context) {
  $("div.block ul.sf-menu").superfish({
    hoverClass:  'sfHover',
    delay:       250,
    animation:   {opacity:'show',height:'show'},
    speed:       'fast',
    autoArrows:  false,
    dropShadows: false,
    disableHI:   true
  }).supposition();
};

Drupal.behaviors.fusionGridMask = function (context) {
  if ($('body.grid-mask-enabled').size() > 0) {
    var grid_width_pos = parseInt($('body').attr('class').indexOf('grid-width-')) + 11;
    var grid_width = $('body').attr('class').substring(grid_width_pos, grid_width_pos + 2);
    var grid = '<div id="grid-mask-overlay" class="full-width"><div class="row">';
    for (i = 1; i <= grid_width; i++) {
      grid += '<div class="block grid' + grid_width + '-1"><div class="inner"></div></div>';
    }
    grid += '</div></div>';
    $('body.grid-mask-enabled').prepend(grid);
    $('#grid-mask-overlay .row').addClass('grid' + grid_width + '-' + grid_width);
    $('#grid-mask-overlay .block .inner').height($('body').height());
  }
};

Drupal.behaviors.fusionGridMaskToggle = function (context) {
  if ($('body.grid-mask-enabled').size() > 0) {
    $('body.grid-mask-enabled').prepend('<div id="grid-mask-toggle">grid</div>');
    $('div#grid-mask-toggle')
      .toggle( function () {
        $(this).toggleClass('grid-on');
        $('body').toggleClass('grid-mask');
      },
      function() {
        $(this).toggleClass('grid-on');
        $('body').toggleClass('grid-mask');
      });
  }
};

Drupal.behaviors.fusionPanelsShowEdit = function (context) {
  // Sets parent row and block elements to have "overflow: visible" if editing Panel page
  if ($("#panels-edit-display-form").size() > 0 || $("#page-manager-edit").size() > 0) {
    $("#panels-edit-display-form").parents('.row, .block').css("overflow", "visible");
    $("#page-manager-edit").parents('.row, .block').css("overflow", "visible");
  }
};

Drupal.behaviors.fusionScreenshotpreview = function (context) {
  // Displays Skinr previews
  if ($('span.preview-icon').size() > 0) {
    // configure distance of preview from the cursor
    var xOffset = 20;
    var yOffset = 0;
  
    $('span.preview-icon').hover(function(e){
      var img_class = this.id;
      var caption = $(this).parent().text();
      // add preview markup
      $('body').append('<div id="screenshot">' +
                       '<div class="screenshot-preview ' + img_class + '" alt="preview"></div>' + 
                       '<div class="screenshot-caption">' + caption + '</div>' +
                       '</div>');
      $("#screenshot").hide();  // hide preview until dimensions are set
      $("#screenshot").css("left", (e.pageX + xOffset) + "px").css("top", (e.pageY + yOffset) + "px");  // set initial preview position
      // load image in order to set preview dimensions
      var img = new Image();
      img.onload = function() {
        var caption_height = parseFloat($("#screenshot .screenshot-caption").css("height"));
        $("#screenshot").css("height", img.height + caption_height);
        $("#screenshot").css("width", img.width);
        $("#screenshot ." + img_class).css("height", img.height);
        $("#screenshot ." + img_class).css("width", img.width);
        $("#screenshot .screenshot-caption").css("width", img.width - 10);
        $("#screenshot").fadeIn("fast");  // now show preview
      }
      img.src = $("." + img_class).css("background-image").replace(/^url|[\(\)\"]/g, '');
    },
    function(){
      $("#screenshot").remove();
    });
    // adjust preview position with cursor movement
    $("span.preview-icon").mousemove(function(e){
      $("#screenshot").css("left", (e.pageX + xOffset) + "px").css("top", (e.pageY + yOffset) + "px");
    });
  }
};
;
// $Id: mix_and_match_script.js,v 1.1 2010/12/05 19:50:42 aross Exp $

Drupal.behaviors.mix_and_matchSuperfish = function (context) {
  $("#primary-menu ul.sf-menu").superfish({
    hoverClass:  'sfHover',
    delay:  250,
    animation:   {opacity:'show',height:'show'},
    speed: 'fast',
    autoArrows: false,
    dropShadows: false,
    disableHI:   true
  }).supposition();
};


;

