/*
 * 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>';
  }
};
;
Drupal.locale = { 'pluralFormula': function($n) { return Number(($n!=1)); }, 'strings': { "Unspecified error": "Uspecificeret fejl", "Group node": "Gruppe-indholdselement", "Tools": "Tools", "Translate Text": "Oversæt tekst", "An HTTP error @status occured.": "Der opstod en HTTP @status-fejl.", "Drag to re-order": "Træk for at (om)sortere", "Changes made in this table will not be saved until the form is submitted.": "Ændringer i tabellen bliver ikke gemt, før du indsender formularen.", "This field is required.": "Feltet er påkrævet.", "!title: !required": "!title: !required", "Automatic alias": "Automatisk alias", "Alias: @alias": "Alias: @alias", "No alias": "Intet alias", "The selected file %filename cannot be uploaded. Only files with the following extensions are allowed: %extensions.": "Den valgte fil %filename kan ikke uploades. Kun filer med følgende endelser er tilladt: %extensions.", "Select all rows in this table": "Vælg alle rækker i tabellen", "Deselect all rows in this table": "Fravælg alle rækker i tabellen", "jQuery UI Tabs: Mismatching fragment identifier.": "jQuery UI Tabs: Uoverensstemmelse i fragmentidentifikator.", "jQuery UI Tabs: Not enough arguments to add tab.": "jQuery UI Tabs: Ikke nok argumenter til at tilføje fane.", "Internal server error. Please see server or PHP logs for error information.": "Intern serverfejl. Kig venligst i server- eller PHP-logfilerne for fejloplysninger.", "Split summary at cursor": "Del sammendrag ved markør", "Join summary": "Saml sammendrag", "The changes to these blocks will not be saved until the \x3cem\x3eSave blocks\x3c/em\x3e button is clicked.": "Ændringerne bliver ikke gemt før du trykker på knappen \x3cem\x3eGem blokke\x3c/em\x3e.", "Your server has been successfully tested to support this feature.": "Din server understøtter denne funktionalitet.", "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.": "Din system-konfiguration understøtter ikke denne funktionalitet. \x3ca href=\"http://drupal.org/node/15365\"\x3eHåndbogens side om rene URLer\x3c/a\x3e har yderligere hjælp til fejlfinding.", "Testing clean URLs...": "Tester rene URLer…", "Edit": "Rediger", "An error occurred. \n@uri\n@text": "Der opstod en fejl. \n@uri\n@text", "An error occurred. \n@uri\n(no information available).": "Der opstod en fejl. \n@uri\n(ingen information tilgængelig).", "An HTTP error @status occurred. \n@uri": "Der opstod en HTTP-fejl @status. \n@uri", "Logout": "Log ud", "Are you sure you want to remove this item?": "Er du sikker på at du vil fjerne dette objekt?" } };;
// $Id: fbconnect.js,v 1.6.2.4 2010/10/08 11:42:49 vectoroc Exp $

Drupal.fbconnect = Drupal.fbconnect || {};
Drupal.fbconnect.init = function () {
  Drupal.behaviors.fbconnect = function(context) {
    if (context != document) {
      jQuery(context).each(function() { FB.XFBML.parse(this); });
    }
    Drupal.fbconnect.initLogoutLinks(context);
  }
  
  if (Drupal.settings.fbconnect.loginout_mode == 'auto') {
    FB.Event.subscribe('auth.sessionChange', Drupal.fbconnect.reload_ifUserConnected);
//    FB.Event.subscribe('auth.login', function(response) {
//      console.log('event auth.login');
//    });
  }
  
  Drupal.behaviors.fbconnect(document);
}

Drupal.fbconnect.logout = function(keep_fbaccount_logged) {
  var logout_url = Drupal.settings.basePath + 'logout'; 
  
  if (!keep_fbaccount_logged) {
    FB.logout(function(response) { 
      window.location.href = logout_url; 
    });
  }
  else {
    window.location.href = logout_url;
  }
}

Drupal.fbconnect.reload_ifUserConnected = function(state) {
  var user = Drupal.settings.fbconnect.user;
  
  if (!state.session || user.uid) return;
  if (state.session.uid != user.fbuid) {
    window.location.reload();
  }
};

Drupal.fbconnect.initLogoutLinks = function(context) {
  var loginout_mode = Drupal.settings.fbconnect.loginout_mode;
  var user          = Drupal.settings.fbconnect.user;
  var basePath      = Drupal.settings.basePath;
  var logout_url    = basePath + 'logout'; 
  var links         = $('a[href='+ logout_url +']', context).not('.logout_link_inited');
  
  if (loginout_mode == 'manual') return;
  
  links.addClass('logout_link_inited').click(function() {
    var fbuid = FB.getSession() && FB.getSession().uid;
    if (!user.fbuid || user.fbuid != fbuid) return;
    if (loginout_mode == 'auto') { 
      Drupal.fbconnect.logout();
    }
    else if (loginout_mode == 'ask') {    
      var t_args  = {'!site_name' : Drupal.settings.fbconnect.invite_name};
      var buttons = [
          { 
            'label': Drupal.t('Facebook and !site_name', t_args), 
            'click': function() {
              this.close();
              Drupal.fbconnect.logout();
            }
          }, {
            'name': 'cancel', 
            'label': Drupal.t('!site_name Only', t_args), 
            'click': function() {
              this.close();
              Drupal.fbconnect.logout(true);
            }
          }              
      ];
    
      var dialog = new Drupal.fbconnect.PopupDialog({
        'title'   : Drupal.t('Logout'),
        'message' : Drupal.t('Do you also want to logout from your Facebook account?'),
        'buttons' : buttons 
      });      
    }
    
    return false;
  });
};

Drupal.fbconnect.DoFastRegistration =  function(link) {
  FB.login(function(response) {
    if (response.session && /email/.test(response.perms)) {
      window.location.href = link.href;
    }
  }, {perms:'email'});
};


function facebook_onlogin_ready() {
  // http://github.com/facebook/connect-js/issues/194
  if (!FB.getSession()) {
    return;
  }
  $("#fbconnect-autoconnect-form").submit();
}

/**
 * Create a dialog. 
 *
 * @param opts {Object} Options:
 * @see Drupal.fbconnect.PopupDialog.prototype.prepareDefaults
 *
 * @return {Object}
 */
Drupal.fbconnect.PopupDialog = function(options) {
  this.prepareDefaults(options);
  this.container = Drupal.theme('fb_popup_dialog', this.options);  
  this.dialog = FB.Dialog.create({
    content : this.container,
    visible : false,
    loader  : true,
    onClose : this.__close_handler,
    closeIcon : true
  });
  
//  FB.XFBML.parse(dialog);
  
//  var popup = new FB.UI.PopupDialog(
//    oThis.options.title, 
//    oThis.container, 
//    oThis.options.showLoading,
//    oThis.options.hideUntilLoaded
//  );
  
  this.callback('load', this.dialog);
};

Drupal.fbconnect.PopupDialog.prototype.options = {};

Drupal.fbconnect.PopupDialog.prototype.createHandler = function(event, data) {
  var oThis = this;
  return function() { oThis.callback(event, data); };
};

Drupal.fbconnect.PopupDialog.prototype.callback = function(event, data) {
  data = data || {};
  switch (event) {
  case 'click':
    var btn = data;
    if (btn.click instanceof Function) btn.click.apply(this, [btn]);
    else if (btn.name == 'cancel') this.close();
    break;
    
  case 'close':
    var btn = this.findButton('cancel'); 
    if (btn) this.callback('click', btn);
    break;
    
  case 'load':
    this.show();
    break;
  }
};

Drupal.fbconnect.PopupDialog.prototype.prepareDefaults = function(options) {
  var defaults = {
    'title'           : '',
    'message'         : ' - ',
    'buttons'         : {},
    'showLoading'     : false,
    'hideUntilLoaded' : false
  };  
  $.extend(this.options, defaults, options);
  
  this.__close_handler = this.createHandler('close', {});
  this.options.dialog = this; 
  if (this.options.callback instanceof Function) {
    this.callback = this.options.callback;
  }
};

Drupal.fbconnect.PopupDialog.prototype.show = function() {
  if (this.dialog) {    
    FB.Dialog.show(this.dialog);
  }
};

Drupal.fbconnect.PopupDialog.prototype.close = function() {
  if (this.dialog) {
    FB.Dialog.remove(this.dialog);
  }
};

Drupal.fbconnect.PopupDialog.prototype.findButton = function(name) {
  var button = null;
  jQuery.each(this.options.buttons, function(i, btn) {
    if (btn.name == name) {
      button = btn;
      return true;
    }
  });
  
  return button;
}

Drupal.theme.prototype.fb_popup_dialog_buttons = function(buttons, dialog) {
  buttons = buttons || {};
  var container = $('<div class="dialog_buttons"></div>');
  
  jQuery.each(buttons, function(i, btn) {
    var button = $('<input type="button" class="dialog_inputbutton">');
    if (!btn['name']) btn['name'] = i;
    if (btn.attr) button.attr(btn.attr);
    if (btn['class']) button.addClass(btn['class']);
    if (btn['name'] == 'cancel') button.addClass('dialog_inputaux');
    button.addClass('fb_button_' + i);
    button.attr('value', btn.label);
    button.click(dialog.createHandler('click', btn));
    button.appendTo(container);
  });
    
  return container.get(0);
};

Drupal.theme.prototype.fb_popup_dialog = function(options) {
  options = options || {buttons:{}};
  var container = document.createDocumentFragment();
  var elements  =  [
     '<h2 class="dialog_header"><span>',
    options.title.toString(),
    '</span></h2>',
       '<div class="dialog_stripes"></div>',
    '<div class="dialog_content">',
    options.message.toString(),
    '</div>'
  ];
  
  $(elements.join("\n")).each(function() {
    container.appendChild(this);
  });
  if (options.buttons) {
    container.appendChild(
      Drupal.theme('fb_popup_dialog_buttons', options.buttons, options.dialog)
    );
  }

  return container;
};


Drupal.theme.prototype.fbml_name = function(fbuid, options) {
  var output = ['<fb:name uid="', fbuid, '"'];
  var defaults = {
    'useyou' : false,
    'linked' : false
  };
  
  options = $.extend({}, defaults, options);
  
  output.push('" useyou="'+ (!!options.useyou ? 'true' : 'false') +'"');
  output.push('" linked="'+ (!!options.linked ? 'true' : 'false') +'"');
  output.push('></fb:name>');
  
  return output.join('');
};

Drupal.theme.prototype.fbml_profile_pic = function(fbuid, options) {
  var output = ['<fb:profile-pic uid="', fbuid, '"'];
  options = options || {};
  
  if (options.width)  output.push('" width="'+ options.width +'"');
  if (options.height) output.push('" height="'+ options.height +'"');
  if (options.size)   output.push('" size="'+ options.size +'"');
  
  output.push('" facebook-logo="'+ (!!options['facebook-logo'] ? 'true' : 'false') +'"')
  output.push('" linked="'+ (!!options.linked ? 'true' : 'false') +'"');  
  output.push('></fb:profile-pic>');
  
  return output.join('');
};

jQuery(document).bind('fb:init', Drupal.fbconnect.init);;
// $Id: og.js,v 1.9.2.3 2010/01/24 14:44:56 amitaibu Exp $

// Content type form
Drupal.behaviors.og_content_type = function() {
  // Disable the group limit textarea if the content type is not a standard group post
  $('input[name="og_content_type_usage"]').click(function(){
    if (!$('#edit-og-content-type-usage-group-post-standard').attr('checked')) {
      $('#edit-og-max-groups').attr('disabled','disabled');
    } else {
      $('#edit-og-max-groups').removeAttr('disabled');
    }
  });
  
  // Initial check to see if content type is standard group post
  if (!$('#edit-og-content-type-usage-group-post-standard').attr('checked')) {
    $('#edit-og-max-groups').attr('disabled','disabled');
  };
}


Drupal.verticalTabs = Drupal.verticalTabs || {};

Drupal.verticalTabs.og_nodeapi = function() {
  var values = [];
  $('.vertical-tabs-og_nodeapi #edit-og-groups :selected')
    .each(function (i, selected) {
      values[i] = $(selected).text();
    });

  return values.join(', ');
}

Drupal.verticalTabs.og = function() {
  var type = $('.vertical-tabs-og input[type=radio]:checked').val();
  
  switch (type) {
    case 'group':
      return Drupal.t('Group node');
      break;
      
    case 'omitted':
      return Drupal.t('May not be posted into a group.');
      break;
      
    case 'group_post_standard':
      return Drupal.t('Standard group post');
      break;
      
    case 'group_post_wiki':
      return Drupal.t('Wiki group post');
      break;
  }
}
;
// $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
  
/**
 * 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
  };

})();
;
/*
 * FancyBox - jQuery Plugin
 * Simple and fancy lightbox alternative
 *
 * Examples and documentation at: http://fancybox.net
 * 
 * Copyright (c) 2008 - 2010 Janis Skarnelis
 *
 * Version: 1.3.1 (05/03/2010)
 * Requires: jQuery v1.3+
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

(function($) {

	var tmp, loading, overlay, wrap, outer, inner, close, nav_left, nav_right,

		selectedIndex = 0, selectedOpts = {}, selectedArray = [], currentIndex = 0, currentOpts = {}, currentArray = [],

		ajaxLoader = null, imgPreloader = new Image(), imgRegExp = /\.(jpg|gif|png|bmp|jpeg)(.*)?$/i, swfRegExp = /[^\.]\.(swf)\s*$/i,

		loadingTimer, loadingFrame = 1,

		start_pos, final_pos, busy = false, shadow = 20, fx = $.extend($('<div/>')[0], { prop: 0 }), titleh = 0, 

		isIE6 = !$.support.opacity && !window.XMLHttpRequest,

		/*
		 * Private methods 
		 */

		fancybox_abort = function() {
			loading.hide();

			imgPreloader.onerror = imgPreloader.onload = null;

			if (ajaxLoader) {
				ajaxLoader.abort();
			}

			tmp.empty();
		},

		fancybox_error = function() {
			$.fancybox('<p id="fancybox_error">The requested content cannot be loaded.<br />Please try again later.</p>', {
				'scrolling'		: 'no',
				'padding'		: 20,
				'transitionIn'	: 'none',
				'transitionOut'	: 'none'
			});
		},

		fancybox_get_viewport = function() {
			return [ $(window).width(), $(window).height(), $(document).scrollLeft(), $(document).scrollTop() ];
		},

		fancybox_get_zoom_to = function () {
			var view	= fancybox_get_viewport(),
				to		= {},

				margin = currentOpts.margin,
				resize = currentOpts.autoScale,

				horizontal_space	= (shadow + margin) * 2,
				vertical_space		= (shadow + margin) * 2,
				double_padding		= (currentOpts.padding * 2),
				
				ratio;

			if (currentOpts.width.toString().indexOf('%') > -1) {
				to.width = ((view[0] * parseFloat(currentOpts.width)) / 100) - (shadow * 2) ;
				resize = false;

			} else {
				to.width = currentOpts.width + double_padding;
			}

			if (currentOpts.height.toString().indexOf('%') > -1) {
				to.height = ((view[1] * parseFloat(currentOpts.height)) / 100) - (shadow * 2);
				resize = false;

			} else {
				to.height = currentOpts.height + double_padding;
			}

			if (resize && (to.width > (view[0] - horizontal_space) || to.height > (view[1] - vertical_space))) {
				if (selectedOpts.type == 'image' || selectedOpts.type == 'swf') {
					horizontal_space	+= double_padding;
					vertical_space		+= double_padding;

					ratio = Math.min(Math.min( view[0] - horizontal_space, currentOpts.width) / currentOpts.width, Math.min( view[1] - vertical_space, currentOpts.height) / currentOpts.height);

					to.width	= Math.round(ratio * (to.width	- double_padding)) + double_padding;
					to.height	= Math.round(ratio * (to.height	- double_padding)) + double_padding;

				} else {
					to.width	= Math.min(to.width,	(view[0] - horizontal_space));
					to.height	= Math.min(to.height,	(view[1] - vertical_space));
				}
			}

			to.top	= view[3] + ((view[1] - (to.height	+ (shadow * 2 ))) * 0.5);
			to.left	= view[2] + ((view[0] - (to.width	+ (shadow * 2 ))) * 0.5);

			if (currentOpts.autoScale === false) {
				to.top	= Math.max(view[3] + margin, to.top);
				to.left	= Math.max(view[2] + margin, to.left);
			}

			return to;
		},

		fancybox_format_title = function(title) {
			if (title && title.length) {
				switch (currentOpts.titlePosition) {
					case 'inside':
						return title;
					case 'over':
						return '<span id="fancybox-title-over">' + title + '</span>';
					default:
						return '<span id="fancybox-title-wrap"><span id="fancybox-title-left"></span><span id="fancybox-title-main">' + title + '</span><span id="fancybox-title-right"></span></span>';
				}
			}

			return false;
		},

		fancybox_process_title = function() {
			var title	= currentOpts.title,
				width	= final_pos.width - (currentOpts.padding * 2),
				titlec	= 'fancybox-title-' + currentOpts.titlePosition;
				
			$('#fancybox-title').remove();

			titleh = 0;

			if (currentOpts.titleShow === false) {
				return;
			}

			title = $.isFunction(currentOpts.titleFormat) ? currentOpts.titleFormat(title, currentArray, currentIndex, currentOpts) : fancybox_format_title(title);

			if (!title || title === '') {
				return;
			}

			$('<div id="fancybox-title" class="' + titlec + '" />').css({
				'width'			: width,
				'paddingLeft'	: currentOpts.padding,
				'paddingRight'	: currentOpts.padding
			}).html(title).appendTo('body');

			switch (currentOpts.titlePosition) {
				case 'inside':
					titleh = $("#fancybox-title").outerHeight(true) - currentOpts.padding;
					final_pos.height += titleh;
				break;

				case 'over':
					$('#fancybox-title').css('bottom', currentOpts.padding);
				break;

				default:
					$('#fancybox-title').css('bottom', $("#fancybox-title").outerHeight(true) * -1);
				break;
			}

			$('#fancybox-title').appendTo( outer ).hide();
		},

		fancybox_set_navigation = function() {
			$(document).unbind('keydown.fb').bind('keydown.fb', function(e) {
				if (e.keyCode == 27 && currentOpts.enableEscapeButton) {
					e.preventDefault();
					$.fancybox.close();

				} else if (e.keyCode == 37) {
					e.preventDefault();
					$.fancybox.prev();

				} else if (e.keyCode == 39) {
					e.preventDefault();
					$.fancybox.next();
				}
			});

			if ($.fn.mousewheel) {
				wrap.unbind('mousewheel.fb');

				if (currentArray.length > 1) {
					wrap.bind('mousewheel.fb', function(e, delta) {
						e.preventDefault();

						if (busy || delta === 0) {
							return;
						}

						if (delta > 0) {
							$.fancybox.prev();
						} else {
							$.fancybox.next();
						}
					});
				}
			}

			if (!currentOpts.showNavArrows) { return; }

			if ((currentOpts.cyclic && currentArray.length > 1) || currentIndex !== 0) {
				nav_left.show();
			}

			if ((currentOpts.cyclic && currentArray.length > 1) || currentIndex != (currentArray.length -1)) {
				nav_right.show();
			}
		},

		fancybox_preload_images = function() {
			var href, 
				objNext;
				
			if ((currentArray.length -1) > currentIndex) {
				href = currentArray[ currentIndex + 1 ].href;

				if (typeof href !== 'undefined' && href.match(imgRegExp)) {
					objNext = new Image();
					objNext.src = href;
				}
			}

			if (currentIndex > 0) {
				href = currentArray[ currentIndex - 1 ].href;

				if (typeof href !== 'undefined' && href.match(imgRegExp)) {
					objNext = new Image();
					objNext.src = href;
				}
			}
		},

		_finish = function () {
			inner.css('overflow', (currentOpts.scrolling == 'auto' ? (currentOpts.type == 'image' || currentOpts.type == 'iframe' || currentOpts.type == 'swf' ? 'hidden' : 'auto') : (currentOpts.scrolling == 'yes' ? 'auto' : 'visible')));

			if (!$.support.opacity) {
				inner.get(0).style.removeAttribute('filter');
				wrap.get(0).style.removeAttribute('filter');
			}

			$('#fancybox-title').show();

			if (currentOpts.hideOnContentClick)	{
				inner.one('click', $.fancybox.close);
			}
			if (currentOpts.hideOnOverlayClick)	{
				overlay.one('click', $.fancybox.close);
			}

			if (currentOpts.showCloseButton) {
				close.show();
			}

			fancybox_set_navigation();

			$(window).bind("resize.fb", $.fancybox.center);

			if (currentOpts.centerOnScroll) {
				$(window).bind("scroll.fb", $.fancybox.center);
			} else {
				$(window).unbind("scroll.fb");
			}

			if ($.isFunction(currentOpts.onComplete)) {
				currentOpts.onComplete(currentArray, currentIndex, currentOpts);
			}

			busy = false;

			fancybox_preload_images();
		},

		fancybox_draw = function(pos) {
			var width	= Math.round(start_pos.width	+ (final_pos.width	- start_pos.width)	* pos),
				height	= Math.round(start_pos.height	+ (final_pos.height	- start_pos.height)	* pos),

				top		= Math.round(start_pos.top	+ (final_pos.top	- start_pos.top)	* pos),
				left	= Math.round(start_pos.left	+ (final_pos.left	- start_pos.left)	* pos);

			wrap.css({
				'width'		: width		+ 'px',
				'height'	: height	+ 'px',
				'top'		: top		+ 'px',
				'left'		: left		+ 'px'
			});

			width	= Math.max(width - currentOpts.padding * 2, 0);
			height	= Math.max(height - (currentOpts.padding * 2 + (titleh * pos)), 0);

			inner.css({
				'width'		: width		+ 'px',
				'height'	: height	+ 'px'
			});

			if (typeof final_pos.opacity !== 'undefined') {
				wrap.css('opacity', (pos < 0.5 ? 0.5 : pos));
			}
		},

		fancybox_get_obj_pos = function(obj) {
			var pos		= obj.offset();

			pos.top		+= parseFloat( obj.css('paddingTop') )	|| 0;
			pos.left	+= parseFloat( obj.css('paddingLeft') )	|| 0;

			pos.top		+= parseFloat( obj.css('border-top-width') )	|| 0;
			pos.left	+= parseFloat( obj.css('border-left-width') )	|| 0;

			pos.width	= obj.width();
			pos.height	= obj.height();

			return pos;
		},

		fancybox_get_zoom_from = function() {
			var orig = selectedOpts.orig ? $(selectedOpts.orig) : false,
				from = {},
				pos,
				view;

			if (orig && orig.length) {
				pos = fancybox_get_obj_pos(orig);

				from = {
					width	: (pos.width	+ (currentOpts.padding * 2)),
					height	: (pos.height	+ (currentOpts.padding * 2)),
					top		: (pos.top		- currentOpts.padding - shadow),
					left	: (pos.left		- currentOpts.padding - shadow)
				};
				
			} else {
				view = fancybox_get_viewport();

				from = {
					width	: 1,
					height	: 1,
					top		: view[3] + view[1] * 0.5,
					left	: view[2] + view[0] * 0.5
				};
			}

			return from;
		},

		fancybox_show = function() {
			loading.hide();

			if (wrap.is(":visible") && $.isFunction(currentOpts.onCleanup)) {
				if (currentOpts.onCleanup(currentArray, currentIndex, currentOpts) === false) {
					$.event.trigger('fancybox-cancel');

					busy = false;
					return;
				}
			}

			currentArray	= selectedArray;
			currentIndex	= selectedIndex;
			currentOpts		= selectedOpts;

			inner.get(0).scrollTop	= 0;
			inner.get(0).scrollLeft	= 0;

			if (currentOpts.overlayShow) {
				if (isIE6) {
					$('select:not(#fancybox-tmp select)').filter(function() {
						return this.style.visibility !== 'hidden';
					}).css({'visibility':'hidden'}).one('fancybox-cleanup', function() {
						this.style.visibility = 'inherit';
					});
				}

				overlay.css({
					'background-color'	: currentOpts.overlayColor,
					'opacity'			: currentOpts.overlayOpacity
				}).unbind().show();
			}

			final_pos = fancybox_get_zoom_to();

			fancybox_process_title();

			if (wrap.is(":visible")) {
				$( close.add( nav_left ).add( nav_right ) ).hide();

				var pos = wrap.position(),
					equal;

				start_pos = {
					top		:	pos.top ,
					left	:	pos.left,
					width	:	wrap.width(),
					height	:	wrap.height()
				};

				equal = (start_pos.width == final_pos.width && start_pos.height == final_pos.height);

				inner.fadeOut(currentOpts.changeFade, function() {
					var finish_resizing = function() {
						inner.html( tmp.contents() ).fadeIn(currentOpts.changeFade, _finish);
					};
					
					$.event.trigger('fancybox-change');

					inner.empty().css('overflow', 'hidden');

					if (equal) {
						inner.css({
							top			: currentOpts.padding,
							left		: currentOpts.padding,
							width		: Math.max(final_pos.width	- (currentOpts.padding * 2), 1),
							height		: Math.max(final_pos.height	- (currentOpts.padding * 2) - titleh, 1)
						});
						
						finish_resizing();

					} else {
						inner.css({
							top			: currentOpts.padding,
							left		: currentOpts.padding,
							width		: Math.max(start_pos.width	- (currentOpts.padding * 2), 1),
							height		: Math.max(start_pos.height	- (currentOpts.padding * 2), 1)
						});
						
						fx.prop = 0;

						$(fx).animate({ prop: 1 }, {
							 duration	: currentOpts.changeSpeed,
							 easing		: currentOpts.easingChange,
							 step		: fancybox_draw,
							 complete	: finish_resizing
						});
					}
				});

				return;
			}

			wrap.css('opacity', 1);

			if (currentOpts.transitionIn == 'elastic') {
				start_pos = fancybox_get_zoom_from();

				inner.css({
						top			: currentOpts.padding,
						left		: currentOpts.padding,
						width		: Math.max(start_pos.width	- (currentOpts.padding * 2), 1),
						height		: Math.max(start_pos.height	- (currentOpts.padding * 2), 1)
					})
					.html( tmp.contents() );

				wrap.css(start_pos).show();

				if (currentOpts.opacity) {
					final_pos.opacity = 0;
				}

				fx.prop = 0;

				$(fx).animate({ prop: 1 }, {
					 duration	: currentOpts.speedIn,
					 easing		: currentOpts.easingIn,
					 step		: fancybox_draw,
					 complete	: _finish
				});

			} else {
				inner.css({
						top			: currentOpts.padding,
						left		: currentOpts.padding,
						width		: Math.max(final_pos.width	- (currentOpts.padding * 2), 1),
						height		: Math.max(final_pos.height	- (currentOpts.padding * 2) - titleh, 1)
					})
					.html( tmp.contents() );

				wrap.css( final_pos ).fadeIn( currentOpts.transitionIn == 'none' ? 0 : currentOpts.speedIn, _finish );
			}
		},

		fancybox_process_inline = function() {
			tmp.width(	selectedOpts.width );
			tmp.height(	selectedOpts.height );

			if (selectedOpts.width	== 'auto') {
				selectedOpts.width = tmp.width();
			}
			if (selectedOpts.height	== 'auto') {
				selectedOpts.height	= tmp.height();
			}

			fancybox_show();
		},
		
		fancybox_process_image = function() {
			busy = true;

			selectedOpts.width	= imgPreloader.width;
			selectedOpts.height	= imgPreloader.height;

			$("<img />").attr({
				'id'	: 'fancybox-img',
				'src'	: imgPreloader.src,
				'alt'	: selectedOpts.title
			}).appendTo( tmp );

			fancybox_show();
		},

		fancybox_start = function() {
			fancybox_abort();

			var obj	= selectedArray[ selectedIndex ],
				href, 
				type, 
				title,
				str,
				emb,
				selector,
				data;

			selectedOpts = $.extend({}, $.fn.fancybox.defaults, (typeof $(obj).data('fancybox') == 'undefined' ? selectedOpts : $(obj).data('fancybox')));
			title = obj.title || $(obj).title || selectedOpts.title || '';
			
			if (obj.nodeName && !selectedOpts.orig) {
				selectedOpts.orig = $(obj).children("img:first").length ? $(obj).children("img:first") : $(obj);
			}

			if (title === '' && selectedOpts.orig) {
				title = selectedOpts.orig.attr('alt');
			}

			if (obj.nodeName && (/^(?:javascript|#)/i).test(obj.href)) {
				href = selectedOpts.href || null;
			} else {
				href = selectedOpts.href || obj.href || null;
			}

			if (selectedOpts.type) {
				type = selectedOpts.type;

				if (!href) {
					href = selectedOpts.content;
				}
				
			} else if (selectedOpts.content) {
				type	= 'html';

			} else if (href) {
				if (href.match(imgRegExp)) {
					type = 'image';

				} else if (href.match(swfRegExp)) {
					type = 'swf';

				} else if ($(obj).hasClass("iframe")) {
					type = 'iframe';

				} else if (href.match(/#/)) {
					obj = href.substr(href.indexOf("#"));

					type = $(obj).length > 0 ? 'inline' : 'ajax';
				} else {
					type = 'ajax';
				}
			} else {
				type = 'inline';
			}

			selectedOpts.type	= type;
			selectedOpts.href	= href;
			selectedOpts.title	= title;

			if (selectedOpts.autoDimensions && selectedOpts.type !== 'iframe' && selectedOpts.type !== 'swf') {
				selectedOpts.width		= 'auto';
				selectedOpts.height		= 'auto';
			}

			if (selectedOpts.modal) {
				selectedOpts.overlayShow		= true;
				selectedOpts.hideOnOverlayClick	= false;
				selectedOpts.hideOnContentClick	= false;
				selectedOpts.enableEscapeButton	= false;
				selectedOpts.showCloseButton	= false;
			}

			if ($.isFunction(selectedOpts.onStart)) {
				if (selectedOpts.onStart(selectedArray, selectedIndex, selectedOpts) === false) {
					busy = false;
					return;
				}
			}

			tmp.css('padding', (shadow + selectedOpts.padding + selectedOpts.margin));

			$('.fancybox-inline-tmp').unbind('fancybox-cancel').bind('fancybox-change', function() {
				$(this).replaceWith(inner.children());
			});

			switch (type) {
				case 'html' :
					tmp.html( selectedOpts.content );
					fancybox_process_inline();
				break;

				case 'inline' :
					$('<div class="fancybox-inline-tmp" />').hide().insertBefore( $(obj) ).bind('fancybox-cleanup', function() {
						$(this).replaceWith(inner.children());
					}).bind('fancybox-cancel', function() {
						$(this).replaceWith(tmp.children());
					});

					$(obj).appendTo(tmp);

					fancybox_process_inline();
				break;

				case 'image':
					busy = false;

					$.fancybox.showActivity();

					imgPreloader = new Image();

					imgPreloader.onerror = function() {
						fancybox_error();
					};

					imgPreloader.onload = function() {
						imgPreloader.onerror = null;
						imgPreloader.onload = null;
						fancybox_process_image();
					};

					imgPreloader.src = href;
		
				break;

				case 'swf':
					str = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' + selectedOpts.width + '" height="' + selectedOpts.height + '"><param name="movie" value="' + href + '"></param>';
					emb = '';
					
					$.each(selectedOpts.swf, function(name, val) {
						str += '<param name="' + name + '" value="' + val + '"></param>';
						emb += ' ' + name + '="' + val + '"';
					});

					str += '<embed src="' + href + '" type="application/x-shockwave-flash" width="' + selectedOpts.width + '" height="' + selectedOpts.height + '"' + emb + '></embed></object>';

					tmp.html(str);

					fancybox_process_inline();
				break;

				case 'ajax':
					selector	= href.split('#', 2);
					data		= selectedOpts.ajax.data || {};

					if (selector.length > 1) {
						href = selector[0];

						if (typeof data == "string") {
							data += '&selector=' + selector[1];
						} else {
							data.selector = selector[1];
						}
					}

					busy = false;
					$.fancybox.showActivity();

					ajaxLoader = $.ajax($.extend(selectedOpts.ajax, {
						url		: href,
						data	: data,
						error	: fancybox_error,
						success : function(data, textStatus, XMLHttpRequest) {
							if (ajaxLoader.status == 200) {
								tmp.html( data );
								fancybox_process_inline();
							}
						}
					}));

				break;

				case 'iframe' :
					$('<iframe id="fancybox-frame" name="fancybox-frame' + new Date().getTime() + '" frameborder="0" hspace="0" scrolling="' + selectedOpts.scrolling + '" src="' + selectedOpts.href + '"></iframe>').appendTo(tmp);
					fancybox_show();
				break;
			}
		},

		fancybox_animate_loading = function() {
			if (!loading.is(':visible')){
				clearInterval(loadingTimer);
				return;
			}

			$('div', loading).css('top', (loadingFrame * -40) + 'px');

			loadingFrame = (loadingFrame + 1) % 12;
		},

		fancybox_init = function() {
			if ($("#fancybox-wrap").length) {
				return;
			}

			$('body').append(
				tmp			= $('<div id="fancybox-tmp"></div>'),
				loading		= $('<div id="fancybox-loading"><div></div></div>'),
				overlay		= $('<div id="fancybox-overlay"></div>'),
				wrap		= $('<div id="fancybox-wrap"></div>')
			);

			if (!$.support.opacity) {
				wrap.addClass('fancybox-ie');
				loading.addClass('fancybox-ie');
			}

			outer = $('<div id="fancybox-outer"></div>')
				.append('<div class="fancy-bg" id="fancy-bg-n"></div><div class="fancy-bg" id="fancy-bg-ne"></div><div class="fancy-bg" id="fancy-bg-e"></div><div class="fancy-bg" id="fancy-bg-se"></div><div class="fancy-bg" id="fancy-bg-s"></div><div class="fancy-bg" id="fancy-bg-sw"></div><div class="fancy-bg" id="fancy-bg-w"></div><div class="fancy-bg" id="fancy-bg-nw"></div>')
				.appendTo( wrap );

			outer.append(
				inner		= $('<div id="fancybox-inner"></div>'),
				close		= $('<a id="fancybox-close"></a>'),

				nav_left	= $('<a href="javascript:;" id="fancybox-left"><span class="fancy-ico" id="fancybox-left-ico"></span></a>'),
				nav_right	= $('<a href="javascript:;" id="fancybox-right"><span class="fancy-ico" id="fancybox-right-ico"></span></a>')
			);

			close.click($.fancybox.close);
			loading.click($.fancybox.cancel);

			nav_left.click(function(e) {
				e.preventDefault();
				$.fancybox.prev();
			});

			nav_right.click(function(e) {
				e.preventDefault();
				$.fancybox.next();
			});

			if (isIE6) {
				overlay.get(0).style.setExpression('height',	"document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'");
				loading.get(0).style.setExpression('top',		"(-20 + (document.documentElement.clientHeight ? document.documentElement.clientHeight/2 : document.body.clientHeight/2 ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop )) + 'px'");

				outer.prepend('<iframe id="fancybox-hide-sel-frame" src="javascript:\'\';" scrolling="no" frameborder="0" ></iframe>');
			}
		};

	/*
	 * Public methods 
	 */

	$.fn.fancybox = function(options) {
		$(this)
			.data('fancybox', $.extend({}, options, ($.metadata ? $(this).metadata() : {})))
			.unbind('click.fb').bind('click.fb', function(e) {
				e.preventDefault();

				if (busy) {
					return;
				}

				busy = true;

				$(this).blur();

				selectedArray	= [];
				selectedIndex	= 0;

				var rel = $(this).attr('rel') || '';

				if (!rel || rel == '' || rel === 'nofollow') {
					selectedArray.push(this);

				} else {
					selectedArray	= $("a[rel=" + rel + "], area[rel=" + rel + "]");
					selectedIndex	= selectedArray.index( this );
				}

				fancybox_start();

				return false;
			});

		return this;
	};

	$.fancybox = function(obj) {
		if (busy) {
			return;
		}

		busy = true;

		var opts = typeof arguments[1] !== 'undefined' ? arguments[1] : {};

		selectedArray	= [];
		selectedIndex	= opts.index || 0;

		if ($.isArray(obj)) {
			for (var i = 0, j = obj.length; i < j; i++) {
				if (typeof obj[i] == 'object') {
					$(obj[i]).data('fancybox', $.extend({}, opts, obj[i]));
				} else {
					obj[i] = $({}).data('fancybox', $.extend({content : obj[i]}, opts));
				}
			}

			selectedArray = jQuery.merge(selectedArray, obj);

		} else {
			if (typeof obj == 'object') {
				$(obj).data('fancybox', $.extend({}, opts, obj));
			} else {
				obj = $({}).data('fancybox', $.extend({content : obj}, opts));
			}

			selectedArray.push(obj);
		}

		if (selectedIndex > selectedArray.length || selectedIndex < 0) {
			selectedIndex = 0;
		}

		fancybox_start();
	};

	$.fancybox.showActivity = function() {
		clearInterval(loadingTimer);

		loading.show();
		loadingTimer = setInterval(fancybox_animate_loading, 66);
	};

	$.fancybox.hideActivity = function() {
		loading.hide();
	};

	$.fancybox.next = function() {
		return $.fancybox.pos( currentIndex + 1);
	};
	
	$.fancybox.prev = function() {
		return $.fancybox.pos( currentIndex - 1);
	};

	$.fancybox.pos = function(pos) {
		if (busy) {
			return;
		}

		pos = parseInt(pos, 10);

		if (pos > -1 && currentArray.length > pos) {
			selectedIndex = pos;
			fancybox_start();
		}

		if (currentOpts.cyclic && currentArray.length > 1 && pos < 0) {
			selectedIndex = currentArray.length - 1;
			fancybox_start();
		}

		if (currentOpts.cyclic && currentArray.length > 1 && pos >= currentArray.length) {
			selectedIndex = 0;
			fancybox_start();
		}

		return;
	};

	$.fancybox.cancel = function() {
		if (busy) {
			return;
		}

		busy = true;

		$.event.trigger('fancybox-cancel');

		fancybox_abort();

		if (selectedOpts && $.isFunction(selectedOpts.onCancel)) {
			selectedOpts.onCancel(selectedArray, selectedIndex, selectedOpts);
		}

		busy = false;
	};

	// Note: within an iframe use - parent.$.fancybox.close();
	$.fancybox.close = function() {
		if (busy || wrap.is(':hidden')) {
			return;
		}

		busy = true;

		if (currentOpts && $.isFunction(currentOpts.onCleanup)) {
			if (currentOpts.onCleanup(currentArray, currentIndex, currentOpts) === false) {
				busy = false;
				return;
			}
		}

		fancybox_abort();

		$(close.add( nav_left ).add( nav_right )).hide();

		$('#fancybox-title').remove();

		wrap.add(inner).add(overlay).unbind();

		$(window).unbind("resize.fb scroll.fb");
		$(document).unbind('keydown.fb');

		function _cleanup() {
			overlay.fadeOut('fast');

			wrap.hide();

			$.event.trigger('fancybox-cleanup');

			inner.empty();

			if ($.isFunction(currentOpts.onClosed)) {
				currentOpts.onClosed(currentArray, currentIndex, currentOpts);
			}

			currentArray	= selectedOpts	= [];
			currentIndex	= selectedIndex	= 0;
			currentOpts		= selectedOpts	= {};

			busy = false;
		}

		inner.css('overflow', 'hidden');

		if (currentOpts.transitionOut == 'elastic') {
			start_pos = fancybox_get_zoom_from();

			var pos = wrap.position();

			final_pos = {
				top		:	pos.top ,
				left	:	pos.left,
				width	:	wrap.width(),
				height	:	wrap.height()
			};

			if (currentOpts.opacity) {
				final_pos.opacity = 1;
			}

			fx.prop = 1;

			$(fx).animate({ prop: 0 }, {
				 duration	: currentOpts.speedOut,
				 easing		: currentOpts.easingOut,
				 step		: fancybox_draw,
				 complete	: _cleanup
			});

		} else {
			wrap.fadeOut( currentOpts.transitionOut == 'none' ? 0 : currentOpts.speedOut, _cleanup);
		}
	};

	$.fancybox.resize = function() {
		var c, h;
		
		if (busy || wrap.is(':hidden')) {
			return;
		}

		busy = true;

		c = inner.wrapInner("<div style='overflow:auto'></div>").children();
		h = c.height();

		wrap.css({height:	h + (currentOpts.padding * 2) + titleh});
		inner.css({height:	h});

		c.replaceWith(c.children());

		$.fancybox.center();
	};

	$.fancybox.center = function() {
		busy = true;

		var view	= fancybox_get_viewport(),
			margin	= currentOpts.margin,
			to		= {};

		to.top	= view[3] + ((view[1] - ((wrap.height() - titleh) + (shadow * 2 ))) * 0.5);
		to.left	= view[2] + ((view[0] - (wrap.width() + (shadow * 2 ))) * 0.5);

		to.top	= Math.max(view[3] + margin, to.top);
		to.left	= Math.max(view[2] + margin, to.left);

		wrap.css(to);

		busy = false;
	};

	$.fn.fancybox.defaults = {
		padding				:	10,
		margin				:	20,
		opacity				:	false,
		modal				:	false,
		cyclic				:	false,
		scrolling			:	'auto',	// 'auto', 'yes' or 'no'

		width				:	560,
		height				:	340,

		autoScale			:	true,
		autoDimensions		:	true,
		centerOnScroll		:	false,

		ajax				:	{},
		swf					:	{ wmode: 'transparent' },

		hideOnOverlayClick	:	true,
		hideOnContentClick	:	false,

		overlayShow			:	true,
		overlayOpacity		:	0.3,
		overlayColor		:	'#666',

		titleShow			:	true,
		titlePosition		:	'outside',	// 'outside', 'inside' or 'over'
		titleFormat			:	null,

		transitionIn		:	'fade',	// 'elastic', 'fade' or 'none'
		transitionOut		:	'fade',	// 'elastic', 'fade' or 'none'

		speedIn				:	300,
		speedOut			:	300,

		changeSpeed			:	300,
		changeFade			:	'fast',

		easingIn			:	'swing',
		easingOut			:	'swing',

		showCloseButton		:	true,
		showNavArrows		:	true,
		enableEscapeButton	:	true,

		onStart				:	null,
		onCancel			:	null,
		onComplete			:	null,
		onCleanup			:	null,
		onClosed			:	null
	};

	$(document).ready(function() {
		fancybox_init();
	});

})(jQuery);;
/**
 * Assign custom selectors and behaviour
 */
$(function () {
  // Creating custom :external selector
  $.expr[':'].external = function(obj){
      return !obj.href.match(/^mailto\:/)
              && (obj.hostname != location.hostname);
  };

  // Add 'target="_blank" to all external links
  $('.article a:external').attr('target', '_blank');
});


/**
 * Open/close login box
 */
$(function () {
	$('div#head div.login').click(function (event) {
		event.stopPropagation();
	});
	$('div#head div.user.out a[href=/user]').click(function () {
		$('div#head div.login').stop(true, true).fadeIn(250);
		$(document).unbind('keydown.login').bind('keydown.login', function (event) {
			if (event.which == 27) {
				$('div#head div.login').stop(true, true).fadeOut(500);
				$(document).unbind('keydown.login').unbind('click.login');
			}
		}).unbind('click.login').bind('click.login', function () {
			$('div#head div.login').stop(true, true).fadeOut(500);
			$(document).unbind('keydown.login').unbind('click.login');
		});
		return false;
	});
	$('div#head div.login').append($('<a href="" class="close"></a>').click(function () {
		$('div#head div.login').stop(true, true).fadeOut(500);
		$(document).unbind('keydown.login').unbind('click.login');
		return false;
	}));
	$('div#head div.login form').submit(function () {
		$('div#head div.login').stop(true, true).fadeOut(500);
		$(document).unbind('keydown.login').unbind('click.login');
	});
});

/**
 * Fancy label overlay on login and search boxes
 */
$(function () {
	$('div#head div.login div.item, div#head div.search div.item, div.block.question.ask div.item, div.block.box div.item.placeholder').each(function () {
		var $input = $(this).find('input');
		var $label = $(this).find('label');
		if ($input.hasClass('error')) $label.addClass('error');
		!$input.val() ? $label.show() : $label.hide();
		$(this).hover(function () {
			$input.addClass('hover');
			$label.stop(true, true).fadeOut(125);
		}, function () {
			$input.removeClass('hover');
			!$input.is('.focus') && !$input.val() ? $label.stop(true, true).fadeIn(250) : $label.hide();
		});
		$input.focus(function () {
			$input.addClass('focus');
			$label.stop(true, true).fadeOut(125);
		}).blur(function () {
			$input.removeClass('focus');
			!$input.is('.hover') && !$input.val() ? $label.stop(true, true).fadeIn(250) : $label.hide();
		});
	});
});

/**
 * Fancy description overlay on group post
 */
$(function () {
	$('div.block.group.post div.post div.item.textarea').each(function () {
		var $textarea = $(this).find('textarea');
		var $description = $(this).find('span.description');
		!$textarea.val() ? $description.show() : $description.hide();
		$(this).hover(function () {
			$textarea.addClass('hover');
			$description.stop(true, true).fadeOut(125);
		}, function () {
			$textarea.removeClass('hover');
			!$textarea.is('.focus') && !$textarea.val() ? $description.stop(true, true).fadeIn(250) : $description.hide();
		});
		$textarea.focus(function () {
			$textarea.addClass('focus');
			$description.stop(true, true).fadeOut(125);
		}).blur(function () {
			$textarea.removeClass('focus');
			!$textarea.is('.hover') && !$textarea.val() ? $description.stop(true, true).fadeIn(250) : $description.hide();
		});
	});
});

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

/**
 * Tabs
 */
$(function () {
	// Select tabs
	var $tabs = $('div#shoulders div.tabs').hide();

	// Define timer
	var timer;

	// Mouseover
	$tabs.add('div#head > div > div, div#shoulders > div > div, div#body > div > div, div#foot > div > div').mouseover(function () {
		clearTimeout(timer);
		!$.browser.msie ? $tabs.fadeIn(125) : $tabs.show();
	});

	// Mouseout
	$tabs.add('div#head > div > div, div#shoulders > div > div, div#body > div > div, div#foot > div > div').mouseout(function () {
		clearTimeout(timer);
		timer = setTimeout(function () {
			!$.browser.msie ? $tabs.fadeOut(125) : $tabs.hide();
		}, 125);
	});
});

/**
 * Styling related
 */
$(function () {
  $('table tr td:last-child').addClass('last');
});

/**
 * Tools
 */
$(function () {
	// Get tools visibility
	var get = function () {
		// Read from cookie
		return !!parseInt((document.cookie.match(/(^|;\s*)tools=(0|1)(\s*;|$)/) || [,,1])[2]);
	};

	// Set tools visibility
	var set = function (visible) {
		// Write to cookie
		document.cookie = 'tools=' + (visible ? 1 : 0) + '; path=/';

		// Update link text
		$a.text(Drupal.t('Tools') + ': ' + Drupal.t(visible ? 'on' : 'off'));
	};

	// Create link
	var $a = $('<a href="" />').click(function () {
		set(!get());
		return false;
	}).appendTo($('<div />').prependTo('div#shoulders div.tabs'));

	// Initialize
	set(get());

	// Iterate through tools
	$('div.tools').each(function () {
		// Select tools
		var $tools = $(this);

		// Define timer
		var timer;

		// Mouseover
		$tools.parent().andSelf().mouseover(function () {
			clearTimeout(timer);
			if (get()) !$.browser.msie ? $tools.fadeIn(125) : $tools.show();
		});

		// Mouseout
		$tools.parent().andSelf().mouseout(function () {
			clearTimeout(timer);
			timer = setTimeout(function () {
				!$.browser.msie ? $tools.fadeOut(125) : $tools.hide();
			}, 125);
		});
	});
});

/**
 * Carousel
 */
$(function () {
	$('div.block.carousel').each(function () {
		// Select carousel
		var $carousel = $(this);

		// Define timer
		var timer;

		// Select items
		var $items = $carousel.find('div.item');

		// Build navigation
		var $navigation = $('<div class="navigation"><ul></ul></div>');
		$items.each(function (i) {
			$navigation.find('ul').append($('<a href="" />').text($items.eq(i).find('div.title a').text()).wrap('<li />').parent());
		});
		$carousel.prepend($navigation);

		// Select links
		var $links = $carousel.find('div.navigation li');

		// Set first as active
		$links.eq(0).addClass('active');
		$items.eq(0).addClass('active');

		// Rotate
		var rotate = function (next, speed) {
			// Define current and next
			var current;
			var next = (typeof next == 'number') ? next : undefined;
			$links.each(function (i) {
				if ($links.eq(i).is('.active')) {
					current = i;
					if (typeof next != 'number') {
						next = i == $links.length - 1 ? 0 : i + 1;
					}
					return;
				}
			});

			// Animate
			$items.css('z-index', 1).removeClass('active').stop(true, true);
			$items.eq(current).css('z-index', 2).show();
			$items.eq(next).css('z-index', 3).addClass('active').hide().fadeIn(speed ? speed : 1000);
			$links.removeClass('active');
			$links.eq(next).addClass('active');
		};

		// Mouseover on links
		$links.each(function (i) {
			$links.eq(i).mouseover(function () {
				clearTimeout(timer);
				rotate(i, 500);
			}).find('a').attr('href', $items.eq(i).find('div.link a').attr('href'));
		});

		// Mouseover on items
		$items.mouseover(function () {
			clearTimeout(timer);
		});

		// Mouseout on carousel
		$carousel.mouseout(function () {
			clearTimeout(timer);
			timer = setInterval(function () {rotate()}, 3000);
		});

		// Start timer
		$carousel.mouseout();
	});
});

/**
 * Google Maps geocoder
 */
$(function () {
	$('.form-gmaps-geocoder').each(function () {
		// Select geocoder
		var $gc = $(this);

		// Define timer
		var timer;

		// Keydown on query input
		$gc.find('.form-gmaps-geocoder-query').attr('autocomplete', 'OFF').keydown(function () {
			// Clear hidden inputs
			$gc.parents('form').find('[class^=form-gmaps-point-]').val('');

			// Clear popup
			$gc.find('.gmaps-geocoder-popup').hide().empty();

			// Reset timer to prevent multiple queries
			clearTimeout(timer);

			// Start timer with delayed query
			timer = setTimeout(function () {
				// Search
				Drupal.gmaps.geocoder.elements[$gc.attr('id')].doSearch(undefined, true);
			}, 1000);
		});

		// Override accuracy levels with nasty hack
		Drupal.settings.gmaps.geocoder.accuracyLevels = ['', '', '', '', '', '', '', '', '', ''];
	});

});

/**
 * Calendar popup
 */
$(document).ready(function() {
	// Click on calendar links
	$('div.block.calendar.full td a').click(function (a) {
		// Make sure that other stuff is closed. This seems to cause a problem in Fx2 and IE7.
		$('div#calpopup').fadeOut();
		$('div#calpopup').remove();

		// create div to hold data and add it to the end of the body
		var div = $('<div id="calpopup"><div id="popup-close"><img id="popup-close-img" src="' + var_path + '/images/cross.png" /></div><div id="calpopup-body"><img src="' + var_path + '/images/throbber.gif" id="popthrobber" /></div></div>').attr('style','display: none');
		div.appendTo(document.body);

		// Locate Popup
		var offset = $(this).offset();
		// Check position with window width.
		var offset_left = offset.left + 5;
		if ($(window).width() < $('#calpopup').width() + offset.left) {
			offset_left -= $('#calpopup').width() + 5;
			if (offset_left < 0) {
				offset_left = 0;
			}
		}
		var offset_top = offset.top + 25;
		if ($(window).height() < $('#calpopup').height() + offset_top) {
			offset_top -= $('#calpopup').height() + 25;
			if (offset_top < 0) {
				offset_top = 0;
			}
		}
		$('#calpopup').css('left', offset_left);
		$('#calpopup').css('top', offset_top);

		// Show Popup
		$('#calpopup').fadeIn('slow');

		// If sucessful call this
		function domCallback(msg) {
			$('#calpopup-body').html(msg);
		}

		// Get NodeID and ItemID
		var ids = $(this).attr('id');
		var arr = ids.split(":");
		var nid = arr[1];
		var id = arr[4];
		var gid = location.href.split('/').pop();

		// fill the div with data
		$.ajax({
			type: "GET",
			url: var_base_path + "?q=jcalendar/getnode/"+nid+"/"+ids+"&gids[]="+gid,
			success: function(msg){
				domCallback(msg);
			}
		});

		// On click of the close image
		$('img#popup-close-img').click(function(x) {
			$('div#calpopup').fadeOut();
			$('div#calpopup').remove();
		});

		$(document).click(function(y) {
			var $tgt = $(y.target);
			if (!$tgt.parents().is('div#calpopup')) {
				$('div#calpopup').fadeOut();
				$('div#calpopup').remove();
				$(document).unbind("click");
			}
		});

		// Don't Follow the real link
		return false;
	});
});

/* open the print dialog when a user clicks the print link */
$(function () {
  $('li.print a').click(function(){
    window.print();
    return false;
  });
});

/**
 * Gallery
 */
$(function () {
  $('div.block.gallery .image a').attr('rel', 'gallery');
  $('div.block.gallery .image a img').attr('alt', '');
});

/**
 * Add fancybox implementation
 */
$(function () {
  $('div.block.gallery .items ul li a').fancybox({
  	'margin': 20,
    'padding': 0,
    'titlePosition': 'over',
    'titleShow': true
  });

  $('div.attachment div.image a').fancybox({
  	'margin': 20,
    'padding': 0,
    'titlePosition': 'over',
    'titleShow': true
  });

  $('div.block.group.messages div.images div.image a, div.block.group.images div.image a').fancybox({
  	'margin': 20,
    'padding': 0,
    'titleShow': false
  });

  playerpath = '/sites/nymotion.dk/libraries/flowplayer/flowplayer-3.2.2.swf';

  $('a.video_link').hover(function(){
    videolink = $(this).attr('name');
  });

  $('a.video_link').fancybox({
    'hideOnContentClick': false,
    'padding': '0',
    'titleShow': false,
    'onComplete': function(){
      player = $f('fancybox-inner', playerpath, {
        clip: {
          autoPlay:true,
          autoBuffering:true,
          url: videolink,
          onStart:function(clip){
          	var wrap=jQuery(this.getParent());
          	var clipwidth = clip.metaData.width;
          	var clipheight= clip.metaData.height;
          	var pos = $.fn.fancybox.getViewport();
          	$("#fancybox-outer").css({width:clipwidth+20,height:clipheight+20});
          	$("#fancybox-outer").css('left', ((clipwidth) > pos[0] ? pos[2] : pos[2] + Math.round((pos[0] - clipwidth	- 36)	/ 2)));
          	$("#fancybox-outer").css('top',  ((clipheight ) > pos[1] ? pos[3] : pos[3] + Math.round((pos[1] - clipheight - 50)	/ 2)));
          	$("#fancy-bg-e, #fancy-bg-w").css({height:clipheight-60, bottom: '70px'});
          },
          onFinish:function(){
          	$('#fancy_close').trigger('click');
          }
        }
      });
      player.load();
  },
  'callbackOnClose':function(){
  	$("#fancy_content_api").remove();
  }
 });
});

$(function() {

    $('.tip_trigger').each(function() {
        var tip = $(this).find('.tip');

        $(this).hover(
            function() { tip.appendTo('body'); },
            function() { tip.appendTo(this); }
        ).mousemove(function(e) {
            var x = e.pageX + 13,
                y = e.pageY + 13,
                w = tip.width(),
                h = tip.height(),
                dx = $(window).width() - (x + w),
                dy = $(window).height() - (y + h);

            tip.css({ left: x, top: y });
        });
    });

});
;

