/*
 * jQuery JavaScript Library v1.3.2
 * http://jquery.com/
 *
 * Copyright (c) 2009 John Resig
 * Dual licensed under the MIT and GPL licenses.
 * http://docs.jquery.com/License
 *
 * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
 * Revision: 6246
 */
(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],"find",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),"find",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement("div");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find("*").andSelf(),F=0;E.find("*").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],"events");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,"closest",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F<J;F++){var G=M[F];if(G.selected){K=o(G).val();if(H){return K}L.push(K)}}return L}return(E.value||"").replace(/\r/g,"")}return g}if(typeof K==="number"){K+=""}return this.each(function(){if(this.nodeType!=1){return}if(o.isArray(K)&&/radio|checkbox/.test(this.type)){this.checked=(o.inArray(this.value,K)>=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(J,M,L){if(this[0]){var I=(this[0].ownerDocument||this[0]).createDocumentFragment(),F=o.clean(J,(this[0].ownerDocument||this[0]),I),H=I.firstChild;if(H){for(var G=0,E=this.length;G<E;G++){L.call(K(this[G],H),this.length>1||G>0?I.cloneNode(true):I)}}if(F){o.each(F,z)}}return this;function K(N,O){return M&&o.nodeName(N,"table")&&o.nodeName(O,"tr")?(N.getElementsByTagName("tbody")[0]||N.appendChild(N.ownerDocument.createElement("tbody"))):N}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H<I;H++){if((G=arguments[H])!=null){for(var F in G){var K=J[F],L=G[F];if(J===L){continue}if(E&&L&&typeof L==="object"&&!L.nodeType){J[F]=o.extend(E,K||(L.length!=null?[]:{}),L)}else{if(L!==g){J[F]=L}}}}}return J};var b=/z-?index|font-?weight|opacity|zoom|line-?height/i,q=document.defaultView||{},s=Object.prototype.toString;o.extend({noConflict:function(E){l.$=p;if(E){l.jQuery=y}return o},isFunction:function(E){return s.call(E)==="[object Function]"},isArray:function(E){return s.call(E)==="[object Array]"},isXMLDoc:function(E){return E.nodeType===9&&E.documentElement.nodeName!=="HTML"||!!E.ownerDocument&&o.isXMLDoc(E.ownerDocument)},globalEval:function(G){if(G&&/\S/.test(G)){var F=document.getElementsByTagName("head")[0]||document.documentElement,E=document.createElement("script");E.type="text/javascript";if(o.support.scriptEval){E.appendChild(document.createTextNode(G))}else{E.text=G}F.insertBefore(E,F.firstChild);F.removeChild(E)}},nodeName:function(F,E){return F.nodeName&&F.nodeName.toUpperCase()==E.toUpperCase()},each:function(G,K,F){var E,H=0,I=G.length;if(F){if(I===g){for(E in G){if(K.apply(G[E],F)===false){break}}}else{for(;H<I;){if(K.apply(G[H++],F)===false){break}}}}else{if(I===g){for(E in G){if(K.call(G[E],E,G[E])===false){break}}}else{for(var J=G[0];H<I&&K.call(J,H,J)!==false;J=G[++H]){}}}return G},prop:function(H,I,G,F,E){if(o.isFunction(I)){I=I.call(H,F)}return typeof I==="number"&&G=="curCSS"&&!b.test(E)?I+"px":I},className:{add:function(E,F){o.each((F||"").split(/\s+/),function(G,H){if(E.nodeType==1&&!o.className.has(E.className,H)){E.className+=(E.className?" ":"")+H}})},remove:function(E,F){if(E.nodeType==1){E.className=F!==g?o.grep(E.className.split(/\s+/),function(G){return !o.className.has(F,G)}).join(" "):""}},has:function(F,E){return F&&o.inArray(E,(F.className||F).toString().split(/\s+/))>-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(H,F,J,E){if(F=="width"||F=="height"){var L,G={position:"absolute",visibility:"hidden",display:"block"},K=F=="width"?["Left","Right"]:["Top","Bottom"];function I(){L=F=="width"?H.offsetWidth:H.offsetHeight;if(E==="border"){return}o.each(K,function(){if(!E){L-=parseFloat(o.curCSS(H,"padding"+this,true))||0}if(E==="margin"){L+=parseFloat(o.curCSS(H,"margin"+this,true))||0}else{L-=parseFloat(o.curCSS(H,"border"+this+"Width",true))||0}})}if(H.offsetWidth!==0){I()}else{o.swap(H,G,I)}return Math.max(0,Math.round(L))}return o.curCSS(H,F,J)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,S){if(typeof S==="number"){S+=""}if(!S){return}if(typeof S==="string"){S=S.replace(/(<(\w+)[^>]*?)\/>/g,function(U,V,T){return T.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?U:V+"></"+T+">"});var O=S.replace(/^\s+/,"").substring(0,10).toLowerCase();var Q=!O.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!O.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!O.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!O.indexOf("<td")||!O.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!O.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||!o.support.htmlSerialize&&[1,"div<div>","</div>"]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/<tbody/i.test(S),N=!O.indexOf("<table")&&!R?L.firstChild&&L.firstChild.childNodes:Q[1]=="<table>"&&!R?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(S)){L.insertBefore(K.createTextNode(S.match(/^\s*/)[0]),L.firstChild)}S=o.makeArray(L.childNodes)}if(S.nodeType){G.push(S)}else{G=o.merge(G,S)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E<F;E++){if(H[E]===G){return E}}return -1},merge:function(H,E){var F=0,G,I=H.length;if(!o.support.getAll){while((G=E[F++])!=null){if(G.nodeType!=8){H[I++]=G}}}else{while((G=E[F++])!=null){H[I++]=G}}return H},unique:function(K){var F=[],E={};try{for(var G=0,H=K.length;G<H;G++){var J=o.data(K[G]);if(!E[J]){E[J]=true;F.push(K[G])}}}catch(I){F=K}return F},grep:function(F,J,E){var G=[];for(var H=0,I=F.length;H<I;H++){if(!E!=!J(F[H],H)){G.push(F[H])}}return G},map:function(E,J){var F=[];for(var G=0,H=E.length;G<H;G++){var I=J(E[G],G);if(I!=null){F[F.length]=I}}return F.concat.apply([],F)}});var C=navigator.userAgent.toLowerCase();o.browser={version:(C.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1],safari:/webkit/.test(C),opera:/opera/.test(C),msie:/msie/.test(C)&&!/opera/.test(C),mozilla:/mozilla/.test(C)&&!/(compatible|webkit)/.test(C)};o.each({parent:function(E){return E.parentNode},parents:function(E){return o.dir(E,"parentNode")},next:function(E){return o.nth(E,2,"nextSibling")},prev:function(E){return o.nth(E,2,"previousSibling")},nextAll:function(E){return o.dir(E,"nextSibling")},prevAll:function(E){return o.dir(E,"previousSibling")},siblings:function(E){return o.sibling(E.parentNode.firstChild,E)},children:function(E){return o.sibling(E.firstChild)},contents:function(E){return o.nodeName(E,"iframe")?E.contentDocument||E.contentWindow.document:o.makeArray(E.childNodes)}},function(E,F){o.fn[E]=function(G){var H=o.map(this,F);if(G&&typeof G=="string"){H=o.multiFilter(G,H)}return this.pushStack(o.unique(H),E,G)}});o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(E,F){o.fn[E]=function(G){var J=[],L=o(G);for(var K=0,H=L.length;K<H;K++){var I=(K>0?this.clone(true):this).get();o.fn[F].apply(o(L[K]),I);J=J.concat(I)}return this.pushStack(J,E,G)}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}});
/*
 * Sizzle CSS Selector Engine - v0.9.3
 *  Copyright 2009, The Dojo Foundation
 *  Released under the MIT, BSD, and GPL Licenses.
 *  More information: http://sizzlejs.com/
 */
(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa<ab.length;aa++){if(ab[aa]===ab[aa-1]){ab.splice(aa--,1)}}}}}return ab};F.matches=function(T,U){return F(T,null,null,U)};F.find=function(aa,T,ab){var Z,X;if(!aa){return[]}for(var W=0,V=I.order.length;W<V;W++){var Y=I.order[W],X;if((X=I.match[Y].exec(aa))){var U=RegExp.leftContext;if(U.substr(U.length-1)!=="\\"){X[1]=(X[1]||"").replace(/\\/g,"");Z=I.find[Y](X,T,ab);if(Z!=null){aa=aa.replace(I.match[Y],"");break}}}}if(!Z){Z=T.getElementsByTagName("*")}return{set:Z,expr:aa}};F.filter=function(ad,ac,ag,W){var V=ad,ai=[],aa=ac,Y,T,Z=ac&&ac[0]&&Q(ac[0]);while(ad&&ac.length){for(var ab in I.filter){if((Y=I.match[ab].exec(ad))!=null){var U=I.filter[ab],ah,af;T=false;if(aa==ai){ai=[]}if(I.preFilter[ab]){Y=I.preFilter[ab](Y,aa,ag,ai,W,Z);if(!Y){T=ah=true}else{if(Y===true){continue}}}if(Y){for(var X=0;(af=aa[X])!=null;X++){if(af){ah=U(af,Y,X,aa);var ae=W^!!ah;if(ag&&ah!=null){if(ae){T=true}else{aa[X]=false}}else{if(ae){ai.push(af);T=true}}}}}if(ah!==g){if(!ag){aa=ai}ad=ad.replace(I.match[ab],"");if(!T){return[]}break}}}if(ad==V){if(T==null){throw"Syntax error, unrecognized expression: "+ad}else{break}}V=ad}return aa};var I=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(T){return T.getAttribute("href")}},relative:{"+":function(aa,T,Z){var X=typeof T==="string",ab=X&&!/\W/.test(T),Y=X&&!ab;if(ab&&!Z){T=T.toUpperCase()}for(var W=0,V=aa.length,U;W<V;W++){if((U=aa[W])){while((U=U.previousSibling)&&U.nodeType!==1){}aa[W]=Y||U&&U.nodeName===T?U||false:U===T}}if(Y){F.filter(T,aa,true)}},">":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){var W=Y.parentNode;Z[V]=W.nodeName===U?W:false}}}else{for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){Z[V]=X?Y.parentNode:Y.parentNode===U}}if(X){F.filter(U,Z,true)}}},"":function(W,U,Y){var V=L++,T=S;if(!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("parentNode",U,V,W,X,Y)},"~":function(W,U,Y){var V=L++,T=S;if(typeof U==="string"&&!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("previousSibling",U,V,W,X,Y)}},find:{ID:function(U,V,W){if(typeof V.getElementById!=="undefined"&&!W){var T=V.getElementById(U[1]);return T?[T]:[]}},NAME:function(V,Y,Z){if(typeof Y.getElementsByName!=="undefined"){var U=[],X=Y.getElementsByName(V[1]);for(var W=0,T=X.length;W<T;W++){if(X[W].getAttribute("name")===V[1]){U.push(X[W])}}return U.length===0?null:U}},TAG:function(T,U){return U.getElementsByTagName(T[1])}},preFilter:{CLASS:function(W,U,V,T,Z,aa){W=" "+W[1].replace(/\\/g,"")+" ";if(aa){return W}for(var X=0,Y;(Y=U[X])!=null;X++){if(Y){if(Z^(Y.className&&(" "+Y.className+" ").indexOf(W)>=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return U<T[3]-0},gt:function(V,U,T){return U>T[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W<T;W++){if(Y[W]===Z){return false}}return true}}}},CHILD:function(T,W){var Z=W[1],U=T;switch(Z){case"only":case"first":while(U=U.previousSibling){if(U.nodeType===1){return false}}if(Z=="first"){return true}U=T;case"last":while(U=U.nextSibling){if(U.nodeType===1){return false}}return true;case"nth":var V=W[2],ac=W[3];if(V==1&&ac==0){return true}var Y=W[0],ab=T.parentNode;if(ab&&(ab.sizcache!==Y||!T.nodeIndex)){var X=0;for(U=ab.firstChild;U;U=U.nextSibling){if(U.nodeType===1){U.nodeIndex=++X}}ab.sizcache=Y}var aa=T.nodeIndex-ac;if(V==0){return aa==0}else{return(aa%V==0&&aa/V>=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V<T;V++){U.push(X[V])}}else{for(var V=0;X[V];V++){U.push(X[V])}}}return U}}var G;if(document.documentElement.compareDocumentPosition){G=function(U,T){var V=U.compareDocumentPosition(T)&4?-1:U===T?0:1;if(V===0){hasDuplicate=true}return V}}else{if("sourceIndex" in document.documentElement){G=function(U,T){var V=U.sourceIndex-T.sourceIndex;if(V===0){hasDuplicate=true}return V}}else{if(document.createRange){G=function(W,U){var V=W.ownerDocument.createRange(),T=U.ownerDocument.createRange();V.selectNode(W);V.collapse(true);T.selectNode(U);T.collapse(true);var X=V.compareBoundaryPoints(Range.START_TO_END,T);if(X===0){hasDuplicate=true}return X}}}}(function(){var U=document.createElement("form"),V="script"+(new Date).getTime();U.innerHTML="<input name='"+V+"'/>";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="<a href='#'></a>";if(T.firstChild&&typeof T.firstChild.getAttribute!=="undefined"&&T.firstChild.getAttribute("href")!=="#"){I.attrHandle.href=function(U){return U.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement("div");U.innerHTML="<p class='TEST'></p>";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="<div class='test e'></div><div class='test'></div>";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1&&!ac){T.sizcache=Y;T.sizset=W}if(T.nodeName===Z){X=T;break}T=T[U]}ad[W]=X}}}function S(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1){if(!ac){T.sizcache=Y;T.sizset=W}if(typeof Z!=="string"){if(T===Z){X=true;break}}else{if(F.filter(Z,[T]).length>0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z<U;Z++){F(T,V[Z],W)}return F.filter(X,W)};o.find=F;o.filter=F.filter;o.expr=F.selectors;o.expr[":"]=o.expr.filters;F.selectors.filters.hidden=function(T){return T.offsetWidth===0||T.offsetHeight===0};F.selectors.filters.visible=function(T){return T.offsetWidth>0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F<E.length){o.event.proxy(G,E[F++])}return this.click(o.event.proxy(G,function(H){this.lastToggle=(this.lastToggle||0)%F;H.preventDefault();return E[this.lastToggle++].apply(this,arguments)||false}))},hover:function(E,F){return this.mouseenter(E).mouseleave(F)},ready:function(E){B();if(o.isReady){E.call(document,o)}else{o.readyList.push(E)}return this},live:function(G,F){var E=o.event.proxy(F);E.guid+=this.selector+G;o(document).bind(i(G,this.selector),this.selector,E);return this},die:function(F,E){o(document).unbind(i(F,this.selector),E?{guid:E.guid+this.selector+F}:null);return this}});function c(H){var E=RegExp("(^|\\.)"+H.type+"(\\.|$)"),G=true,F=[];o.each(o.data(this,"events").live||[],function(I,J){if(E.test(J.type)){var K=o(H.target).closest(J.data)[0];if(K){F.push({elem:K,fn:J})}}});F.sort(function(J,I){return o.data(J.elem,"closest")-o.data(I.elem,"closest")});o.each(F,function(){if(this.fn.call(this.elem,H,this.fn.data)===false){return(G=false)}});return G}function i(F,E){return["live",F,E.replace(/\./g,"`").replace(/ /g,"|")].join(".")}o.extend({isReady:false,readyList:[],ready:function(){if(!o.isReady){o.isReady=true;if(o.readyList){o.each(o.readyList,function(){this.call(document,o)});o.readyList=null}o(document).triggerHandler("ready")}}});var x=false;function B(){if(x){return}x=true;if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);o.ready()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",arguments.callee);o.ready()}});if(document.documentElement.doScroll&&l==l.top){(function(){if(o.isReady){return}try{document.documentElement.doScroll("left")}catch(E){setTimeout(arguments.callee,0);return}o.ready()})()}}}o.event.add(l,"load",o.ready)}o.each(("blur,focus,load,resize,scroll,unload,click,dblclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error").split(","),function(F,E){o.fn[E]=function(G){return G?this.bind(E,G):this.trigger(E)}});o(l).bind("unload",function(){for(var E in o.cache){if(E!=1&&o.cache[E].handle){o.event.remove(o.cache[E].handle.elem)}}});(function(){o.support={};var F=document.documentElement,G=document.createElement("script"),K=document.createElement("div"),J="script"+(new Date).getTime();K.style.display="none";K.innerHTML='   <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';var H=K.getElementsByTagName("*"),E=K.getElementsByTagName("a")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName("tbody").length,objectAll:!!K.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!K.getElementsByTagName("link").length,style:/red/.test(E.getAttribute("style")),hrefNormalized:E.getAttribute("href")==="/a",opacity:E.style.opacity==="0.5",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type="text/javascript";try{G.appendChild(document.createTextNode("window."+J+"=1;"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent("onclick",function(){o.support.noCloneEvent=false;K.detachEvent("onclick",arguments.callee)});K.cloneNode(true).fireEvent("onclick")}o(function(){var L=document.createElement("div");L.style.width=L.style.paddingLeft="1px";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L).style.display="none"})})();var w=o.support.cssFloat?"cssFloat":"styleFloat";o.props={"for":"htmlFor","class":"className","float":w,cssFloat:w,styleFloat:w,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!=="string"){return this._load(G)}var I=G.indexOf(" ");if(I>=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("<div/>").append(M.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H<F;H++){var E=o.data(this[H],"olddisplay");this[H].style.display=E||"";if(o.css(this[H],"display")==="none"){var G=this[H].tagName,K;if(m[G]){K=m[G]}else{var I=o("<"+G+" />").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H<F;H++){this[H].style.display=o.data(this[H],"olddisplay")||""}return this}},hide:function(H,I){if(H){return this.animate(t("hide",3),H,I)}else{for(var G=0,F=this.length;G<F;G++){var E=o.data(this[G],"olddisplay");if(!E&&E!=="none"){o.data(this[G],"olddisplay",o.css(this[G],"display"))}}for(var G=0,F=this.length;G<F;G++){this[G].style.display="none"}return this}},_toggle:o.fn.toggle,toggle:function(G,F){var E=typeof G==="boolean";return o.isFunction(G)&&o.isFunction(F)?this._toggle.apply(this,arguments):G==null||E?this.each(function(){var H=E?G:o(this).is(":hidden");o(this)[H?"show":"hide"]()}):this.animate(t("toggle",3),G,F)},fadeTo:function(E,G,F){return this.animate({opacity:G},E,F)},animate:function(I,F,H,G){var E=o.speed(F,H,G);return this[E.queue===false?"each":"queue"](function(){var K=o.extend({},E),M,L=this.nodeType==1&&o(this).is(":hidden"),J=this;for(M in I){if(I[M]=="hide"&&L||I[M]=="show"&&!L){return K.complete.call(this)}if((M=="height"||M=="width")&&this.style){K.display=o.css(this,"display");K.overflow=this.style.overflow}}if(K.overflow!=null){this.style.overflow="hidden"}K.curAnim=o.extend({},I);o.each(I,function(O,S){var R=new o.fx(J,K,O);if(/toggle|show|hide/.test(S)){R[S=="toggle"?L?"show":"hide":S](I)}else{var Q=S.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),T=R.cur(true)||0;if(Q){var N=parseFloat(Q[2]),P=Q[3]||"px";if(P!="px"){J.style[O]=(N||1)+P;T=((N||1)/R.cur(true))*T;J.style[O]=T+P}if(Q[1]){N=((Q[1]=="-="?-1:1)*N)+T}R.custom(T,N,P)}else{R.custom(T,S,"")}}});return true})},stop:function(F,E){var G=o.timers;if(F){this.queue([])}this.each(function(){for(var H=G.length-1;H>=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J<K.length;J++){if(!K[J]()){K.splice(J--,1)}}if(!K.length){clearInterval(n);n=g}},13)}},show:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.show=true;this.custom(this.prop=="width"||this.prop=="height"?1:0,this.cur());o(this.elem).show()},hide:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(H){var G=e();if(H||G>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})();
/**
 * jquery.Jcrop.js v0.9.8
 * jQuery Image Cropping Plugin
 * @author Kelly Hallman <khallman@gmail.com>
 * Copyright (c) 2008-2009 Kelly Hallman - released under MIT License {{{
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:

 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.

 * }}}
 */

(function($) {

$.Jcrop = function(obj,opt)
{
	// Initialization {{{

	// Sanitize some options {{{
	var obj = obj, opt = opt;

	if (typeof(obj) !== 'object') obj = $(obj)[0];
	if (typeof(opt) !== 'object') opt = { };

	// Some on-the-fly fixes for MSIE...sigh
	if (!('trackDocument' in opt))
	{
		opt.trackDocument = $.browser.msie ? false : true;
		if ($.browser.msie && $.browser.version.split('.')[0] == '8')
			opt.trackDocument = true;
	}

	if (!('keySupport' in opt))
			opt.keySupport = $.browser.msie ? false : true;
		
	// }}}
	// Extend the default options {{{
	var defaults = {

		// Basic Settings
		trackDocument:		false,
		baseClass:			'jcrop',
		addClass:			null,

		// Styling Options
		bgColor:			'black',
		bgOpacity:			.6,
		borderOpacity:		.4,
		handleOpacity:		.5,

		handlePad:			5,
		handleSize:			9,
		handleOffset:		5,
		edgeMargin:			14,

		aspectRatio:		0,
		keySupport:			true,
		cornerHandles:		true,
		sideHandles:		true,
		drawBorders:		true,
		dragEdges:			true,

		boxWidth:			0,
		boxHeight:			0,

		boundary:			8,
		animationDelay:		20,
		swingSpeed:			3,

		allowSelect:		true,
		allowMove:			true,
		allowResize:		true,

		minSelect:			[ 0, 0 ],
		maxSize:			[ 0, 0 ],
		minSize:			[ 0, 0 ],

		// Callbacks / Event Handlers
		onChange: function() { },
		onSelect: function() { }

	};
	var options = defaults;
	setOptions(opt);

	// }}}
	// Initialize some jQuery objects {{{

	var $origimg = $(obj);
	var $img = $origimg.clone().removeAttr('id').css({ position: 'absolute' });

	$img.width($origimg.width());
	$img.height($origimg.height());
	$origimg.after($img).hide();

	presize($img,options.boxWidth,options.boxHeight);

	var boundx = $img.width(),
		boundy = $img.height(),

		$div = $('<div />')
			.width(boundx).height(boundy)
			.addClass(cssClass('holder'))
			.css({
				position: 'relative',
				backgroundColor: options.bgColor
			}).insertAfter($origimg).append($img);
	;
	
	if (options.addClass) $div.addClass(options.addClass);
	//$img.wrap($div);

	var $img2 = $('<img />')/*{{{*/
			.attr('src',$img.attr('src'))
			.css('position','absolute')
			.width(boundx).height(boundy)
	;/*}}}*/
	var $img_holder = $('<div />')/*{{{*/
		.width(pct(100)).height(pct(100))
		.css({
			zIndex: 310,
			position: 'absolute',
			overflow: 'hidden'
		})
		.append($img2)
	;/*}}}*/
	var $hdl_holder = $('<div />')/*{{{*/
		.width(pct(100)).height(pct(100))
		.css('zIndex',320);
	/*}}}*/
	var $sel = $('<div />')/*{{{*/
		.css({
			position: 'absolute',
			zIndex: 300
		})
		.insertBefore($img)
		.append($img_holder,$hdl_holder)
	;/*}}}*/

	var bound = options.boundary;
	var $trk = newTracker().width(boundx+(bound*2)).height(boundy+(bound*2))
		.css({ position: 'absolute', top: px(-bound), left: px(-bound), zIndex: 290 })
		.mousedown(newSelection);	
	
	/* }}} */
	// Set more variables {{{

	var xlimit, ylimit, xmin, ymin;
	var xscale, yscale, enabled = true;
	var docOffset = getPos($img),
		// Internal states
		btndown, lastcurs, dimmed, animating,
		shift_down;

	// }}}
		

		// }}}
	// Internal Modules {{{

	var Coords = function()/*{{{*/
	{
		var x1 = 0, y1 = 0, x2 = 0, y2 = 0, ox, oy;

		function setPressed(pos)/*{{{*/
		{
			var pos = rebound(pos);
			x2 = x1 = pos[0];
			y2 = y1 = pos[1];
		};
		/*}}}*/
		function setCurrent(pos)/*{{{*/
		{
			var pos = rebound(pos);
			ox = pos[0] - x2;
			oy = pos[1] - y2;
			x2 = pos[0];
			y2 = pos[1];
		};
		/*}}}*/
		function getOffset()/*{{{*/
		{
			return [ ox, oy ];
		};
		/*}}}*/
		function moveOffset(offset)/*{{{*/
		{
			var ox = offset[0], oy = offset[1];

			if (0 > x1 + ox) ox -= ox + x1;
			if (0 > y1 + oy) oy -= oy + y1;

			if (boundy < y2 + oy) oy += boundy - (y2 + oy);
			if (boundx < x2 + ox) ox += boundx - (x2 + ox);

			x1 += ox;
			x2 += ox;
			y1 += oy;
			y2 += oy;
		};
		/*}}}*/
		function getCorner(ord)/*{{{*/
		{
			var c = getFixed();
			switch(ord)
			{
				case 'ne': return [ c.x2, c.y ];
				case 'nw': return [ c.x, c.y ];
				case 'se': return [ c.x2, c.y2 ];
				case 'sw': return [ c.x, c.y2 ];
			}
		};
		/*}}}*/
		function getFixed()/*{{{*/
		{
			if (!options.aspectRatio) return getRect();
			// This function could use some optimization I think...
			var aspect = options.aspectRatio,
				min_x = options.minSize[0]/xscale, 
				min_y = options.minSize[1]/yscale,
				max_x = options.maxSize[0]/xscale, 
				max_y = options.maxSize[1]/yscale,
				rw = x2 - x1,
				rh = y2 - y1,
				rwa = Math.abs(rw),
				rha = Math.abs(rh),
				real_ratio = rwa / rha,
				xx, yy
			;
			if (max_x == 0) { max_x = boundx * 10 }
			if (max_y == 0) { max_y = boundy * 10 }
			if (real_ratio < aspect)
			{
				yy = y2;
				w = rha * aspect;
				xx = rw < 0 ? x1 - w : w + x1;

				if (xx < 0)
				{
					xx = 0;
					h = Math.abs((xx - x1) / aspect);
					yy = rh < 0 ? y1 - h: h + y1;
				}
				else if (xx > boundx)
				{
					xx = boundx;
					h = Math.abs((xx - x1) / aspect);
					yy = rh < 0 ? y1 - h : h + y1;
				}
			}
			else
			{
				xx = x2;
				h = rwa / aspect;
				yy = rh < 0 ? y1 - h : y1 + h;
				if (yy < 0)
				{
					yy = 0;
					w = Math.abs((yy - y1) * aspect);
					xx = rw < 0 ? x1 - w : w + x1;
				}
				else if (yy > boundy)
				{
					yy = boundy;
					w = Math.abs(yy - y1) * aspect;
					xx = rw < 0 ? x1 - w : w + x1;
				}
			}

			// Magic %-)
			if(xx > x1) { // right side
			  if(xx - x1 < min_x) {
				xx = x1 + min_x;
			  } else if (xx - x1 > max_x) {
				xx = x1 + max_x;
			  }
			  if(yy > y1) {
				yy = y1 + (xx - x1)/aspect;
			  } else {
				yy = y1 - (xx - x1)/aspect;
			  }
			} else if (xx < x1) { // left side
			  if(x1 - xx < min_x) {
				xx = x1 - min_x
			  } else if (x1 - xx > max_x) {
				xx = x1 - max_x;
			  }
			  if(yy > y1) {
				yy = y1 + (x1 - xx)/aspect;
			  } else {
				yy = y1 - (x1 - xx)/aspect;
			  }
			}

			if(xx < 0) {
				x1 -= xx;
				xx = 0;
			} else  if (xx > boundx) {
				x1 -= xx - boundx;
				xx = boundx;
			}

			if(yy < 0) {
				y1 -= yy;
				yy = 0;
			} else  if (yy > boundy) {
				y1 -= yy - boundy;
				yy = boundy;
			}

			return last = makeObj(flipCoords(x1,y1,xx,yy));
		};
		/*}}}*/
		function rebound(p)/*{{{*/
		{
			if (p[0] < 0) p[0] = 0;
			if (p[1] < 0) p[1] = 0;

			if (p[0] > boundx) p[0] = boundx;
			if (p[1] > boundy) p[1] = boundy;

			return [ p[0], p[1] ];
		};
		/*}}}*/
		function flipCoords(x1,y1,x2,y2)/*{{{*/
		{
			var xa = x1, xb = x2, ya = y1, yb = y2;
			if (x2 < x1)
			{
				xa = x2;
				xb = x1;
			}
			if (y2 < y1)
			{
				ya = y2;
				yb = y1;
			}
			return [ Math.round(xa), Math.round(ya), Math.round(xb), Math.round(yb) ];
		};
		/*}}}*/
		function getRect()/*{{{*/
		{
			var xsize = x2 - x1;
			var ysize = y2 - y1;

			if (xlimit && (Math.abs(xsize) > xlimit))
				x2 = (xsize > 0) ? (x1 + xlimit) : (x1 - xlimit);
			if (ylimit && (Math.abs(ysize) > ylimit))
				y2 = (ysize > 0) ? (y1 + ylimit) : (y1 - ylimit);

			if (ymin && (Math.abs(ysize) < ymin))
				y2 = (ysize > 0) ? (y1 + ymin) : (y1 - ymin);
			if (xmin && (Math.abs(xsize) < xmin))
				x2 = (xsize > 0) ? (x1 + xmin) : (x1 - xmin);

			if (x1 < 0) { x2 -= x1; x1 -= x1; }
			if (y1 < 0) { y2 -= y1; y1 -= y1; }
			if (x2 < 0) { x1 -= x2; x2 -= x2; }
			if (y2 < 0) { y1 -= y2; y2 -= y2; }
			if (x2 > boundx) { var delta = x2 - boundx; x1 -= delta; x2 -= delta; }
			if (y2 > boundy) { var delta = y2 - boundy; y1 -= delta; y2 -= delta; }
			if (x1 > boundx) { var delta = x1 - boundy; y2 -= delta; y1 -= delta; }
			if (y1 > boundy) { var delta = y1 - boundy; y2 -= delta; y1 -= delta; }

			return makeObj(flipCoords(x1,y1,x2,y2));
		};
		/*}}}*/
		function makeObj(a)/*{{{*/
		{
			return { x: a[0], y: a[1], x2: a[2], y2: a[3],
				w: a[2] - a[0], h: a[3] - a[1] };
		};
		/*}}}*/

		return {
			flipCoords: flipCoords,
			setPressed: setPressed,
			setCurrent: setCurrent,
			getOffset: getOffset,
			moveOffset: moveOffset,
			getCorner: getCorner,
			getFixed: getFixed
		};
	}();

	/*}}}*/
	var Selection = function()/*{{{*/
	{
		var start, end, dragmode, awake, hdep = 370;
		var borders = { };
		var handle = { };
		var seehandles = false;
		var hhs = options.handleOffset;

		/* Insert draggable elements {{{*/

		// Insert border divs for outline
		if (options.drawBorders) {
			borders = {
					top: insertBorder('hline')
						.css('top',$.browser.msie?px(-1):px(0)),
					bottom: insertBorder('hline'),
					left: insertBorder('vline'),
					right: insertBorder('vline')
			};
		}

		// Insert handles on edges
		if (options.dragEdges) {
			handle.t = insertDragbar('n');
			handle.b = insertDragbar('s');
			handle.r = insertDragbar('e');
			handle.l = insertDragbar('w');
		}

		// Insert side handles
		options.sideHandles &&
			createHandles(['n','s','e','w']);

		// Insert corner handles
		options.cornerHandles &&
			createHandles(['sw','nw','ne','se']);

		/*}}}*/
		// Private Methods
		function insertBorder(type)/*{{{*/
		{
			var jq = $('<div />')
				.css({position: 'absolute', opacity: options.borderOpacity })
				.addClass(cssClass(type));
			$img_holder.append(jq);
			return jq;
		};
		/*}}}*/
		function dragDiv(ord,zi)/*{{{*/
		{
			var jq = $('<div />')
				.mousedown(createDragger(ord))
				.css({
					cursor: ord+'-resize',
					position: 'absolute',
					zIndex: zi 
				})
			;
			$hdl_holder.append(jq);
			return jq;
		};
		/*}}}*/
		function insertHandle(ord)/*{{{*/
		{
			return dragDiv(ord,hdep++)
				.css({ top: px(-hhs+1), left: px(-hhs+1), opacity: options.handleOpacity })
				.addClass(cssClass('handle'));
		};
		/*}}}*/
		function insertDragbar(ord)/*{{{*/
		{
			var s = options.handleSize,
				o = hhs,
				h = s, w = s,
				t = o, l = o;

			switch(ord)
			{
				case 'n': case 's': w = pct(100); break;
				case 'e': case 'w': h = pct(100); break;
			}

			return dragDiv(ord,hdep++).width(w).height(h)
				.css({ top: px(-t+1), left: px(-l+1)});
		};
		/*}}}*/
		function createHandles(li)/*{{{*/
		{
			for(i in li) handle[li[i]] = insertHandle(li[i]);
		};
		/*}}}*/
		function moveHandles(c)/*{{{*/
		{
			var midvert  = Math.round((c.h / 2) - hhs),
				midhoriz = Math.round((c.w / 2) - hhs),
				north = west = -hhs+1,
				east = c.w - hhs,
				south = c.h - hhs,
				x, y;

			'e' in handle &&
				handle.e.css({ top: px(midvert), left: px(east) }) &&
				handle.w.css({ top: px(midvert) }) &&
				handle.s.css({ top: px(south), left: px(midhoriz) }) &&
				handle.n.css({ left: px(midhoriz) });

			'ne' in handle &&
				handle.ne.css({ left: px(east) }) &&
				handle.se.css({ top: px(south), left: px(east) }) &&
				handle.sw.css({ top: px(south) });

			'b' in handle &&
				handle.b.css({ top: px(south) }) &&
				handle.r.css({ left: px(east) });
		};
		/*}}}*/
		function moveto(x,y)/*{{{*/
		{
			$img2.css({ top: px(-y), left: px(-x) });
			$sel.css({ top: px(y), left: px(x) });
		};
		/*}}}*/
		function resize(w,h)/*{{{*/
		{
			$sel.width(w).height(h);
		};
		/*}}}*/
		function refresh()/*{{{*/
		{
			var c = Coords.getFixed();

			Coords.setPressed([c.x,c.y]);
			Coords.setCurrent([c.x2,c.y2]);

			updateVisible();
		};
		/*}}}*/

		// Internal Methods
		function updateVisible()/*{{{*/
			{ if (awake) return update(); };
		/*}}}*/
		function update()/*{{{*/
		{
			var c = Coords.getFixed();

			resize(c.w,c.h);
			moveto(c.x,c.y);

			options.drawBorders &&
				borders['right'].css({ left: px(c.w-1) }) &&
					borders['bottom'].css({ top: px(c.h-1) });

			seehandles && moveHandles(c);
			awake || show();

			options.onChange(unscale(c));
		};
		/*}}}*/
		function show()/*{{{*/
		{
			$sel.show();
			$img.css('opacity',options.bgOpacity);
			awake = true;
		};
		/*}}}*/
		function release()/*{{{*/
		{
			disableHandles();
			$sel.hide();
			$img.css('opacity',1);
			awake = false;
		};
		/*}}}*/
		function showHandles()//{{{
		{
			if (seehandles)
			{
				moveHandles(Coords.getFixed());
				$hdl_holder.show();
			}
		};
		//}}}
		function enableHandles()/*{{{*/
		{ 
			seehandles = true;
			if (options.allowResize)
			{
				moveHandles(Coords.getFixed());
				$hdl_holder.show();
				return true;
			}
		};
		/*}}}*/
		function disableHandles()/*{{{*/
		{
			seehandles = false;
			$hdl_holder.hide();
		};
		/*}}}*/
		function animMode(v)/*{{{*/
		{
			(animating = v) ? disableHandles(): enableHandles();
		};
		/*}}}*/
		function done()/*{{{*/
		{
			animMode(false);
			refresh();
		};
		/*}}}*/

		var $track = newTracker().mousedown(createDragger('move'))
				.css({ cursor: 'move', position: 'absolute', zIndex: 360 })

		$img_holder.append($track);
		disableHandles();

		return {
			updateVisible: updateVisible,
			update: update,
			release: release,
			refresh: refresh,
			setCursor: function (cursor) { $track.css('cursor',cursor); },
			enableHandles: enableHandles,
			enableOnly: function() { seehandles = true; },
			showHandles: showHandles,
			disableHandles: disableHandles,
			animMode: animMode,
			done: done
		};
	}();
	/*}}}*/
	var Tracker = function()/*{{{*/
	{
		var onMove		= function() { },
			onDone		= function() { },
			trackDoc	= options.trackDocument;

		if (!trackDoc)
		{
			$trk
				.mousemove(trackMove)
				.mouseup(trackUp)
				.mouseout(trackUp)
			;
		}

		function toFront()/*{{{*/
		{
			$trk.css({zIndex:450});
			if (trackDoc)
			{
				$(document)
					.mousemove(trackMove)
					.mouseup(trackUp)
				;
			}
		}
		/*}}}*/
		function toBack()/*{{{*/
		{
			$trk.css({zIndex:290});
			if (trackDoc)
			{
				$(document)
					.unbind('mousemove',trackMove)
					.unbind('mouseup',trackUp)
				;
			}
		}
		/*}}}*/
		function trackMove(e)/*{{{*/
		{
			onMove(mouseAbs(e));
		};
		/*}}}*/
		function trackUp(e)/*{{{*/
		{
			e.preventDefault();
			e.stopPropagation();

			if (btndown)
			{
				btndown = false;

				onDone(mouseAbs(e));
				options.onSelect(unscale(Coords.getFixed()));
				toBack();
				onMove = function() { };
				onDone = function() { };
			}

			return false;
		};
		/*}}}*/

		function activateHandlers(move,done)/* {{{ */
		{
			btndown = true;
			onMove = move;
			onDone = done;
			toFront();
			return false;
		};
		/* }}} */

		function setCursor(t) { $trk.css('cursor',t); };

		$img.before($trk);
		return {
			activateHandlers: activateHandlers,
			setCursor: setCursor
		};
	}();
	/*}}}*/
	var KeyManager = function()/*{{{*/
	{
		var $keymgr = $('<input type="radio" />')
				.css({ position: 'absolute', left: '-30px' })
				.keypress(parseKey)
				.blur(onBlur),

			$keywrap = $('<div />')
				.css({
					position: 'absolute',
					overflow: 'hidden'
				})
				.append($keymgr)
		;

		function watchKeys()/*{{{*/
		{
			if (options.keySupport)
			{
				$keymgr.show();
				$keymgr.focus();
			}
		};
		/*}}}*/
		function onBlur(e)/*{{{*/
		{
			$keymgr.hide();
		};
		/*}}}*/
		function doNudge(e,x,y)/*{{{*/
		{
			if (options.allowMove) {
				Coords.moveOffset([x,y]);
				Selection.updateVisible();
			};
			e.preventDefault();
			e.stopPropagation();
		};
		/*}}}*/
		function parseKey(e)/*{{{*/
		{
			if (e.ctrlKey) return true;
			shift_down = e.shiftKey ? true : false;
			var nudge = shift_down ? 10 : 1;
			switch(e.keyCode)
			{
				case 37: doNudge(e,-nudge,0); break;
				case 39: doNudge(e,nudge,0); break;
				case 38: doNudge(e,0,-nudge); break;
				case 40: doNudge(e,0,nudge); break;

				case 27: Selection.release(); break;

				case 9: return true;
			}

			return nothing(e);
		};
		/*}}}*/
		
		if (options.keySupport) $keywrap.insertBefore($img);
		return {
			watchKeys: watchKeys
		};
	}();
	/*}}}*/

	// }}}
	// Internal Methods {{{

	function px(n) { return '' + parseInt(n) + 'px'; };
	function pct(n) { return '' + parseInt(n) + '%'; };
	function cssClass(cl) { return options.baseClass + '-' + cl; };
	function getPos(obj)/*{{{*/
	{
		// Updated in v0.9.4 to use built-in dimensions plugin
		var pos = $(obj).offset();
		return [ pos.left, pos.top ];
	};
	/*}}}*/
	function mouseAbs(e)/*{{{*/
	{
		return [ (e.pageX - docOffset[0]), (e.pageY - docOffset[1]) ];
	};
	/*}}}*/
	function myCursor(type)/*{{{*/
	{
		if (type != lastcurs)
		{
			Tracker.setCursor(type);
			//Handles.xsetCursor(type);
			lastcurs = type;
		}
	};
	/*}}}*/
	function startDragMode(mode,pos)/*{{{*/
	{
		docOffset = getPos($img);
		Tracker.setCursor(mode=='move'?mode:mode+'-resize');

		if (mode == 'move')
			return Tracker.activateHandlers(createMover(pos), doneSelect);

		var fc = Coords.getFixed();
		var opp = oppLockCorner(mode);
		var opc = Coords.getCorner(oppLockCorner(opp));

		Coords.setPressed(Coords.getCorner(opp));
		Coords.setCurrent(opc);

		Tracker.activateHandlers(dragmodeHandler(mode,fc),doneSelect);
	};
	/*}}}*/
	function dragmodeHandler(mode,f)/*{{{*/
	{
		return function(pos) {
			if (!options.aspectRatio) switch(mode)
			{
				case 'e': pos[1] = f.y2; break;
				case 'w': pos[1] = f.y2; break;
				case 'n': pos[0] = f.x2; break;
				case 's': pos[0] = f.x2; break;
			}
			else switch(mode)
			{
				case 'e': pos[1] = f.y+1; break;
				case 'w': pos[1] = f.y+1; break;
				case 'n': pos[0] = f.x+1; break;
				case 's': pos[0] = f.x+1; break;
			}
			Coords.setCurrent(pos);
			Selection.update();
		};
	};
	/*}}}*/
	function createMover(pos)/*{{{*/
	{
		var lloc = pos;
		KeyManager.watchKeys();

		return function(pos)
		{
			Coords.moveOffset([pos[0] - lloc[0], pos[1] - lloc[1]]);
			lloc = pos;
			
			Selection.update();
		};
	};
	/*}}}*/
	function oppLockCorner(ord)/*{{{*/
	{
		switch(ord)
		{
			case 'n': return 'sw';
			case 's': return 'nw';
			case 'e': return 'nw';
			case 'w': return 'ne';
			case 'ne': return 'sw';
			case 'nw': return 'se';
			case 'se': return 'nw';
			case 'sw': return 'ne';
		};
	};
	/*}}}*/
	function createDragger(ord)/*{{{*/
	{
		return function(e) {
			if (options.disabled) return false;
			if ((ord == 'move') && !options.allowMove) return false;
			btndown = true;
			startDragMode(ord,mouseAbs(e));
			e.stopPropagation();
			e.preventDefault();
			return false;
		};
	};
	/*}}}*/
	function presize($obj,w,h)/*{{{*/
	{
		var nw = $obj.width(), nh = $obj.height();
		if ((nw > w) && w > 0)
		{
			nw = w;
			nh = (w/$obj.width()) * $obj.height();
		}
		if ((nh > h) && h > 0)
		{
			nh = h;
			nw = (h/$obj.height()) * $obj.width();
		}
		xscale = $obj.width() / nw;
		yscale = $obj.height() / nh;
		$obj.width(nw).height(nh);
	};
	/*}}}*/
	function unscale(c)/*{{{*/
	{
		return {
			x: parseInt(c.x * xscale), y: parseInt(c.y * yscale), 
			x2: parseInt(c.x2 * xscale), y2: parseInt(c.y2 * yscale), 
			w: parseInt(c.w * xscale), h: parseInt(c.h * yscale)
		};
	};
	/*}}}*/
	function doneSelect(pos)/*{{{*/
	{
		var c = Coords.getFixed();
		if (c.w > options.minSelect[0] && c.h > options.minSelect[1])
		{
			Selection.enableHandles();
			Selection.done();
		}
		else
		{
			Selection.release();
		}
		Tracker.setCursor( options.allowSelect?'crosshair':'default' );
	};
	/*}}}*/
	function newSelection(e)/*{{{*/
	{
		if (options.disabled) return false;
		if (!options.allowSelect) return false;
		btndown = true;
		docOffset = getPos($img);
		Selection.disableHandles();
		myCursor('crosshair');
		var pos = mouseAbs(e);
		Coords.setPressed(pos);
		Tracker.activateHandlers(selectDrag,doneSelect);
		KeyManager.watchKeys();
		Selection.update();

		e.stopPropagation();
		e.preventDefault();
		return false;
	};
	/*}}}*/
	function selectDrag(pos)/*{{{*/
	{
		Coords.setCurrent(pos);
		Selection.update();
	};
	/*}}}*/
	function newTracker()
	{
		var trk = $('<div></div>').addClass(cssClass('tracker'));
		$.browser.msie && trk.css({ opacity: 0, backgroundColor: 'white' });
		return trk;
	};

	// }}}
	// API methods {{{
		
	function animateTo(a)/*{{{*/
	{
		var x1 = a[0] / xscale,
			y1 = a[1] / yscale,
			x2 = a[2] / xscale,
			y2 = a[3] / yscale;

		if (animating) return;

		var animto = Coords.flipCoords(x1,y1,x2,y2);
		var c = Coords.getFixed();
		var animat = initcr = [ c.x, c.y, c.x2, c.y2 ];
		var interv = options.animationDelay;

		var x = animat[0];
		var y = animat[1];
		var x2 = animat[2];
		var y2 = animat[3];
		var ix1 = animto[0] - initcr[0];
		var iy1 = animto[1] - initcr[1];
		var ix2 = animto[2] - initcr[2];
		var iy2 = animto[3] - initcr[3];
		var pcent = 0;
		var velocity = options.swingSpeed;

		Selection.animMode(true);

		var animator = function()
		{
			return function()
			{
				pcent += (100 - pcent) / velocity;

				animat[0] = x + ((pcent / 100) * ix1);
				animat[1] = y + ((pcent / 100) * iy1);
				animat[2] = x2 + ((pcent / 100) * ix2);
				animat[3] = y2 + ((pcent / 100) * iy2);

				if (pcent < 100) animateStart();
					else Selection.done();

				if (pcent >= 99.8) pcent = 100;

				setSelectRaw(animat);
			};
		}();

		function animateStart()
			{ window.setTimeout(animator,interv); };

		animateStart();
	};
	/*}}}*/
	function setSelect(rect)//{{{
	{
		setSelectRaw([rect[0]/xscale,rect[1]/yscale,rect[2]/xscale,rect[3]/yscale]);
	};
	//}}}
	function setSelectRaw(l) /*{{{*/
	{
		Coords.setPressed([l[0],l[1]]);
		Coords.setCurrent([l[2],l[3]]);
		Selection.update();
	};
	/*}}}*/
	function setOptions(opt)/*{{{*/
	{
		if (typeof(opt) != 'object') opt = { };
		options = $.extend(options,opt);

		if (typeof(options.onChange)!=='function')
			options.onChange = function() { };

		if (typeof(options.onSelect)!=='function')
			options.onSelect = function() { };

	};
	/*}}}*/
	function tellSelect()/*{{{*/
	{
		return unscale(Coords.getFixed());
	};
	/*}}}*/
	function tellScaled()/*{{{*/
	{
		return Coords.getFixed();
	};
	/*}}}*/
	function setOptionsNew(opt)/*{{{*/
	{
		setOptions(opt);
		interfaceUpdate();
	};
	/*}}}*/
	function disableCrop()//{{{
	{
		options.disabled = true;
		Selection.disableHandles();
		Selection.setCursor('default');
		Tracker.setCursor('default');
	};
	//}}}
	function enableCrop()//{{{
	{
		options.disabled = false;
		interfaceUpdate();
	};
	//}}}
	function cancelCrop()//{{{
	{
		Selection.done();
		Tracker.activateHandlers(null,null);
	};
	//}}}
	function destroy()//{{{
	{
		$div.remove();
		$origimg.show();
	};
	//}}}

	function interfaceUpdate(alt)//{{{
	// This method tweaks the interface based on options object.
	// Called when options are changed and at end of initialization.
	{
		options.allowResize ?
			alt?Selection.enableOnly():Selection.enableHandles():
			Selection.disableHandles();

		Tracker.setCursor( options.allowSelect? 'crosshair': 'default' );
		Selection.setCursor( options.allowMove? 'move': 'default' );

		$div.css('backgroundColor',options.bgColor);

		if ('setSelect' in options) {
			setSelect(opt.setSelect);
			Selection.done();
			delete(options.setSelect);
		}

		if ('trueSize' in options) {
			xscale = options.trueSize[0] / boundx;
			yscale = options.trueSize[1] / boundy;
		}

		xlimit = options.maxSize[0] || 0;
		ylimit = options.maxSize[1] || 0;
		xmin = options.minSize[0] || 0;
		ymin = options.minSize[1] || 0;

		if ('outerImage' in options)
		{
			$img.attr('src',options.outerImage);
			delete(options.outerImage);
		}

		Selection.refresh();
	};
	//}}}

	// }}}

	$hdl_holder.hide();
	interfaceUpdate(true);
	
	var api = {
		animateTo: animateTo,
		setSelect: setSelect,
		setOptions: setOptionsNew,
		tellSelect: tellSelect,
		tellScaled: tellScaled,

		disable: disableCrop,
		enable: enableCrop,
		cancel: cancelCrop,

		focus: KeyManager.watchKeys,

		getBounds: function() { return [ boundx * xscale, boundy * yscale ]; },
		getWidgetSize: function() { return [ boundx, boundy ]; },

		release: Selection.release,
		destroy: destroy

	};

	$origimg.data('Jcrop',api);
	return api;
};

$.fn.Jcrop = function(options)/*{{{*/
{
	function attachWhenDone(from)/*{{{*/
	{
		var loadsrc = options.useImg || from.src;
		var img = new Image();
		img.onload = function() { $.Jcrop(from,options); };
		img.src = loadsrc;
	};
	/*}}}*/
	if (typeof(options) !== 'object') options = { };

	// Iterate over each object, attach Jcrop
	this.each(function()
	{
		// If we've already attached to this object
		if ($(this).data('Jcrop'))
		{
			// The API can be requested this way (undocumented)
			if (options == 'api') return $(this).data('Jcrop');
			// Otherwise, we just reset the options...
			else $(this).data('Jcrop').setOptions(options);
		}
		// If we haven't been attached, preload and attach
		else attachWhenDone(this);
	});

	// Return "this" so we're chainable a la jQuery plugin-style!
	return this;
};
/*}}}*/

})(jQuery);
/*
 * jQuery UI 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
;jQuery.ui || (function($) {

var _remove = $.fn.remove,
	isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9);

//Helper functions and ui object
$.ui = {
	version: "1.7.2",

	// $.ui.plugin is deprecated.  Use the proxy pattern instead.
	plugin: {
		add: function(module, option, set) {
			var proto = $.ui[module].prototype;
			for(var i in set) {
				proto.plugins[i] = proto.plugins[i] || [];
				proto.plugins[i].push([option, set[i]]);
			}
		},
		call: function(instance, name, args) {
			var set = instance.plugins[name];
			if(!set || !instance.element[0].parentNode) { return; }

			for (var i = 0; i < set.length; i++) {
				if (instance.options[set[i][0]]) {
					set[i][1].apply(instance.element, args);
				}
			}
		}
	},

	contains: function(a, b) {
		return document.compareDocumentPosition
			? a.compareDocumentPosition(b) & 16
			: a !== b && a.contains(b);
	},

	hasScroll: function(el, a) {

		//If overflow is hidden, the element might have extra content, but the user wants to hide it
		if ($(el).css('overflow') == 'hidden') { return false; }

		var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop',
			has = false;

		if (el[scroll] > 0) { return true; }

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		el[scroll] = 1;
		has = (el[scroll] > 0);
		el[scroll] = 0;
		return has;
	},

	isOverAxis: function(x, reference, size) {
		//Determines when x coordinate is over "b" element axis
		return (x > reference) && (x < (reference + size));
	},

	isOver: function(y, x, top, left, height, width) {
		//Determines when x, y coordinates is over "b" element
		return $.ui.isOverAxis(y, top, height) && $.ui.isOverAxis(x, left, width);
	},

	keyCode: {
		BACKSPACE: 8,
		CAPS_LOCK: 20,
		COMMA: 188,
		CONTROL: 17,
		DELETE: 46,
		DOWN: 40,
		END: 35,
		ENTER: 13,
		ESCAPE: 27,
		HOME: 36,
		INSERT: 45,
		LEFT: 37,
		NUMPAD_ADD: 107,
		NUMPAD_DECIMAL: 110,
		NUMPAD_DIVIDE: 111,
		NUMPAD_ENTER: 108,
		NUMPAD_MULTIPLY: 106,
		NUMPAD_SUBTRACT: 109,
		PAGE_DOWN: 34,
		PAGE_UP: 33,
		PERIOD: 190,
		RIGHT: 39,
		SHIFT: 16,
		SPACE: 32,
		TAB: 9,
		UP: 38
	}
};

// WAI-ARIA normalization
if (isFF2) {
	var attr = $.attr,
		removeAttr = $.fn.removeAttr,
		ariaNS = "http://www.w3.org/2005/07/aaa",
		ariaState = /^aria-/,
		ariaRole = /^wairole:/;

	$.attr = function(elem, name, value) {
		var set = value !== undefined;

		return (name == 'role'
			? (set
				? attr.call(this, elem, name, "wairole:" + value)
				: (attr.apply(this, arguments) || "").replace(ariaRole, ""))
			: (ariaState.test(name)
				? (set
					? elem.setAttributeNS(ariaNS,
						name.replace(ariaState, "aaa:"), value)
					: attr.call(this, elem, name.replace(ariaState, "aaa:")))
				: attr.apply(this, arguments)));
	};

	$.fn.removeAttr = function(name) {
		return (ariaState.test(name)
			? this.each(function() {
				this.removeAttributeNS(ariaNS, name.replace(ariaState, ""));
			}) : removeAttr.call(this, name));
	};
}

//jQuery plugins
$.fn.extend({
	remove: function() {
		// Safari has a native remove event which actually removes DOM elements,
		// so we have to use triggerHandler instead of trigger (#3037).
		$("*", this).add(this).each(function() {
			$(this).triggerHandler("remove");
		});
		return _remove.apply(this, arguments );
	},

	enableSelection: function() {
		return this
			.attr('unselectable', 'off')
			.css('MozUserSelect', '')
			.unbind('selectstart.ui');
	},

	disableSelection: function() {
		return this
			.attr('unselectable', 'on')
			.css('MozUserSelect', 'none')
			.bind('selectstart.ui', function() { return false; });
	},

	scrollParent: function() {
		var scrollParent;
		if(($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
			scrollParent = this.parents().filter(function() {
				return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		} else {
			scrollParent = this.parents().filter(function() {
				return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		}

		return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
	}
});


//Additional selectors
$.extend($.expr[':'], {
	data: function(elem, i, match) {
		return !!$.data(elem, match[3]);
	},

	focusable: function(element) {
		var nodeName = element.nodeName.toLowerCase(),
			tabIndex = $.attr(element, 'tabindex');
		return (/input|select|textarea|button|object/.test(nodeName)
			? !element.disabled
			: 'a' == nodeName || 'area' == nodeName
				? element.href || !isNaN(tabIndex)
				: !isNaN(tabIndex))
			// the element and all of its ancestors must be visible
			// the browser may report that the area is hidden
			&& !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length;
	},

	tabbable: function(element) {
		var tabIndex = $.attr(element, 'tabindex');
		return (isNaN(tabIndex) || tabIndex >= 0) && $(element).is(':focusable');
	}
});


// $.widget is a factory to create jQuery plugins
// taking some boilerplate code out of the plugin code
function getter(namespace, plugin, method, args) {
	function getMethods(type) {
		var methods = $[namespace][plugin][type] || [];
		return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods);
	}

	var methods = getMethods('getter');
	if (args.length == 1 && typeof args[0] == 'string') {
		methods = methods.concat(getMethods('getterSetter'));
	}
	return ($.inArray(method, methods) != -1);
}

$.widget = function(name, prototype) {
	var namespace = name.split(".")[0];
	name = name.split(".")[1];

	// create plugin method
	$.fn[name] = function(options) {
		var isMethodCall = (typeof options == 'string'),
			args = Array.prototype.slice.call(arguments, 1);

		// prevent calls to internal methods
		if (isMethodCall && options.substring(0, 1) == '_') {
			return this;
		}

		// handle getter methods
		if (isMethodCall && getter(namespace, name, options, args)) {
			var instance = $.data(this[0], name);
			return (instance ? instance[options].apply(instance, args)
				: undefined);
		}

		// handle initialization and non-getter methods
		return this.each(function() {
			var instance = $.data(this, name);

			// constructor
			(!instance && !isMethodCall &&
				$.data(this, name, new $[namespace][name](this, options))._init());

			// method call
			(instance && isMethodCall && $.isFunction(instance[options]) &&
				instance[options].apply(instance, args));
		});
	};

	// create widget constructor
	$[namespace] = $[namespace] || {};
	$[namespace][name] = function(element, options) {
		var self = this;

		this.namespace = namespace;
		this.widgetName = name;
		this.widgetEventPrefix = $[namespace][name].eventPrefix || name;
		this.widgetBaseClass = namespace + '-' + name;

		this.options = $.extend({},
			$.widget.defaults,
			$[namespace][name].defaults,
			$.metadata && $.metadata.get(element)[name],
			options);

		this.element = $(element)
			.bind('setData.' + name, function(event, key, value) {
				if (event.target == element) {
					return self._setData(key, value);
				}
			})
			.bind('getData.' + name, function(event, key) {
				if (event.target == element) {
					return self._getData(key);
				}
			})
			.bind('remove', function() {
				return self.destroy();
			});
	};

	// add widget prototype
	$[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);

	// TODO: merge getter and getterSetter properties from widget prototype
	// and plugin prototype
	$[namespace][name].getterSetter = 'option';
};

$.widget.prototype = {
	_init: function() {},
	destroy: function() {
		this.element.removeData(this.widgetName)
			.removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled')
			.removeAttr('aria-disabled');
	},

	option: function(key, value) {
		var options = key,
			self = this;

		if (typeof key == "string") {
			if (value === undefined) {
				return this._getData(key);
			}
			options = {};
			options[key] = value;
		}

		$.each(options, function(key, value) {
			self._setData(key, value);
		});
	},
	_getData: function(key) {
		return this.options[key];
	},
	_setData: function(key, value) {
		this.options[key] = value;

		if (key == 'disabled') {
			this.element
				[value ? 'addClass' : 'removeClass'](
					this.widgetBaseClass + '-disabled' + ' ' +
					this.namespace + '-state-disabled')
				.attr("aria-disabled", value);
		}
	},

	enable: function() {
		this._setData('disabled', false);
	},
	disable: function() {
		this._setData('disabled', true);
	},

	_trigger: function(type, event, data) {
		var callback = this.options[type],
			eventName = (type == this.widgetEventPrefix
				? type : this.widgetEventPrefix + type);

		event = $.Event(event);
		event.type = eventName;

		// copy original event properties over to the new event
		// this would happen if we could call $.event.fix instead of $.Event
		// but we don't have a way to force an event to be fixed multiple times
		if (event.originalEvent) {
			for (var i = $.event.props.length, prop; i;) {
				prop = $.event.props[--i];
				event[prop] = event.originalEvent[prop];
			}
		}

		this.element.trigger(event, data);

		return !($.isFunction(callback) && callback.call(this.element[0], event, data) === false
			|| event.isDefaultPrevented());
	}
};

$.widget.defaults = {
	disabled: false
};


/** Mouse Interaction Plugin **/

$.ui.mouse = {
	_mouseInit: function() {
		var self = this;

		this.element
			.bind('mousedown.'+this.widgetName, function(event) {
				return self._mouseDown(event);
			})
			.bind('click.'+this.widgetName, function(event) {
				if(self._preventClickEvent) {
					self._preventClickEvent = false;
					event.stopImmediatePropagation();
					return false;
				}
			});

		// Prevent text selection in IE
		if ($.browser.msie) {
			this._mouseUnselectable = this.element.attr('unselectable');
			this.element.attr('unselectable', 'on');
		}

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.unbind('.'+this.widgetName);

		// Restore text selection in IE
		($.browser.msie
			&& this.element.attr('unselectable', this._mouseUnselectable));
	},

	_mouseDown: function(event) {
		// don't let more than one widget handle mouseStart
		// TODO: figure out why we have to use originalEvent
		event.originalEvent = event.originalEvent || {};
		if (event.originalEvent.mouseHandled) { return; }

		// we may have missed mouseup (out of window)
		(this._mouseStarted && this._mouseUp(event));

		this._mouseDownEvent = event;

		var self = this,
			btnIsLeft = (event.which == 1),
			elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if (!this.mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				self.mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted = (this._mouseStart(event) !== false);
			if (!this._mouseStarted) {
				event.preventDefault();
				return true;
			}
		}

		// these delegates are required to keep context
		this._mouseMoveDelegate = function(event) {
			return self._mouseMove(event);
		};
		this._mouseUpDelegate = function(event) {
			return self._mouseUp(event);
		};
		$(document)
			.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		// preventDefault() is used to prevent the selection of text here -
		// however, in Safari, this causes select boxes not to be selectable
		// anymore, so this fix is needed
		($.browser.safari || event.preventDefault());

		event.originalEvent.mouseHandled = true;
		return true;
	},

	_mouseMove: function(event) {
		// IE mouseup check - mouseup happened when mouse was out of window
		if ($.browser.msie && !event.button) {
			return this._mouseUp(event);
		}

		if (this._mouseStarted) {
			this._mouseDrag(event);
			return event.preventDefault();
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted =
				(this._mouseStart(this._mouseDownEvent, event) !== false);
			(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
		}

		return !this._mouseStarted;
	},

	_mouseUp: function(event) {
		$(document)
			.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		if (this._mouseStarted) {
			this._mouseStarted = false;
			this._preventClickEvent = (event.target == this._mouseDownEvent.target);
			this._mouseStop(event);
		}

		return false;
	},

	_mouseDistanceMet: function(event) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - event.pageX),
				Math.abs(this._mouseDownEvent.pageY - event.pageY)
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function(event) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function(event) {},
	_mouseDrag: function(event) {},
	_mouseStop: function(event) {},
	_mouseCapture: function(event) { return true; }
};

$.ui.mouse.defaults = {
	cancel: null,
	distance: 1,
	delay: 0
};

})(jQuery);
/*
 * jQuery UI Slider 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Slider
 *
 * Depends:
 *	ui.core.js
 */

(function($) {

$.widget("ui.slider", $.extend({}, $.ui.mouse, {

	_init: function() {

		var self = this, o = this.options;
		this._keySliding = false;
		this._handleIndex = null;
		this._detectOrientation();
		this._mouseInit();

		this.element
			.addClass("ui-slider"
				+ " ui-slider-" + this.orientation
				+ " ui-widget"
				+ " ui-widget-content"
				+ " ui-corner-all");

		this.range = $([]);

		if (o.range) {

			if (o.range === true) {
				this.range = $('<div></div>');
				if (!o.values) o.values = [this._valueMin(), this._valueMin()];
				if (o.values.length && o.values.length != 2) {
					o.values = [o.values[0], o.values[0]];
				}
			} else {
				this.range = $('<div></div>');
			}

			this.range
				.appendTo(this.element)
				.addClass("ui-slider-range");

			if (o.range == "min" || o.range == "max") {
				this.range.addClass("ui-slider-range-" + o.range);
			}

			// note: this isn't the most fittingly semantic framework class for this element,
			// but worked best visually with a variety of themes
			this.range.addClass("ui-widget-header");

		}

		if ($(".ui-slider-handle", this.element).length == 0)
			$('<a href="#"></a>')
				.appendTo(this.element)
				.addClass("ui-slider-handle");

		if (o.values && o.values.length) {
			while ($(".ui-slider-handle", this.element).length < o.values.length)
				$('<a href="#"></a>')
					.appendTo(this.element)
					.addClass("ui-slider-handle");
		}

		this.handles = $(".ui-slider-handle", this.element)
			.addClass("ui-state-default"
				+ " ui-corner-all");

		this.handle = this.handles.eq(0);

		this.handles.add(this.range).filter("a")
			.click(function(event) {
				event.preventDefault();
			})
			.hover(function() {
				if (!o.disabled) {
					$(this).addClass('ui-state-hover');
				}
			}, function() {
				$(this).removeClass('ui-state-hover');
			})
			.focus(function() {
				if (!o.disabled) {
					$(".ui-slider .ui-state-focus").removeClass('ui-state-focus'); $(this).addClass('ui-state-focus');
				} else {
					$(this).blur();
				}
			})
			.blur(function() {
				$(this).removeClass('ui-state-focus');
			});

		this.handles.each(function(i) {
			$(this).data("index.ui-slider-handle", i);
		});

		this.handles.keydown(function(event) {

			var ret = true;

			var index = $(this).data("index.ui-slider-handle");

			if (self.options.disabled)
				return;

			switch (event.keyCode) {
				case $.ui.keyCode.HOME:
				case $.ui.keyCode.END:
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					ret = false;
					if (!self._keySliding) {
						self._keySliding = true;
						$(this).addClass("ui-state-active");
						self._start(event, index);
					}
					break;
			}

			var curVal, newVal, step = self._step();
			if (self.options.values && self.options.values.length) {
				curVal = newVal = self.values(index);
			} else {
				curVal = newVal = self.value();
			}

			switch (event.keyCode) {
				case $.ui.keyCode.HOME:
					newVal = self._valueMin();
					break;
				case $.ui.keyCode.END:
					newVal = self._valueMax();
					break;
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
					if(curVal == self._valueMax()) return;
					newVal = curVal + step;
					break;
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					if(curVal == self._valueMin()) return;
					newVal = curVal - step;
					break;
			}

			self._slide(event, index, newVal);

			return ret;

		}).keyup(function(event) {

			var index = $(this).data("index.ui-slider-handle");

			if (self._keySliding) {
				self._stop(event, index);
				self._change(event, index);
				self._keySliding = false;
				$(this).removeClass("ui-state-active");
			}

		});

		this._refreshValue();

	},

	destroy: function() {

		this.handles.remove();
		this.range.remove();

		this.element
			.removeClass("ui-slider"
				+ " ui-slider-horizontal"
				+ " ui-slider-vertical"
				+ " ui-slider-disabled"
				+ " ui-widget"
				+ " ui-widget-content"
				+ " ui-corner-all")
			.removeData("slider")
			.unbind(".slider");

		this._mouseDestroy();

	},

	_mouseCapture: function(event) {

		var o = this.options;

		if (o.disabled)
			return false;

		this.elementSize = {
			width: this.element.outerWidth(),
			height: this.element.outerHeight()
		};
		this.elementOffset = this.element.offset();

		var position = { x: event.pageX, y: event.pageY };
		var normValue = this._normValueFromMouse(position);

		var distance = this._valueMax() - this._valueMin() + 1, closestHandle;
		var self = this, index;
		this.handles.each(function(i) {
			var thisDistance = Math.abs(normValue - self.values(i));
			if (distance > thisDistance) {
				distance = thisDistance;
				closestHandle = $(this);
				index = i;
			}
		});

		// workaround for bug #3736 (if both handles of a range are at 0,
		// the first is always used as the one with least distance,
		// and moving it is obviously prevented by preventing negative ranges)
		if(o.range == true && this.values(1) == o.min) {
			closestHandle = $(this.handles[++index]);
		}

		this._start(event, index);

		self._handleIndex = index;

		closestHandle
			.addClass("ui-state-active")
			.focus();
		
		var offset = closestHandle.offset();
		var mouseOverHandle = !$(event.target).parents().andSelf().is('.ui-slider-handle');
		this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
			left: event.pageX - offset.left - (closestHandle.width() / 2),
			top: event.pageY - offset.top
				- (closestHandle.height() / 2)
				- (parseInt(closestHandle.css('borderTopWidth'),10) || 0)
				- (parseInt(closestHandle.css('borderBottomWidth'),10) || 0)
				+ (parseInt(closestHandle.css('marginTop'),10) || 0)
		};

		normValue = this._normValueFromMouse(position);
		this._slide(event, index, normValue);
		return true;

	},

	_mouseStart: function(event) {
		return true;
	},

	_mouseDrag: function(event) {

		var position = { x: event.pageX, y: event.pageY };
		var normValue = this._normValueFromMouse(position);
		
		this._slide(event, this._handleIndex, normValue);

		return false;

	},

	_mouseStop: function(event) {

		this.handles.removeClass("ui-state-active");
		this._stop(event, this._handleIndex);
		this._change(event, this._handleIndex);
		this._handleIndex = null;
		this._clickOffset = null;

		return false;

	},
	
	_detectOrientation: function() {
		this.orientation = this.options.orientation == 'vertical' ? 'vertical' : 'horizontal';
	},

	_normValueFromMouse: function(position) {

		var pixelTotal, pixelMouse;
		if ('horizontal' == this.orientation) {
			pixelTotal = this.elementSize.width;
			pixelMouse = position.x - this.elementOffset.left - (this._clickOffset ? this._clickOffset.left : 0);
		} else {
			pixelTotal = this.elementSize.height;
			pixelMouse = position.y - this.elementOffset.top - (this._clickOffset ? this._clickOffset.top : 0);
		}

		var percentMouse = (pixelMouse / pixelTotal);
		if (percentMouse > 1) percentMouse = 1;
		if (percentMouse < 0) percentMouse = 0;
		if ('vertical' == this.orientation)
			percentMouse = 1 - percentMouse;

		var valueTotal = this._valueMax() - this._valueMin(),
			valueMouse = percentMouse * valueTotal,
			valueMouseModStep = valueMouse % this.options.step,
			normValue = this._valueMin() + valueMouse - valueMouseModStep;

		if (valueMouseModStep > (this.options.step / 2))
			normValue += this.options.step;

		// Since JavaScript has problems with large floats, round
		// the final value to 5 digits after the decimal point (see #4124)
		return parseFloat(normValue.toFixed(5));

	},

	_start: function(event, index) {
		var uiHash = {
			handle: this.handles[index],
			value: this.value()
		};
		if (this.options.values && this.options.values.length) {
			uiHash.value = this.values(index);
			uiHash.values = this.values();
		}
		this._trigger("start", event, uiHash);
	},

	_slide: function(event, index, newVal) {

		var handle = this.handles[index];

		if (this.options.values && this.options.values.length) {

			var otherVal = this.values(index ? 0 : 1);

			if ((this.options.values.length == 2 && this.options.range === true) && 
				((index == 0 && newVal > otherVal) || (index == 1 && newVal < otherVal))){
 				newVal = otherVal;
			}

			if (newVal != this.values(index)) {
				var newValues = this.values();
				newValues[index] = newVal;
				// A slide can be canceled by returning false from the slide callback
				var allowed = this._trigger("slide", event, {
					handle: this.handles[index],
					value: newVal,
					values: newValues
				});
				var otherVal = this.values(index ? 0 : 1);
				if (allowed !== false) {
					this.values(index, newVal, ( event.type == 'mousedown' && this.options.animate ), true);
				}
			}

		} else {

			if (newVal != this.value()) {
				// A slide can be canceled by returning false from the slide callback
				var allowed = this._trigger("slide", event, {
					handle: this.handles[index],
					value: newVal
				});
				if (allowed !== false) {
					this._setData('value', newVal, ( event.type == 'mousedown' && this.options.animate ));
				}
					
			}

		}

	},

	_stop: function(event, index) {
		var uiHash = {
			handle: this.handles[index],
			value: this.value()
		};
		if (this.options.values && this.options.values.length) {
			uiHash.value = this.values(index);
			uiHash.values = this.values();
		}
		this._trigger("stop", event, uiHash);
	},

	_change: function(event, index) {
		var uiHash = {
			handle: this.handles[index],
			value: this.value()
		};
		if (this.options.values && this.options.values.length) {
			uiHash.value = this.values(index);
			uiHash.values = this.values();
		}
		this._trigger("change", event, uiHash);
	},

	value: function(newValue) {

		if (arguments.length) {
			this._setData("value", newValue);
			this._change(null, 0);
		}

		return this._value();

	},

	values: function(index, newValue, animated, noPropagation) {

		if (arguments.length > 1) {
			this.options.values[index] = newValue;
			this._refreshValue(animated);
			if(!noPropagation) this._change(null, index);
		}

		if (arguments.length) {
			if (this.options.values && this.options.values.length) {
				return this._values(index);
			} else {
				return this.value();
			}
		} else {
			return this._values();
		}

	},

	_setData: function(key, value, animated) {

		$.widget.prototype._setData.apply(this, arguments);

		switch (key) {
			case 'disabled':
				if (value) {
					this.handles.filter(".ui-state-focus").blur();
					this.handles.removeClass("ui-state-hover");
					this.handles.attr("disabled", "disabled");
				} else {
					this.handles.removeAttr("disabled");
				}
			case 'orientation':

				this._detectOrientation();
				
				this.element
					.removeClass("ui-slider-horizontal ui-slider-vertical")
					.addClass("ui-slider-" + this.orientation);
				this._refreshValue(animated);
				break;
			case 'value':
				this._refreshValue(animated);
				break;
		}

	},

	_step: function() {
		var step = this.options.step;
		return step;
	},

	_value: function() {

		var val = this.options.value;
		if (val < this._valueMin()) val = this._valueMin();
		if (val > this._valueMax()) val = this._valueMax();

		return val;

	},

	_values: function(index) {

		if (arguments.length) {
			var val = this.options.values[index];
			if (val < this._valueMin()) val = this._valueMin();
			if (val > this._valueMax()) val = this._valueMax();

			return val;
		} else {
			return this.options.values;
		}

	},

	_valueMin: function() {
		var valueMin = this.options.min;
		return valueMin;
	},

	_valueMax: function() {
		var valueMax = this.options.max;
		return valueMax;
	},

	_refreshValue: function(animate) {

		var oRange = this.options.range, o = this.options, self = this;

		if (this.options.values && this.options.values.length) {
			var vp0, vp1;
			this.handles.each(function(i, j) {
				var valPercent = (self.values(i) - self._valueMin()) / (self._valueMax() - self._valueMin()) * 100;
				var _set = {}; _set[self.orientation == 'horizontal' ? 'left' : 'bottom'] = valPercent + '%';
				$(this).stop(1,1)[animate ? 'animate' : 'css'](_set, o.animate);
				if (self.options.range === true) {
					if (self.orientation == 'horizontal') {
						(i == 0) && self.range.stop(1,1)[animate ? 'animate' : 'css']({ left: valPercent + '%' }, o.animate);
						(i == 1) && self.range[animate ? 'animate' : 'css']({ width: (valPercent - lastValPercent) + '%' }, { queue: false, duration: o.animate });
					} else {
						(i == 0) && self.range.stop(1,1)[animate ? 'animate' : 'css']({ bottom: (valPercent) + '%' }, o.animate);
						(i == 1) && self.range[animate ? 'animate' : 'css']({ height: (valPercent - lastValPercent) + '%' }, { queue: false, duration: o.animate });
					}
				}
				lastValPercent = valPercent;
			});
		} else {
			var value = this.value(),
				valueMin = this._valueMin(),
				valueMax = this._valueMax(),
				valPercent = valueMax != valueMin
					? (value - valueMin) / (valueMax - valueMin) * 100
					: 0;
			var _set = {}; _set[self.orientation == 'horizontal' ? 'left' : 'bottom'] = valPercent + '%';
			this.handle.stop(1,1)[animate ? 'animate' : 'css'](_set, o.animate);

			(oRange == "min") && (this.orientation == "horizontal") && this.range.stop(1,1)[animate ? 'animate' : 'css']({ width: valPercent + '%' }, o.animate);
			(oRange == "max") && (this.orientation == "horizontal") && this.range[animate ? 'animate' : 'css']({ width: (100 - valPercent) + '%' }, { queue: false, duration: o.animate });
			(oRange == "min") && (this.orientation == "vertical") && this.range.stop(1,1)[animate ? 'animate' : 'css']({ height: valPercent + '%' }, o.animate);
			(oRange == "max") && (this.orientation == "vertical") && this.range[animate ? 'animate' : 'css']({ height: (100 - valPercent) + '%' }, { queue: false, duration: o.animate });
		}

	}
	
}));

$.extend($.ui.slider, {
	getter: "value values",
	version: "1.7.2",
	eventPrefix: "slide",
	defaults: {
		animate: false,
		delay: 0,
		distance: 0,
		max: 100,
		min: 0,
		orientation: 'horizontal',
		range: false,
		step: 1,
		value: 0,
		values: null
	}
});

})(jQuery);
/**
 * jquery.scrollFollow.js
 * Copyright (c) 2008 Net Perspective (http://kitchen.net-perspective.com/)
 * Licensed under the MIT License (http://www.opensource.org/licenses/mit-license.php)
 * 
 * @author R.A. Ray
 *
 * @projectDescription	jQuery plugin for allowing an element to animate down as the user scrolls the page.
 * 
 * @version 0.4.0
 * 
 * @requires jquery.js (tested with 1.2.6)
 * @requires ui.core.js (tested with 1.5.2)
 * 
 * @optional jquery.cookie.js (http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/)
 * @optional jquery.easing.js (http://gsgd.co.uk/sandbox/jquery/easing/ - tested with 1.3)
 * 
 * @param speed		int - Duration of animation (in milliseconds)
 * 								default: 500
 * @param offset			int - Number of pixels box should remain from top of viewport
 * 								default: 0
 * @param easing		string - Any one of the easing options from the easing plugin - Requires jQuery Easing Plugin < http://gsgd.co.uk/sandbox/jquery/easing/ >
 * 								default: 'linear'
 * @param container	string - ID of the containing div
 * 								default: box's immediate parent
 * @param killSwitch	string - ID of the On/Off toggle element
 * 								default: 'killSwitch'
 * @param onText		string - killSwitch text to be displayed if sliding is enabled
 * 								default: 'Turn Slide Off'
 * @param offText		string - killSwitch text to be displayed if sliding is disabled
 * 								default: 'Turn Slide On'
 * @param relativeTo	string - Scroll animation can be relative to either the 'top' or 'bottom' of the viewport
 * 								default: 'top'
 * @param delay			int - Time between the end of the scroll and the beginning of the animation in milliseconds
 * 								default: 0
 */

( function( $ ) {
	
	$.scrollFollow = function ( box, options )
	{ 
		// Convert box into a jQuery object
		box = $( box );
		
		// 'box' is the object to be animated
		var position = box.css( 'position' );
		
		function ani()
		{		
			// The script runs on every scroll which really means many times during a scroll.
			// We don't want multiple slides to queue up.
			box.queue( [ ] );
		
			// A bunch of values we need to determine where to animate to
			var viewportHeight = parseInt( $( window ).height() );	
			var pageScroll =  parseInt( $( document ).scrollTop() );
			var parentTop =  parseInt( box.cont.offset().top );
			var parentHeight = parseInt( box.cont.attr( 'offsetHeight' ) );
			var boxHeight = parseInt( box.attr( 'offsetHeight' ) + ( parseInt( box.css( 'marginTop' ) ) || 0 ) + ( parseInt( box.css( 'marginBottom' ) ) || 0 ) );
			var aniTop;
			
			// Make sure the user wants the animation to happen
			if ( isActive )
			{
				// If the box should animate relative to the top of the window
				if ( options.relativeTo == 'top' )
				{
					// Don't animate until the top of the window is close enough to the top of the box
					if ( box.initialOffsetTop >= ( pageScroll + options.offset ) )
					{
						aniTop = box.initialTop;
					}
					else
					{
						aniTop = Math.min( ( Math.max( ( -parentTop ), ( pageScroll - box.initialOffsetTop + box.initialTop ) ) + options.offset ), ( parentHeight - boxHeight - box.paddingAdjustment ) );
					}
				}
				// If the box should animate relative to the bottom of the window
				else if ( options.relativeTo == 'bottom' )
				{
					// Don't animate until the bottom of the window is close enough to the bottom of the box
					if ( ( box.initialOffsetTop + boxHeight ) >= ( pageScroll + options.offset + viewportHeight ) )
					{
						aniTop = box.initialTop;
					}
					else
					{
						aniTop = Math.min( ( pageScroll + viewportHeight - boxHeight - options.offset ), ( parentHeight - boxHeight ) );
					}
				}
				
				// Checks to see if the relevant scroll was the last one
				// "-20" is to account for inaccuracy in the timeout
				if ( ( new Date().getTime() - box.lastScroll ) >= ( options.delay - 20 ) )
				{
					box.animate(
						{
							top: aniTop
						}, options.speed, options.easing
					);
				}
			}
		};
		
		// For user-initiated stopping of the slide
		var isActive = true;
		
		if ( $.cookie != undefined )
		{
			if( $.cookie( 'scrollFollowSetting' + box.attr( 'id' ) ) == 'false' )
			{
				var isActive = false;
				
				$( '#' + options.killSwitch ).text( options.offText )
					.toggle( 
						function ()
						{
							isActive = true;
							
							$( this ).text( options.onText );
							
							$.cookie( 'scrollFollowSetting' + box.attr( 'id' ), true, { expires: 365, path: '/'} );
							
							ani();
						},
						function ()
						{
							isActive = false;
							
							$( this ).text( options.offText );
							
							box.animate(
								{
									top: box.initialTop
								}, options.speed, options.easing
							);	
							
							$.cookie( 'scrollFollowSetting' + box.attr( 'id' ), false, { expires: 365, path: '/'} );
						}
					);
			}
			else
			{
				$( '#' + options.killSwitch ).text( options.onText )
					.toggle( 
						function ()
						{
							isActive = false;
							
							$( this ).text( options.offText );
							
							box.animate(
								{
									top: box.initialTop
								}, 0
							);	
							
							$.cookie( 'scrollFollowSetting' + box.attr( 'id' ), false, { expires: 365, path: '/'} );
						},
						function ()
						{
							isActive = true;
							
							$( this ).text( options.onText );
							
							$.cookie( 'scrollFollowSetting' + box.attr( 'id' ), true, { expires: 365, path: '/'} );
							
							ani();
						}
					);
			}
		}
		
		// If no parent ID was specified, and the immediate parent does not have an ID
		// options.container will be undefined. So we need to figure out the parent element.
		if ( options.container == '')
		{
			box.cont = box.parent();
		}
		else
		{
			box.cont = $( '#' + options.container );
		}
		
		// Finds the default positioning of the box.
		box.initialOffsetTop =  parseInt( box.offset().top );
		box.initialTop = parseInt( box.css( 'top' ) ) || 0;
		
		// Hack to fix different treatment of boxes positioned 'absolute' and 'relative'
		if ( box.css( 'position' ) == 'relative' )
		{
			box.paddingAdjustment = parseInt( box.cont.css( 'paddingTop' ) ) + parseInt( box.cont.css( 'paddingBottom' ) );
		}
		else
		{
			box.paddingAdjustment = 0;
		}
		
		// Animate the box when the page is scrolled
		$( window ).scroll( function ()
			{
				// Sets up the delay of the animation
				$.fn.scrollFollow.interval = setTimeout( function(){ ani();} , options.delay );
				
				// To check against right before setting the animation
				box.lastScroll = new Date().getTime();
			}
		);
		
		// Animate the box when the page is resized
		$( window ).resize( function ()
			{
				// Sets up the delay of the animation
				$.fn.scrollFollow.interval = setTimeout( function(){ ani();} , options.delay );
				
				// To check against right before setting the animation
				box.lastScroll = new Date().getTime();
			}
		);

		// Run an initial animation on page load
		box.lastScroll = 0;
		
		ani();
	};
	
	$.fn.scrollFollow = function ( options )
	{
		options = options || {};
		options.relativeTo = options.relativeTo || 'top';
		options.speed = options.speed || 500;
		options.offset = options.offset || 0;
		options.easing = options.easing || 'swing';
		options.container = options.container || this.parent().attr( 'id' );
		options.killSwitch = options.killSwitch || 'killSwitch';
		options.onText = options.onText || 'Turn Slide Off';
		options.offText = options.offText || 'Turn Slide On';
		options.delay = options.delay || 0;
		
		this.each( function() 
			{
				new $.scrollFollow( this, options );
			}
		);
		
		return this;
	};
})( jQuery );



/*
 * FancyBox - jQuery Plugin
 * Simple and fancy lightbox alternative
 *
 * Copyright (c) 20010 Janis Skarnelis
 * Examples and documentation at: http://fancybox.net
 *
 * Version: 1.3.0 (02/02/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(b){function H(){v.hide();r.onerror=r.onload=null;F&&F.abort();l.empty()}function Q(){b.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"})}function B(){H();var a=q[s];e=b.extend({},b.fn.fancybox.defaults,typeof b(a).data("fancybox")=="undefined"?e:b(a).data("fancybox"));var d,f,o=a.title||b(a).title||e.title||"";if(a.nodeName&&!e.orig)e.orig=b(a).children("img:first").length?
b(a).children("img:first"):b(a);if(o==""&&e.orig)o=e.orig.attr("alt");d=a.nodeName&&/^(?:javascript|#)/i.test(a.href)?e.href||null:e.href||a.href||null;if(e.type){f=e.type;if(!d)d=e.content}else if(e.content)f="html";else if(d)if(d.match(I))f="image";else if(d.match(T))f="swf";else if(b(a).hasClass("iframe"))f="iframe";else if(d.match(/#/)){a=d.substr(d.indexOf("#"));f=b(a).length>0?"inline":"ajax"}else f="ajax";else f="inline";e.type=f;e.href=d;e.title=o;if(e.autoDimensions&&e.type!=="iframe"&&e.type!==
"swf"){e.width="auto";e.height="auto"}if(e.modal){e.overlayShow=true;e.hideOnOverlayClick=false;e.hideOnContentClick=false;e.enableEscapeButton=false;e.showCloseButton=false}if(b.isFunction(e.onStart))if(e.onStart(q,s,e)===false){h=false;return}l.css("padding",t+e.padding+e.margin);b(".fancybox-inline-tmp").unbind("fancybox-cancel").bind("fancybox-change",function(){b(this).replaceWith(i.children())});switch(f){case "html":l.html(e.content);G();break;case "inline":b('<div class="fancybox-inline-tmp" />').hide().insertBefore(b(a)).bind("fancybox-cleanup",
function(){b(this).replaceWith(i.children())}).bind("fancybox-cancel",function(){b(this).replaceWith(l.children())});b(a).appendTo(l);G();break;case "image":h=false;b.fancybox.showActivity();r=new Image;r.onerror=function(){Q()};r.onload=function(){r.onerror=null;r.onload=null;U()};r.src=d;break;case "swf":var u="",w="";u+='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+e.width+'" height="'+e.height+'"><param name="movie" value="'+d+'"></param>';b.each(e.swf,function(p,R){u+=
'<param name="'+p+'" value="'+R+'"></param>';w+=" "+p+'="'+R+'"'});u+='<embed src="'+d+'" type="application/x-shockwave-flash" width="'+e.width+'" height="'+e.height+'"'+w+"></embed></object>";l.html(u);G();break;case "ajax":a=d.split("#",2);f=e.ajax.data||{};if(a.length>1){d=a[0];typeof f=="string"?(f+="&selector="+a[1]):(f.selector=a[1])}h=false;b.fancybox.showActivity();F=b.ajax(b.extend(e.ajax,{url:d,data:f,error:Q,success:function(p){if(F.status==200){l.html(p);G()}}}));break;case "iframe":b('<iframe id="fancybox-frame" name="fancybox-frame'+
(new Date).getTime()+'" frameborder="0" hspace="0" scrolling="'+e.scrolling+'" src="'+e.href+'"></iframe>').appendTo(l);J();break}}function U(){h=true;e.width=r.width;e.height=r.height;b("<img />").attr({id:"fancybox-img",src:r.src,alt:e.title}).appendTo(l);J()}function G(){l.width(e.width);l.height(e.height);if(e.width=="auto")e.width=l.width();if(e.height=="auto")e.height=l.height();J()}function J(){v.hide();if(g.is(":visible")&&b.isFunction(c.onCleanup))if(c.onCleanup(j,n,c)===false){b.event.trigger("fancybox-cancel");
h=false;return}j=q;n=s;c=e;i.get(0).scrollTop=0;i.get(0).scrollLeft=0;if(c.overlayShow){K&&b("select:not(#fancybox-tmp select)").filter(function(){return this.style.visibility!=="hidden"}).css({visibility:"hidden"}).one("fancybox-cleanup",function(){this.style.visibility="inherit"});y.css({"background-color":c.overlayColor,opacity:c.overlayOpacity}).unbind().show()}m=V();W();if(g.is(":visible")){b(z.add(C).add(D)).hide();var a=g.position();k={top:a.top,left:a.left,width:g.width(),height:g.height()};
var d=k.width==m.width&&k.height==m.height;i.fadeOut(c.changeFade,function(){function f(){i.html(l.contents()).fadeIn(c.changeFade,L)}b.event.trigger("fancybox-change");i.css({top:c.padding,left:c.padding,width:Math.max(k.width-c.padding*2,1),height:Math.max(k.height-c.padding*2,1)}).empty().css("overflow","hidden");A.prop=0;b(A).animate({prop:1},{duration:d?0:c.changeSpeed,easing:c.easingChange,step:M,complete:f})})}else{g.css("opacity",1);if(c.transitionIn=="elastic"){k=S();i.css({top:c.padding,
left:c.padding,width:Math.max(k.width-c.padding*2,1),height:Math.max(k.height-c.padding*2,1)}).html(l.contents());g.css(k).show();if(c.opacity)m.opacity=0;A.prop=0;b(A).animate({prop:1},{duration:c.speedIn,easing:c.easingIn,step:M,complete:L})}else{i.css({top:c.padding,left:c.padding,width:Math.max(m.width-c.padding*2,1),height:Math.max(m.height-c.padding*2-x,1)}).html(l.contents());g.css(m).fadeIn(c.transitionIn=="none"?0:c.speedIn,L)}}}function M(a){var d=Math.round(k.width+(m.width-k.width)*a),
f=Math.round(k.height+(m.height-k.height)*a),o=Math.round(k.top+(m.top-k.top)*a),u=Math.round(k.left+(m.left-k.left)*a);g.css({width:d+"px",height:f+"px",top:o+"px",left:u+"px"});d=Math.max(d-c.padding*2,0);f=Math.max(f-(c.padding*2+x*a),0);i.css({width:d+"px",height:f+"px"});if(typeof m.opacity!=="undefined")g.css("opacity",a<0.5?0.5:a)}function L(){i.css("overflow",overflow=c.scrolling=="auto"?c.type=="image"||c.type=="iframe"||c.type=="swf"?"hidden":"auto":c.scrolling=="yes"?"auto":"visible");
if(!b.support.opacity){i.get(0).style.removeAttribute("filter");g.get(0).style.removeAttribute("filter")}b("#fancybox-title").show();c.hideOnContentClick&&i.one("click",b.fancybox.close);c.hideOnOverlayClick&&y.one("click",b.fancybox.close);c.showCloseButton&&z.show();X();b(window).bind("resize.fb",b.fancybox.center);c.centerOnScroll?b(window).bind("scroll.fb",b.fancybox.center):b(window).unbind("scroll.fb");b.isFunction(c.onComplete)&&c.onComplete(j,n,c);h=false;Y()}function V(){var a=N(),d={},f=
c.margin,o=c.autoScale,u=(t+f)*2,w=(t+f)*2,p=c.padding*2;if(c.width.toString().indexOf("%")>-1){d.width=a[0]*parseFloat(c.width)/100-t*2;o=false}else d.width=c.width+p;if(c.height.toString().indexOf("%")>-1){d.height=a[1]*parseFloat(c.height)/100-t*2;o=false}else d.height=c.height+p;if(o&&(d.width>a[0]-u||d.height>a[1]-w))if(e.type=="image"||e.type=="swf"){u+=p;w+=p;o=Math.min(Math.min(a[0]-u,c.width)/c.width,Math.min(a[1]-w,c.height)/c.height);d.width=Math.round(o*(d.width-p))+p;d.height=Math.round(o*
(d.height-p))+p}else{d.width=Math.min(d.width,a[0]-u);d.height=Math.min(d.height,a[1]-w)}d.top=a[3]+(a[1]-(d.height+t*2))*0.5;d.left=a[2]+(a[0]-(d.width+t*2))*0.5;if(c.autoScale==false){d.top=Math.max(a[3]+f,d.top);d.left=Math.max(a[2]+f,d.left)}return d}function S(){var a=e.orig?b(e.orig):false,d={};if(a&&a.length){a=Z(a);d={width:a.width+c.padding*2,height:a.height+c.padding*2,top:a.top-c.padding-t,left:a.left-c.padding-t}}else{a=N();d={width:1,height:1,top:a[3]+a[1]*0.5,left:a[2]+a[0]*0.5}}return d}
function X(){b(document).unbind("keydown.fb").bind("keydown.fb",function(a){if(a.keyCode==27&&c.enableEscapeButton){a.preventDefault();b.fancybox.close()}/*else if(a.keyCode==37){a.preventDefault();b.fancybox.prev()}else if(a.keyCode==39){a.preventDefault();b.fancybox.next()}*/});if(b.fn.mousewheel){g.unbind("mousewheel.fb");j.length>1&&g.bind("mousewheel.fb",function(a,d){a.preventDefault();h||d==0||(d>0?b.fancybox.prev():b.fancybox.next())})}if(c.showNavArrows){if(c.cyclic&&j.length>1||n!=0)C.show();
if(c.cyclic&&j.length>1||n!=j.length-1)D.show()}}function Y(){if(j.length-1>n){var a=j[n+1].href;if(typeof a!=="undefined"&&a.match(I)){var d=new Image;d.src=a}}if(n>0){a=j[n-1].href;if(typeof a!=="undefined"&&a.match(I)){d=new Image;d.src=a}}}function $(){if(v.is(":visible")){b("div",v).css("top",O*-40+"px");O=(O+1)%12}else clearInterval(P)}function N(){return[b(window).width(),b(window).height(),b(document).scrollLeft(),b(document).scrollTop()]}function Z(a){var d=a.offset();d.top+=parseFloat(a.css("paddingTop"))||
0;d.left+=parseFloat(a.css("paddingLeft"))||0;d.top+=parseFloat(a.css("border-top-width"))||0;d.left+=parseFloat(a.css("border-left-width"))||0;d.width=a.width();d.height=a.height();return d}function W(){b("#fancybox-title").remove();x=0;if(c.titleShow!=false){var a=c.title;a=b.isFunction(c.titleFormat)?c.titleFormat(a,j,n,c):aa(a);if(!(!a||a=="")){var d=m.width-c.padding*2;b('<div id="fancybox-title" class="'+("fancybox-title-"+c.titlePosition)+'" />').css({width:d,paddingLeft:c.padding,paddingRight:c.padding}).html(a).appendTo("body");
switch(c.titlePosition){case "inside":x=b("#fancybox-title").outerHeight(true)-c.padding;m.height+=x;break;case "over":b("#fancybox-title").css("bottom",c.padding);break;default:b("#fancybox-title").css("bottom",b("#fancybox-title").outerHeight(true)*-1);break}b("#fancybox-title").appendTo(E).hide();K&&b("#fancybox-title span").fixPNG()}}}function aa(a){if(a&&a.length)switch(c.titlePosition){case "inside":return a;case "over":return'<span id="fancybox-title-over">'+a+"</span>";default:return'<span id="fancybox-title-wrap"><span id="fancybox-title-left"></span><span id="fancybox-title-main">'+
a+'</span><span id="fancybox-title-right"></span></span>'}return false}function ba(){if(!b("#fancybox-wrap").length){b("body").append(l=b('<div id="fancybox-tmp"></div>'),v=b('<div id="fancybox-loading"><div></div></div>'),y=b('<div id="fancybox-overlay"></div>'),g=b('<div id="fancybox-wrap"></div>'));E=b('<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(g);
E.append(i=b('<div id="fancybox-inner"></div>'),z=b('<a id="fancybox-close"></a>'),C=b('<a href="javascript:;" id="fancybox-left"><span class="fancy-ico" id="fancybox-left-ico"></span></a>'),D=b('<a href="javascript:;" id="fancybox-right"><span class="fancy-ico" id="fancybox-right-ico"></span></a>'));z.click(b.fancybox.close);v.click(b.fancybox.cancel);C.click(function(a){a.preventDefault();b.fancybox.prev()});D.click(function(a){a.preventDefault();b.fancybox.next()});b.support.opacity||E.find(".fancy-bg").fixPNG();
if(K){b(z.add(".fancy-ico").add("div",v)).fixPNG();y.get(0).style.setExpression("height","document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'");v.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'");E.prepend('<iframe id="fancybox-hide-sel-frame" src="javascript:\'\';" scrolling="no" frameborder="0" ></iframe>')}}}
var l,v,y,g,E,i,z,C,D,s=0,e={},q=[],n=0,c={},j=[],F=null,r=new Image,I=/\.(jpg|gif|png|bmp|jpeg)(.*)?$/i,T=/[^\.]\.(swf)\s*$/i,P,O=1,k,m,h=false,t=20,A=b.extend(b("<div/>")[0],{prop:0}),x=0,K=!b.support.opacity&&!window.XMLHttpRequest;b.fn.fixPNG=function(){return this.each(function(){var a=b(this).css("backgroundImage");if(a.match(/^url\(["']?(.*\.png)["']?\)$/i)){a=RegExp.$1;b(this).css({backgroundImage:"none",filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod="+
(b(this).css("backgroundRepeat")=="no-repeat"?"crop":"scale")+", src='"+a+"')"}).each(function(){var d=b(this).css("position");d!="absolute"&&d!="relative"&&b(this).css("position","relative")}).css("zoom",1)}})};b.fn.fancybox=function(a){b(this).data("fancybox",b.extend({},a));b(this).unbind("click.fb").bind("click.fb",function(d){d.preventDefault();if(!h){h=true;b(this).blur();q=[];s=0;d=b(this).attr("rel")||"";if(!d||d==""||d==="nofollow")q.push(this);else{q=b("a[rel="+d+"], area[rel="+d+"]");s=
q.index(this)}B();return false}});return this};b.fancybox=function(a,d){if(!h){h=true;q=[];s=0;if(b.isArray(a)){for(var f=0,o=a.length;f<o;f++)if(typeof a[f]=="object")b(a[f]).data("fancybox",b.extend({},d,a[f]));else a[f]=b({}).data("fancybox",b.extend({content:a[f]},d));q=jQuery.merge(q,a)}else{if(typeof a=="object")b(a).data("fancybox",b.extend({},d,a));else a=b({}).data("fancybox",b.extend({content:a},d));q.push(a)}B()}};b.fancybox.showActivity=function(){clearInterval(P);v.show();P=setInterval($,
66)};b.fancybox.hideActivity=function(){v.hide()};b.fancybox.next=function(){return b.fancybox.pos(n+1)};b.fancybox.prev=function(){return b.fancybox.pos(n-1)};b.fancybox.pos=function(a){if(!h){a=parseInt(a);if(a>-1&&j.length>a){s=a;B()}if(c.cyclic&&j.length>1&&a<0){s=j.length-1;B()}if(c.cyclic&&j.length>1&&a>=j.length){s=0;B()}}};b.fancybox.cancel=function(){if(!h){h=true;b.event.trigger("fancybox-cancel");H();e&&b.isFunction(e.onCancel)&&e.onCancel(q,s,e);h=false}};b.fancybox.close=function(){function a(){y.fadeOut("fast");
g.hide();b.event.trigger("fancybox-cleanup");i.empty();b.isFunction(c.onClosed)&&c.onClosed(j,n,c);j=e=[];n=s=0;c=e={};h=false}if(!(h||g.is(":hidden"))){h=true;if(c&&b.isFunction(c.onCleanup))if(c.onCleanup(j,n,c)===false){h=false;return}H();b(z.add(C).add(D)).hide();b("#fancybox-title").remove();g.add(i).add(y).unbind();b(window).unbind("resize.fb scroll.fb");b(document).unbind("keydown.fb");i.css("overflow","hidden");if(c.transitionOut=="elastic"){k=S();var d=g.position();m={top:d.top,left:d.left,
width:g.width(),height:g.height()};if(c.opacity)m.opacity=1;A.prop=1;b(A).animate({prop:0},{duration:c.speedOut,easing:c.easingOut,step:M,complete:a})}else g.fadeOut(c.transitionOut=="none"?0:c.speedOut,a)}};b.fancybox.resize=function(){if(!(h||g.is(":hidden"))){h=true;var a=i.wrapInner("<div style='overflow:auto'></div>").children(),d=a.height();g.css({height:d+c.padding*2+x});i.css({height:d});a.replaceWith(a.children());b.fancybox.center()}};b.fancybox.center=function(){h=true;var a=N(),d=c.margin,
f={};f.top=a[3]+(a[1]-(g.height()-x+t*2))*0.5;f.left=a[2]+(a[0]-(g.width()+t*2))*0.5;f.top=Math.max(a[3]+d,f.top);f.left=Math.max(a[2]+d,f.left);g.css(f);h=false};b.fn.fancybox.defaults={padding:10,margin:20,opacity:false,modal:false,cyclic:false,scrolling:"auto",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",
titleFormat:null,transitionIn:"fade",transitionOut:"fade",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};b(document).ready(function(){ba()})})(jQuery);
/**
*
* jquery.corners.js
*
* v1.0
* Contact: Christian Haack Arnaboldi (ragamo@gmail.com)
* http://ragamo.medioclick.com
*
* Create rounded corners using canvas element.
* 
* Tested in Internet Explorer 7 and Mozilla Firefox 3
*
* License: GPL
* 
* Copyright (c) 2008, Christian Haack Arnaboldi
* All rights reserved.
* 
* Redistribution and use in source and binary forms, with or without modification, 
* are permitted provided that the following conditions are met:
* 
*     * Redistributions of source code must retain the above copyright notice, 
*       this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice, 
*       this list of conditions and the following disclaimer in the documentation 
*       and/or other materials provided with the distribution.
*     * Neither the name of Splunk Inc nor the names of its contributors may 
*       be used to endorse or promote products derived from this software without 
*       specific prior written permission.
* 
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
* SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* 
*
* Usage: 
*  $(selector).corners([options])
*
* Supported options:
*   radio - (int) radius size of corners
*   inColor - (color) inside color of element
*   outColor - (color) outside color of corners   
*       
*   Examples:
*   $('#example_1').corners();
*	$('#example_2').corners({ inColor: '#8FC7FF' });
*	$('#example_3').corners({ inColor: '#FEFF8F', outColor: '#000' });
*	$('#example_4').corners({ radio: 30 });
*	$('#example_5').corners({ radio: 40, inColor: '#FFCC66', outColor: '#D2FBAE' });
*/

(function($) {		
	$.fn.drawCorners = function(id, radio, inColor, outColor, bSize, bColor) {
		if($.browser.msie) {
			var bC = bColor;
			var iC = inColor;
		} else {
			var bC = inColor;
			var iC = bColor;
		}
		
		var UpLeftCanvas = excanvas(document.getElementById(id +'_UpLeftCorner'));
      	if (UpLeftCanvas.getContext) {
        	var ctx = UpLeftCanvas.getContext("2d");
			
			ctx.fillStyle = outColor;
      		ctx.fillRect(0,0,radio,radio);

			ctx.fillStyle = bC;
			ctx.arc(radio, radio, radio, (Math.PI/2), 0, 0);
			ctx.fill();
			
			ctx.fillStyle = iC;
			ctx.arc(radio, radio, (radio-bSize), 0, (Math.PI/2), 1);
			ctx.fill();	
			
      	}
		
		var UpRightCanvas = excanvas(document.getElementById(id +'_UpRightCorner'));
      	if (UpRightCanvas.getContext) {
        	var ctx = UpRightCanvas.getContext("2d");
			
			ctx.fillStyle = outColor;
      		ctx.fillRect(0,0,radio,radio);
			
			ctx.fillStyle = bC;
			ctx.arc(0, radio, radio, (Math.PI), (Math.PI/2), 0);
			ctx.fill();
			
			ctx.fillStyle = iC;
			ctx.arc(0, radio, (radio-bSize), (Math.PI/2), (Math.PI), 1);
			ctx.fill();
      	}
		
		var DownLeftCanvas = excanvas(document.getElementById(id +'_DownLeftCorner'));
      	if (DownLeftCanvas.getContext) {
        	var ctx = DownLeftCanvas.getContext("2d");
			
			ctx.fillStyle = outColor;
      		ctx.fillRect(0,0,radio,radio);
			
			ctx.fillStyle = bC;
			ctx.arc(radio, 0, radio, 0, (3*Math.PI/2), 0);
			ctx.fill();
			
			ctx.fillStyle = iC;
			ctx.arc(radio, 0, (radio-bSize), (3*Math.PI/2), 0, 1);
			ctx.fill();
      	}
		
		var DownRightCanvas = excanvas(document.getElementById(id +'_DownRightCorner'));
      	if (DownRightCanvas.getContext) {
        	var ctx = DownRightCanvas.getContext("2d");
			
			ctx.fillStyle = outColor;
      		ctx.fillRect(0,0,radio,radio);
			
			ctx.fillStyle = bC;
			ctx.arc(0, 0, radio, (3*Math.PI/2), (Math.PI), 0);
			ctx.fill();
			
			ctx.fillStyle = iC;
			ctx.arc(0, 0, (radio-bSize), (Math.PI), (3*Math.PI/2), 1);
			ctx.fill();
      	}
	};
	
	$.fn.corners = function(options) {
		
		var options = $.extend({
			radio: 10,
			outColor: '#FFF',
			inColor: '#CDCDCD',
			borderSize: 0,
			borderColor: '#000000'
		}, options ? options : {});	
		
		return this.each(function() { 			
			if(options.borderSize > options.radio) {
				options.radio = options.borderSize;
			}
								  
			if($(this).css('backgroundColor')!='transparent') {
				options.inColor = $(this).css('backgroundColor');
			}
			
			if(options.borderSize == 0) {
				options.borderColor = $(this).css('border-left-color') || $(this).css('border-top-color') || $(this).css('border-bottom-color') || $(this).css('border-right-color');
				if(($(this).css('borderWidth')!='medium') || ($(this).css('borderWidth')!='')) {
					options.borderSize = ($(this).outerWidth()-$(this).innerWidth())/2 || ($(this).outerHeight()-$(this).innerHeight())/2;
				}
			}
								  
			var id = $(this).attr('id');
			var cont = $(this).html();
			
			$(this).css({ 
				position: 'relative', 
				backgroundColor: options.inColor,
				borderStyle: 'solid',
				borderWidth: options.borderSize+'px', 
				borderColor: options.borderColor
			}).html('');
			
			$(this).append('<canvas id=\''+ id +'_UpLeftCorner\' width='+ options.radio +' height='+ options.radio +'></canvas>');
			$(this).append('<canvas id=\''+ id +'_UpRightCorner\' width='+ options.radio +' height='+ options.radio +'></canvas>');
			$(this).append('<canvas id=\''+ id +'_DownLeftCorner\' width='+ options.radio +' height='+ options.radio +'></canvas>');
			$(this).append('<canvas id=\''+ id +'_DownRightCorner\' width='+ options.radio +' height='+ options.radio +'></canvas>');
			$(this).append('<div id=\''+ id +'_main\'>'+ cont +'</div>');
			//$(this).append('<span id=\''+ id +'_main\'>'+ cont +'</span>');
			
			$('#'+ id +'_main').css({ 
				position: 'relative', 
				zIndex: 1
			});
			
			$('#'+ id +'_UpLeftCorner, #'+ id +'_UpRightCorner, #'+ id +'_DownLeftCorner, #'+ id +'_DownRightCorner').css({ 
				position: 'absolute', 
				zIndex: 0,
				width: options.radio+'px', 
				height: options.radio+'px',
				backgroundColor: options.inColor 
			});
			
			if(options.borderSize != 0) {
				var B = -(options.borderSize);
				$('#'+ id +'_UpLeftCorner').css({ top: B+'px', left: B+'px' });
				$('#'+ id +'_UpRightCorner').css({ top: B+'px', right: B+'px' });
				$('#'+ id +'_DownLeftCorner').css({ bottom: B+'px', left: B+'px' });
				$('#'+ id +'_DownRightCorner').css({ bottom: B+'px', right: B+'px' });

			} else {
				$('#'+ id +'_UpLeftCorner').css({ top: '0px', left: '0px' });
				$('#'+ id +'_UpRightCorner').css({ top: '0px', right: '0px' });
				$('#'+ id +'_DownLeftCorner').css({ bottom: '0px', left: '0px' });
				$('#'+ id +'_DownRightCorner').css({ bottom: '0px', right: '0px' });
				
				options.borderColor = options.inColor;
			}
			
			$(this).drawCorners(id, options.radio, options.inColor, options.outColor, options.borderSize, options.borderColor);
		});
	};
})(jQuery)
// Copyright 2006 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.


// Known Issues:
//
// * Patterns are not implemented.
// * Radial gradient are not implemented. The VML version of these look very
//   different from the canvas one.
// * Clipping paths are not implemented.
// * Coordsize. The width and height attribute have higher priority than the
//   width and height style values which isn't correct.
// * Painting mode isn't implemented.
// * Canvas width/height should is using content-box by default. IE in
//   Quirks mode will draw the canvas using border-box. Either change your
//   doctype to HTML5
//   (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype)
//   or use Box Sizing Behavior from WebFX
//   (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html)
// * Optimize. There is always room for speed improvements.

// only add this code if we do not already have a canvas implementation
var excanvas = function(canvas){if (arguments.length == 1) return canvas;}
if (!window.CanvasRenderingContext2D) {

excanvas = function (canvasObject) {

  // alias some functions to make (compiled) code shorter
  var m = Math;
  var mr = m.round;
  var ms = m.sin;
  var mc = m.cos;

  // this is used for sub pixel precision
  var Z = 10;
  var Z2 = Z / 2;

  var G_vmlCanvasManager_ = {
    init: function (opt_doc, canvasObject) {
      var doc = opt_doc || document;
      if (/MSIE/.test(navigator.userAgent) && !window.opera) {
        var self = this;
        if (typeof canvasObject != "undefined")
        {
           return self.init_(doc, canvasObject);
        }
        else
        {
            doc.attachEvent("onreadystatechange", function () {self.init_(doc);});
        }
      }
    },

    init_: function (doc, canvasObject) 
    {        
      if (typeof canvasObject != "undefined")
      {      
          if (!canvasObject.getContext) {          
           return this.initElement(canvasObject);
          }      
        return;
      }
      if (doc.readyState == "complete")
      {
        // create xmlns
        if (!doc.namespaces["g_vml_"]) {
          doc.namespaces.add("g_vml_", "urn:schemas-microsoft-com:vml");
        }

        // setup default css
        var ss = doc.createStyleSheet();
        ss.cssText = "canvas{display:inline-block;/*overflow:hidden;*/" +
            // default size is 300x150 in Gecko and Opera
            "text-align:left;width:300px;height:150px}" +
            "g_vml_\\:*{behavior:url(#default#VML)}";

        // find all canvas elements
        var els = doc.getElementsByTagName("canvas");
        for (var i = 0; i < els.length; i++) {
          if (!els[i].getContext) {
            this.initElement(els[i]);
          }
        }
      }
    },

    fixElement_: function (el) {
      // in IE before version 5.5 we would need to add HTML: to the tag name
      // but we do not care about IE before version 6
      var outerHTML = el.outerHTML;

      var newEl = el.ownerDocument.createElement(outerHTML);
      // if the tag is still open IE has created the children as siblings and
      // it has also created a tag with the name "/FOO"
      if (outerHTML.slice(-2) != "/>") {
        var tagName = "/" + el.tagName;
        var ns;
        // remove content
        while ((ns = el.nextSibling) && ns.tagName != tagName) {
          ns.removeNode();
        }
        // remove the incorrect closing tag
        if (ns) {
          ns.removeNode();
        }
      }
      if (el.parentNode == null)
      {
        return el;
      }
      
      el.parentNode.replaceChild(newEl, el);
      return newEl;
    },

    /**
     * Public initializes a canvas element so that it can be used as canvas
     * element from now on. This is called automatically before the page is
     * loaded but if you are creating elements using createElement you need to
     * make sure this is called on the element.
     * @param {HTMLElement} el The canvas element to initialize.
     * @return {HTMLElement} the element that was created.
     */
    initElement: function (el) {
      el = this.fixElement_(el);
      el.getContext = function () {
        if (this.context_) {
          return this.context_;
        }
        return this.context_ = new CanvasRenderingContext2D_(this);
      };

      // do not use inline function because that will leak memory
      el.attachEvent('onpropertychange', onPropertyChange);
      el.attachEvent('onresize', onResize);

      var attrs = el.attributes;
      if (attrs.width && attrs.width.specified) {
        // TODO: use runtimeStyle and coordsize
        // el.getContext().setWidth_(attrs.width.nodeValue);
        el.style.width = attrs.width.nodeValue + "px";
      } else {
        el.width = el.clientWidth;
      }
      if (attrs.height && attrs.height.specified) {
        // TODO: use runtimeStyle and coordsize
        // el.getContext().setHeight_(attrs.height.nodeValue);
        el.style.height = attrs.height.nodeValue + "px";
      } else {
        el.height = el.clientHeight;
      }
      //el.getContext().setCoordsize_()
      return el;
    }
  };

  function onPropertyChange(e) {
    var el = e.srcElement;

    switch (e.propertyName) {
      case 'width':
        el.style.width = el.attributes.width.nodeValue + "px";
        el.getContext().clearRect();
        break;
      case 'height':
        el.style.height = el.attributes.height.nodeValue + "px";
        el.getContext().clearRect();
        break;
    }
  }

  function onResize(e) {
    var el = e.srcElement;
    if (el.firstChild) {
      el.firstChild.style.width =  el.clientWidth + 'px';
      el.firstChild.style.height = el.clientHeight + 'px';
    }
  }

  var newCanvas = G_vmlCanvasManager_.init(null, canvasObject);

  // precompute "00" to "FF"
  var dec2hex = [];
  for (var i = 0; i < 16; i++) {
    for (var j = 0; j < 16; j++) {
      dec2hex[i * 16 + j] = i.toString(16) + j.toString(16);
    }
  }

  function createMatrixIdentity() {
    return [
      [1, 0, 0],
      [0, 1, 0],
      [0, 0, 1]
    ];
  }

  function matrixMultiply(m1, m2) {
    var result = createMatrixIdentity();

    for (var x = 0; x < 3; x++) {
      for (var y = 0; y < 3; y++) {
        var sum = 0;

        for (var z = 0; z < 3; z++) {
          sum += m1[x][z] * m2[z][y];
        }

        result[x][y] = sum;
      }
    }
    return result;
  }

  function copyState(o1, o2) {
    o2.fillStyle     = o1.fillStyle;
    o2.lineCap       = o1.lineCap;
    o2.lineJoin      = o1.lineJoin;
    o2.lineWidth     = o1.lineWidth;
    o2.miterLimit    = o1.miterLimit;
    o2.shadowBlur    = o1.shadowBlur;
    o2.shadowColor   = o1.shadowColor;
    o2.shadowOffsetX = o1.shadowOffsetX;
    o2.shadowOffsetY = o1.shadowOffsetY;
    o2.strokeStyle   = o1.strokeStyle;
    o2.arcScaleX_    = o1.arcScaleX_;
    o2.arcScaleY_    = o1.arcScaleY_;
  }

  function processStyle(styleString) {
    var str, alpha = 1;

    styleString = String(styleString);
    if (styleString.substring(0, 3) == "rgb") {
      var start = styleString.indexOf("(", 3);
      var end = styleString.indexOf(")", start + 1);
      var guts = styleString.substring(start + 1, end).split(",");

      str = "#";
      for (var i = 0; i < 3; i++) {
        str += dec2hex[Number(guts[i])];
      }

      if ((guts.length == 4) && (styleString.substr(3, 1) == "a")) {
        alpha = guts[3];
      }
    } else {
      str = styleString;
    }

    return [str, alpha];
  }

  function processLineCap(lineCap) {
    switch (lineCap) {
      case "butt":
        return "flat";
      case "round":
        return "round";
      case "square":
      default:
        return "square";
    }
  }

  /**
   * This class implements CanvasRenderingContext2D interface as described by
   * the WHATWG.
   * @param {HTMLElement} surfaceElement The element that the 2D context should
   * be associated with
   */
   function CanvasRenderingContext2D_(surfaceElement) {
    this.m_ = createMatrixIdentity();

    this.mStack_ = [];
    this.aStack_ = [];
    this.currentPath_ = [];

    // Canvas context properties
    this.strokeStyle = "#000";
    this.fillStyle = "#000";

    this.lineWidth = 1;
    this.lineJoin = "miter";
    this.lineCap = "butt";
    this.miterLimit = Z * 1;
    this.globalAlpha = 1;
    this.canvas = surfaceElement;

    var el = surfaceElement.ownerDocument.createElement('div');
    el.style.width =  surfaceElement.clientWidth + 'px';
    el.style.height = surfaceElement.clientHeight + 'px';
    el.style.overflow = 'hidden';
    el.style.position = 'absolute';
    surfaceElement.appendChild(el);

    this.element_ = el;
    this.arcScaleX_ = 1;
    this.arcScaleY_ = 1;
  };

  var contextPrototype = CanvasRenderingContext2D_.prototype;
  contextPrototype.clearRect = function() {
    this.element_.innerHTML = "";
    this.currentPath_ = [];
  };

  contextPrototype.beginPath = function() {
    // TODO: Branch current matrix so that save/restore has no effect
    //       as per safari docs.

    this.currentPath_ = [];
  };

  contextPrototype.moveTo = function(aX, aY) {
    this.currentPath_.push({type: "moveTo", x: aX, y: aY});
    this.currentX_ = aX;
    this.currentY_ = aY;
  };

  contextPrototype.lineTo = function(aX, aY) {
    this.currentPath_.push({type: "lineTo", x: aX, y: aY});
    this.currentX_ = aX;
    this.currentY_ = aY;
  };

  contextPrototype.bezierCurveTo = function(aCP1x, aCP1y,
                                            aCP2x, aCP2y,
                                            aX, aY) {
    this.currentPath_.push({type: "bezierCurveTo",
                           cp1x: aCP1x,
                           cp1y: aCP1y,
                           cp2x: aCP2x,
                           cp2y: aCP2y,
                           x: aX,
                           y: aY});
    this.currentX_ = aX;
    this.currentY_ = aY;
  };

  contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) {
    // the following is lifted almost directly from
    // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes
    var cp1x = this.currentX_ + 2.0 / 3.0 * (aCPx - this.currentX_);
    var cp1y = this.currentY_ + 2.0 / 3.0 * (aCPy - this.currentY_);
    var cp2x = cp1x + (aX - this.currentX_) / 3.0;
    var cp2y = cp1y + (aY - this.currentY_) / 3.0;
    this.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, aX, aY);
  };

  contextPrototype.arc = function(aX, aY, aRadius,
                                  aStartAngle, aEndAngle, aClockwise) {
    aRadius *= Z;
    var arcType = aClockwise ? "at" : "wa";

    var xStart = aX + (mc(aStartAngle) * aRadius) - Z2;
    var yStart = aY + (ms(aStartAngle) * aRadius) - Z2;

    var xEnd = aX + (mc(aEndAngle) * aRadius) - Z2;
    var yEnd = aY + (ms(aEndAngle) * aRadius) - Z2;

    // IE won't render arches drawn counter clockwise if xStart == xEnd.
    if (xStart == xEnd && !aClockwise) {
      xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something
                       // that can be represented in binary
    }

    this.currentPath_.push({type: arcType,
                           x: aX,
                           y: aY,
                           radius: aRadius,
                           xStart: xStart,
                           yStart: yStart,
                           xEnd: xEnd,
                           yEnd: yEnd});

  };

  contextPrototype.rect = function(aX, aY, aWidth, aHeight) {
    this.moveTo(aX, aY);
    this.lineTo(aX + aWidth, aY);
    this.lineTo(aX + aWidth, aY + aHeight);
    this.lineTo(aX, aY + aHeight);
    this.closePath();
  };

  contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) {
    // Will destroy any existing path (same as FF behaviour)
    this.beginPath();
    this.moveTo(aX, aY);
    this.lineTo(aX + aWidth, aY);
    this.lineTo(aX + aWidth, aY + aHeight);
    this.lineTo(aX, aY + aHeight);
    this.closePath();
    this.stroke();
  };

  contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) {
    // Will destroy any existing path (same as FF behaviour)
    this.beginPath();
    this.moveTo(aX, aY);
    this.lineTo(aX + aWidth, aY);
    this.lineTo(aX + aWidth, aY + aHeight);
    this.lineTo(aX, aY + aHeight);
    this.closePath();
    this.fill();
  };

  contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) {
    var gradient = new CanvasGradient_("gradient");
    return gradient;
  };

  contextPrototype.createRadialGradient = function(aX0, aY0,
                                                   aR0, aX1,
                                                   aY1, aR1) {
    var gradient = new CanvasGradient_("gradientradial");
    gradient.radius1_ = aR0;
    gradient.radius2_ = aR1;
    gradient.focus_.x = aX0;
    gradient.focus_.y = aY0;
    return gradient;
  };

  contextPrototype.drawImage = function (image, var_args) {
    var dx, dy, dw, dh, sx, sy, sw, sh;

    // to find the original width we overide the width and height
    var oldRuntimeWidth = image.runtimeStyle.width;
    var oldRuntimeHeight = image.runtimeStyle.height;
    image.runtimeStyle.width = 'auto';
    image.runtimeStyle.height = 'auto';

    // get the original size
    var w = image.width;
    var h = image.height;

    // and remove overides
    image.runtimeStyle.width = oldRuntimeWidth;
    image.runtimeStyle.height = oldRuntimeHeight;

    if (arguments.length == 3) {
      dx = arguments[1];
      dy = arguments[2];
      sx = sy = 0;
      sw = dw = w;
      sh = dh = h;
    } else if (arguments.length == 5) {
      dx = arguments[1];
      dy = arguments[2];
      dw = arguments[3];
      dh = arguments[4];
      sx = sy = 0;
      sw = w;
      sh = h;
    } else if (arguments.length == 9) {
      sx = arguments[1];
      sy = arguments[2];
      sw = arguments[3];
      sh = arguments[4];
      dx = arguments[5];
      dy = arguments[6];
      dw = arguments[7];
      dh = arguments[8];
    } else {
      throw "Invalid number of arguments";
    }

    var d = this.getCoords_(dx, dy);

    var w2 = sw / 2;
    var h2 = sh / 2;

    var vmlStr = [];

    var W = 10;
    var H = 10;

    // For some reason that I've now forgotten, using divs didn't work
    vmlStr.push(' <g_vml_:group',
                ' coordsize="', Z * W, ',', Z * H, '"',
                ' coordorigin="0,0"' ,
                ' style="width:', W, ';height:', H, ';position:absolute;');

    // If filters are necessary (rotation exists), create them
    // filters are bog-slow, so only create them if abbsolutely necessary
    // The following check doesn't account for skews (which don't exist
    // in the canvas spec (yet) anyway.

    if (this.m_[0][0] != 1 || this.m_[0][1]) {
      var filter = [];

      // Note the 12/21 reversal
      filter.push("M11='", this.m_[0][0], "',",
                  "M12='", this.m_[1][0], "',",
                  "M21='", this.m_[0][1], "',",
                  "M22='", this.m_[1][1], "',",
                  "Dx='", mr(d.x / Z), "',",
                  "Dy='", mr(d.y / Z), "'");

      // Bounding box calculation (need to minimize displayed area so that
      // filters don't waste time on unused pixels.
      var max = d;
      var c2 = this.getCoords_(dx + dw, dy);
      var c3 = this.getCoords_(dx, dy + dh);
      var c4 = this.getCoords_(dx + dw, dy + dh);

      max.x = Math.max(max.x, c2.x, c3.x, c4.x);
      max.y = Math.max(max.y, c2.y, c3.y, c4.y);

      vmlStr.push("padding:0 ", mr(max.x / Z), "px ", mr(max.y / Z),
                  "px 0;filter:progid:DXImageTransform.Microsoft.Matrix(",
                  filter.join(""), ", sizingmethod='clip');")
    } else {
      vmlStr.push("top:", mr(d.y / Z), "px;left:", mr(d.x / Z), "px;")
    }

    vmlStr.push(' ">' ,
                '<g_vml_:image src="', image.src, '"',
                ' style="width:', Z * dw, ';',
                ' height:', Z * dh, ';"',
                ' cropleft="', sx / w, '"',
                ' croptop="', sy / h, '"',
                ' cropright="', (w - sx - sw) / w, '"',
                ' cropbottom="', (h - sy - sh) / h, '"',
                ' />',
                '</g_vml_:group>');

    this.element_.insertAdjacentHTML("BeforeEnd",
                                    vmlStr.join(""));
  };

  contextPrototype.stroke = function(aFill) {
    var lineStr = [];
    var lineOpen = false;
    var a = processStyle(aFill ? this.fillStyle : this.strokeStyle);
    var color = a[0];
    var opacity = a[1] * this.globalAlpha;

    var W = 10;
    var H = 10;

    lineStr.push('<g_vml_:shape',
                 ' fillcolor="', color, '"',
                 ' filled="', Boolean(aFill), '"',
                 ' style="position:absolute;width:', W, ';height:', H, ';"',
                 ' coordorigin="0 0" coordsize="', Z * W, ' ', Z * H, '"',
                 ' stroked="', !aFill, '"',
                 ' strokeweight="', this.lineWidth, '"',
                 ' strokecolor="', color, '"',
                 ' path="');

    var newSeq = false;
    var min = {x: null, y: null};
    var max = {x: null, y: null};

    for (var i = 0; i < this.currentPath_.length; i++) {
      var p = this.currentPath_[i];

      if (p.type == "moveTo") {
        lineStr.push(" m ");
        var c = this.getCoords_(p.x, p.y);
        lineStr.push(mr(c.x), ",", mr(c.y));
      } else if (p.type == "lineTo") {
        lineStr.push(" l ");
        var c = this.getCoords_(p.x, p.y);
        lineStr.push(mr(c.x), ",", mr(c.y));
      } else if (p.type == "close") {
        lineStr.push(" x ");
      } else if (p.type == "bezierCurveTo") {
        lineStr.push(" c ");
        var c = this.getCoords_(p.x, p.y);
        var c1 = this.getCoords_(p.cp1x, p.cp1y);
        var c2 = this.getCoords_(p.cp2x, p.cp2y);
        lineStr.push(mr(c1.x), ",", mr(c1.y), ",",
                     mr(c2.x), ",", mr(c2.y), ",",
                     mr(c.x), ",", mr(c.y));
      } else if (p.type == "at" || p.type == "wa") {
        lineStr.push(" ", p.type, " ");
        var c  = this.getCoords_(p.x, p.y);
        var cStart = this.getCoords_(p.xStart, p.yStart);
        var cEnd = this.getCoords_(p.xEnd, p.yEnd);

        lineStr.push(mr(c.x - this.arcScaleX_ * p.radius), ",",
                     mr(c.y - this.arcScaleY_ * p.radius), " ",
                     mr(c.x + this.arcScaleX_ * p.radius), ",",
                     mr(c.y + this.arcScaleY_ * p.radius), " ",
                     mr(cStart.x), ",", mr(cStart.y), " ",
                     mr(cEnd.x), ",", mr(cEnd.y));
      }


      // TODO: Following is broken for curves due to
      //       move to proper paths.

      // Figure out dimensions so we can do gradient fills
      // properly
      if(c) {
        if (min.x == null || c.x < min.x) {
          min.x = c.x;
        }
        if (max.x == null || c.x > max.x) {
          max.x = c.x;
        }
        if (min.y == null || c.y < min.y) {
          min.y = c.y;
        }
        if (max.y == null || c.y > max.y) {
          max.y = c.y;
        }
      }
    }
    lineStr.push(' ">');

    if (typeof this.fillStyle == "object") {
      var focus = {x: "50%", y: "50%"};
      var width = (max.x - min.x);
      var height = (max.y - min.y);
      var dimension = (width > height) ? width : height;

      focus.x = mr((this.fillStyle.focus_.x / width) * 100 + 50) + "%";
      focus.y = mr((this.fillStyle.focus_.y / height) * 100 + 50) + "%";

      var colors = [];

      // inside radius (%)
      if (this.fillStyle.type_ == "gradientradial") {
        var inside = (this.fillStyle.radius1_ / dimension * 100);

        // percentage that outside radius exceeds inside radius
        var expansion = (this.fillStyle.radius2_ / dimension * 100) - inside;
      } else {
        var inside = 0;
        var expansion = 100;
      }

      var insidecolor = {offset: null, color: null};
      var outsidecolor = {offset: null, color: null};

      // We need to sort 'colors' by percentage, from 0 > 100 otherwise ie
      // won't interpret it correctly
      this.fillStyle.colors_.sort(function (cs1, cs2) {
        return cs1.offset - cs2.offset;
      });

      for (var i = 0; i < this.fillStyle.colors_.length; i++) {
        var fs = this.fillStyle.colors_[i];

        colors.push( (fs.offset * expansion) + inside, "% ", fs.color, ",");

        if (fs.offset > insidecolor.offset || insidecolor.offset == null) {
          insidecolor.offset = fs.offset;
          insidecolor.color = fs.color;
        }

        if (fs.offset < outsidecolor.offset || outsidecolor.offset == null) {
          outsidecolor.offset = fs.offset;
          outsidecolor.color = fs.color;
        }
      }
      colors.pop();

      lineStr.push('<g_vml_:fill',
                   ' color="', outsidecolor.color, '"',
                   ' color2="', insidecolor.color, '"',
                   ' type="', this.fillStyle.type_, '"',
                   ' focusposition="', focus.x, ', ', focus.y, '"',
                   ' colors="', colors.join(""), '"',
                   ' opacity="', opacity, '" />');
    } else if (aFill) {
      lineStr.push('<g_vml_:fill color="', color, '" opacity="', opacity, '" />');
    } else {
      lineStr.push(
        '<g_vml_:stroke',
        ' opacity="', opacity,'"',
        ' joinstyle="', this.lineJoin, '"',
        ' miterlimit="', this.miterLimit, '"',
        ' endcap="', processLineCap(this.lineCap) ,'"',
        ' weight="', this.lineWidth, 'px"',
        ' color="', color,'" />'
      );
    }

    lineStr.push("</g_vml_:shape>");

    this.element_.insertAdjacentHTML("beforeEnd", lineStr.join(""));

    this.currentPath_ = [];
  };

  contextPrototype.fill = function() {
    this.stroke(true);
  }

  contextPrototype.closePath = function() {
    this.currentPath_.push({type: "close"});
  };

  /**
   * @private
   */
  contextPrototype.getCoords_ = function(aX, aY) {
    return {
      x: Z * (aX * this.m_[0][0] + aY * this.m_[1][0] + this.m_[2][0]) - Z2,
      y: Z * (aX * this.m_[0][1] + aY * this.m_[1][1] + this.m_[2][1]) - Z2
    }
  };

  contextPrototype.save = function() {
    var o = {};
    copyState(this, o);
    this.aStack_.push(o);
    this.mStack_.push(this.m_);
    this.m_ = matrixMultiply(createMatrixIdentity(), this.m_);
  };

  contextPrototype.restore = function() {
    copyState(this.aStack_.pop(), this);
    this.m_ = this.mStack_.pop();
  };

  contextPrototype.translate = function(aX, aY) {
    var m1 = [
      [1,  0,  0],
      [0,  1,  0],
      [aX, aY, 1]
    ];

    this.m_ = matrixMultiply(m1, this.m_);
  };

  contextPrototype.rotate = function(aRot) {
    var c = mc(aRot);
    var s = ms(aRot);

    var m1 = [
      [c,  s, 0],
      [-s, c, 0],
      [0,  0, 1]
    ];

    this.m_ = matrixMultiply(m1, this.m_);
  };

  contextPrototype.scale = function(aX, aY) {
    this.arcScaleX_ *= aX;
    this.arcScaleY_ *= aY;
    var m1 = [
      [aX, 0,  0],
      [0,  aY, 0],
      [0,  0,  1]
    ];

    this.m_ = matrixMultiply(m1, this.m_);
  };

  /******** STUBS ********/
  contextPrototype.clip = function() {
    // TODO: Implement
  };

  contextPrototype.arcTo = function() {
    // TODO: Implement
  };

  contextPrototype.createPattern = function() {
    return new CanvasPattern_;
  };

  // Gradient / Pattern Stubs
  function CanvasGradient_(aType) {
    this.type_ = aType;
    this.radius1_ = 0;
    this.radius2_ = 0;
    this.colors_ = [];
    this.focus_ = {x: 0, y: 0};
  }

  CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) {
    aColor = processStyle(aColor);
    this.colors_.push({offset: 1-aOffset, color: aColor});
  };

  function CanvasPattern_() {}

  // set up externs
  G_vmlCanvasManager = G_vmlCanvasManager_;
  CanvasRenderingContext2D = CanvasRenderingContext2D_;
  CanvasGradient = CanvasGradient_;
  CanvasPattern = CanvasPattern_;

    return newCanvas;
}
    
} // if

excanvas();
/*
jQuery.ThreeDots.min

Author Jeremy Horn
Version 1.0.10
Date: 1/25/2009
More: http://tpgblog.com/ThreeDots/
compiled by http://yui.2clics.net/
*/

(function(e){e.fn.ThreeDots=function(h){var g=this;if((typeof h=="object")||(h==undefined)){e.fn.ThreeDots.the_selected=this;var g=e.fn.ThreeDots.update(h)}return g};e.fn.ThreeDots.update=function(u){var k,t=null;var m,j,s,q,o;var l,i;var r,h,n;if((typeof u=="object")||(u==undefined)){e.fn.ThreeDots.c_settings=e.extend({},e.fn.ThreeDots.settings,u);var p=e.fn.ThreeDots.c_settings.max_rows;if(p<1){return e.fn.ThreeDots.the_selected}var g=false;jQuery.each(e.fn.ThreeDots.c_settings.valid_delimiters,function(v,w){if(((new String(w)).length==1)){g=true}});if(g==false){return e.fn.ThreeDots.the_selected}e.fn.ThreeDots.the_selected.each(function(){k=e(this);if(e(k).children("."+e.fn.ThreeDots.c_settings.text_span_class).length==0){return true}l=e(k).children("."+e.fn.ThreeDots.c_settings.text_span_class).get(0);var y=a(k,true);var x=e(l).text();d(k,l,y);var v=e(l).text();if((h=e(k).attr("threedots"))!=undefined){e(l).text(h);e(k).children("."+e.fn.ThreeDots.c_settings.e_span_class).remove()}r=e(l).text();if(r.length<=0){r=""}e(k).attr("threedots",x);if(a(k,y)>p){curr_ellipsis=e(k).append('<span style="white-space:nowrap" class="'+e.fn.ThreeDots.c_settings.e_span_class+'">'+e.fn.ThreeDots.c_settings.ellipsis_string+"</span>");while(a(k,y)>p){i=b(e(l).text());e(l).text(i.updated_string);t=i.word;n=i.del;if(n==null){break}}if(t!=null){var w=c(k,y);if((a(k,y)<=p-1)||(w)||(!e.fn.ThreeDots.c_settings.whole_word)){r=e(l).text();if(i.del!=null){e(l).text(r+n)}if(a(k,y)>p){e(l).text(r)}else{e(l).text(e(l).text()+t);if((a(k,y)>p+1)||(!e.fn.ThreeDots.c_settings.whole_word)||(v==t)||w){while((a(k,y)>p)){if(e(l).text().length>0){e(l).text(e(l).text().substr(0,e(l).text().length-1))}else{break}}}}}}}if(x==e(e(k).children("."+e.fn.ThreeDots.c_settings.text_span_class).get(0)).text()){e(k).children("."+e.fn.ThreeDots.c_settings.e_span_class).remove()}else{if((e(k).children("."+e.fn.ThreeDots.c_settings.e_span_class)).length>0){if(e.fn.ThreeDots.c_settings.alt_text_t){e(k).children("."+e.fn.ThreeDots.c_settings.text_span_class).attr("title",x)}if(e.fn.ThreeDots.c_settings.alt_text_e){e(k).children("."+e.fn.ThreeDots.c_settings.e_span_class).attr("title",x)}}}})}return e.fn.ThreeDots.the_selected};e.fn.ThreeDots.settings={valid_delimiters:[" ",",","."],ellipsis_string:"...",max_rows:2,text_span_class:"ellipsis_text",e_span_class:"threedots_ellipsis",whole_word:true,allow_dangle:false,alt_text_e:false,alt_text_t:false};function c(k,h){if(e.fn.ThreeDots.c_settings.allow_dangle==true){return false}var l=e(k).children("."+e.fn.ThreeDots.c_settings.e_span_class).get(0);var g=e(l).css("display");var i=a(k,h);e(l).css("display","none");var j=a(k,h);e(l).css("display",g);if(i>j){return true}else{return false}}function a(i,j){var g=typeof j;if((g=="object")||(g==undefined)){return e(i).height()/j.lh}else{if(g=="boolean"){var h=f(e(i));return{lh:h}}}}function b(k){var j;var i=e.fn.ThreeDots.c_settings.valid_delimiters;k=jQuery.trim(k);var g=-1;var h=null;var l=null;jQuery.each(i,function(m,o){if(((new String(o)).length!=1)||(o==null)){return false}var n=k.lastIndexOf(o);if(n!=-1){if(n>g){g=n;h=k.substring(g+1);l=o}}});if(g>0){return{updated_string:jQuery.trim(k.substring(0,g)),word:h,del:l}}else{return{updated_string:"",word:jQuery.trim(k),del:null}}}function f(h){e(h).append("<div id='temp_ellipsis_div' style='position:absolute; visibility:hidden'>H</div>");var g=e("#temp_ellipsis_div").height();e("#temp_ellipsis_div").remove();return g}function d(k,l,m){var q=e(l).text();var i=q;var o=e.fn.ThreeDots.c_settings.max_rows;var h,g,n,r,j;var p;if(a(k,m)<=o){return}else{p=0;curr_length=i.length;curr_middle=Math.floor((curr_length-p)/2);h=q.substring(p,p+curr_middle);g=q.substring(p+curr_middle);while(curr_middle!=0){e(l).text(h);if(a(k,m)<=(o)){j=Math.floor(g.length/2);n=g.substring(0,j);p=h.length;i=h+n;curr_length=i.length;e(l).text(i)}else{i=h;curr_length=i.length}curr_middle=Math.floor((curr_length-p)/2);h=q.substring(0,p+curr_middle);g=q.substring(p+curr_middle)}}}})(jQuery);
var isOpen = false;
var __SEARCH_STRING_MAX_ALLOWED = 200; // Max px allowed
var __SEARCH_LOC_MAX_ALLOWED = 105;    // Max px allowed

/* Email to friends fields */
var EF_MYNAME = 'My Name:';
var EF_COMMENTS = 'Leave a message:';
var EF_MYEMAIL = 'My Email:';
var EF_FRIENDSEMAIl = 'To: (Separate recipients by commas)';
var EF_GRAYCOLOR = '#A4A4A4';
/* End Email to friends fields */

/* Certificate Image Title */
var CERT_TITLE_U = "Universal Suitable for all";
var CERT_TITLE_PG = "Parental Guidance";
var CERT_TITLE_12A = "Suitable for 12 years and over";
var CERT_TITLE_15 = "Suitable only for 15 years and over";
var CERT_TITLE_18 = "Suitable only for adults";
/* End Certificate Image Title */

/* Distance slider values */
var distanceValueArr = [ 0.5, 1, 2, 3, 4, 5, 10, 15, 20]; 
/* End Distance slider values */


/* SignInUp values */
var SIN_EMAIL = 'Email';
var SIN_PASSWORD = 'Password';
var SUP_POSTCODE = 'Postcode e.g. SW19 4AE';
var SUP_NICKNAME = 'Nickname';
var SUP_CONF_PASSWORD = 'Confirm Password';
/* End SignInUp values */

/* Reset Password */
var RP_EMAIL = "Enter your Email address";
/* End reset password */

/* Submission Process */
var SP_V_VENUE_NAME = 'Venue name';
var SP_V_CITY = 'City';
var SP_V_POSTCODE = 'Postcode';
var SP_V_HEAD_FIRST = "First of all, check if your venue is already listed on woZZon:";
var SP_V_HEAD_NOT_IN_LIST = "We don't seem to have your venue";

var SP_VADD_VENUE_NAME = 'Venue name';
var SP_VADD_TOWN = 'Town';
var SP_VADD_POSTCODE = 'Postcode';
var SP_VADD_COUNTY = 'County';
var SP_VADD_EMAIL = 'Email';
var SP_VADD_ADDRESS = 'Address';
var SP_VADD_PNO = 'Phone number';
var SP_VADD_TAGS = 'Tags';
var SP_VADD_CAT = 'Venue category';
var SP_VADD_DESC = 'Describe the place!';
var SP_VADD_UI = 'Any useful tips or insider info?';
var SP_VADD_OCAT ='Specify other category';
var SP_VADD_WEBADD = 'Venue website';

var SP_VADD_VUI_VMSG = 'Surely you must have something you can tell us?';

var SP_EADD_EVENT_NAME = 'Event name';
var SP_EADD_DESC = 'Event description';
var SP_EADD_SHORTD = 'Short description (75 characters)';
var SP_EADD_TAGS = 'Tags';
var SP_EADD_TNOTES = 'Additional time/date information';
var SP_EADD_ECAT ='Specify event category';

/* End Submission Process */

var GLOBAL_CNTX_PATH = "";

/* Submit tasks changes */
var ST_CHANGES = 'Type changes here..';

var NICK_NAME_INVALID_CHAR = " _ character is not allowed";

var CAMPAIGN_REDIRECT_URL = "controller.web?method=addVenueEvent";


var $ = jQuery.noConflict();
(function ($) {
	// VERTICALLY ALIGN FUNCTION
	$.fn.vAlign = function() {
		return this.each(function(i){
		var ah = $(this).height();
		var ph = $(this).parent().height();
		var mh = (ph - ah) / 2;
		$(this).css('margin-top', mh);
		});
	};
	})(jQuery);

$(document).ready(function () {

	GLOBAL_CNTX_PATH = $('#cntx').val();
	
   $("#findNow").each(function()
		   {
        $(this).mouseover(function() { 					
					   
            var src = $(this).attr("src").match(/[^\.]+/) + "_hover.png";			
            $(this).attr("src", src);
        });
        
        $(this).mouseout(function() {
            var src = $(this).attr("src").replace("_hover", "");
            $(this).attr("src", src);
        });
        
        $(this).click(function(){     
        	 SNG_SubmitSearchForm();
        });
        
        $(this).keypress(function(e) {
	        if(e.which == 13) {	           
	            SNG_SubmitSearchForm();
	        }
	    });
            
	});
   
   $("#GO").each(function()
		   {
        $(this).mouseover(function() { 					
					   
            var src = $(this).attr("src").match(/[^\.]+/) + "_hover.gif";			
            $(this).attr("src", src);
        });
        
        $(this).mouseout(function() {
            var src = $(this).attr("src").replace("_hover", "");
            $(this).attr("src", src);
        });
        
        $(this).click(function(){     
        	 SNG_SubmitSearchForm();
        });
        
        $(this).keypress(function(e) {
	        if(e.which == 13) {	           
	            SNG_SubmitSearchForm();
	        }
	    });
            
	});


	
    $('#SNG_when').click(function () {	
    $('ul.SNG_whenMenu').slideToggle('medium');
  	$('#SNG_when').addClass("searchHover"); 
	 

  	  if(isOpen) {      
	    $("a.SNG_whenMenuCont").css("border-color", "#FF0B32");
    	$("a.SNG_whenMenuCont").css("background-color", "#FFFFFF");
	    $("a.SNG_whenMenuCont").css("color", "#464545");
	     SNG_hideCalender();
		 isOpen = false;
       }  else {
		 $("a.SNG_whenMenuCont").css("border-color", "#FF7171");
		 $("a.SNG_whenMenuCont").css("background-color", "#FFF7C4");
		 $("a.SNG_whenMenuCont").css("color", "#999999");
		 isOpen = true;
	   }

    });

    $('#SNG_main input[type="text"]').each(function(){
	
	  $(this).focus(function(){
		  if(this.value == this.defaultValue) {
		    this.value = '';
		  }
		  
		  // Remove ellipses and copy back original text.
		  if($(this).attr('id')=='searchString'){
			 this.value = $('#tmp_searchString').val();
		  }else if($(this).attr('id')=='searchLocation'){
		   	  this.value =  $('#tmp_searchLocation').val();
		  }
	      $(this).addClass("SNG_searchHover");	    
	   });
	 
	  $(this).blur(function(){
		   if(this.value == '') {
		     this.value = this.defaultValue;
		   }
		   
		  // Apply ellipsis is no. of characters exceeds the limit and copy
			// original text to hidden elem.
		  if($(this).attr('id')=='searchString'){
			  if(this.value != this.defaultValue){
				  $('#tmp_searchString').val(this.value);
				  this.value = autoEllipseText(this.value, __SEARCH_STRING_MAX_ALLOWED);
			  }

		  }else if($(this).attr('id')=='searchLocation'){
			  if(this.value != this.defaultValue){
				  $('#tmp_searchLocation').val(this.value);
		   		  this.value = autoEllipseText(this.value, __SEARCH_LOC_MAX_ALLOWED);
			  }
		  }
		    
		  $(this).removeClass("SNG_searchHover");
	  });	
	  
	  $(this).change(function(){
		  	if($(this).attr('id')=='searchString'){
				 $('#tmp_searchString').val(this.value);
			  }else if($(this).attr('id')=='searchLocation'){
			   	  $('#tmp_searchLocation').val(this.value);
			  }
	  });
	  
	  $(this).keypress(function(e) {
		    if(e.which == 13) {
	            // $(this).blur();
	            // SNG_SubmitSearchForm();
	            return false;
	        }else{
	        	return true;
	        }
	  });

	  $(this).keyup(function(e){
		  if(this.id == 'searchLocation' && $("#defaultLocation") ){
			  if(this.value.length > 0){
				  $('.SNGbrowseListingIN').show();
			  }else{
				  $('.SNGbrowseListingIN').hide();
			  }
			   $("#defaultLocation").html (this.value);
		   }
		  if(this.id == 'searchString'){
			   $('#tmp_searchString').val($(this).val());
		  }
		  if(this.id == 'searchLocation'){
		   	   $('#tmp_searchLocation').val($(this).val());
		  }
		  if(e.which == 13) {
			  SNG_SubmitSearchForm();
		  }
	  });
	  
	  if($('#tmp_searchString').val() == ''){
		  $('#searchString').val('What');
	  }else{
		  $('#searchString').val(autoEllipseText($('#tmp_searchString').val(), __SEARCH_STRING_MAX_ALLOWED));
	  }
	  
	  if($('#tmp_searchLocation').val() == '') {
		   $("#searchLocation").val("Where");
	  }else{
		  $("#searchLocation").val(autoEllipseText($('#tmp_searchLocation').val(), __SEARCH_LOC_MAX_ALLOWED));
		  if($('#tmp_searchLocation').val().length > 0){
			  $('.SNGbrowseListingIN').show();
		  }else{
			  $('.SNGbrowseListingIN').hide();
		  }
		  $("#defaultLocation").html(autoEllipseText($('#tmp_searchLocation').val(), __SEARCH_LOC_MAX_ALLOWED));
	  }
	   
    });
 
	  if($("#dateCriteria").val() == 5){
		  $('div.SNG_choosedDates p:first').text(SNG_fmtDate($('#SNG_main input[name="when"]').val()) + ' -');
		  $('div.SNG_choosedDates p:last').text(SNG_fmtDate($('#SNG_main input[name="till"]').val()));
		  $('div.SNG_choosedDates').show();
		  $('div.SNG_whereText').hide();
	  }else{
		  $('div.SNG_choosedDates').hide();
		  $('div.SNG_whereText').show();
	  }
	  
	  $('.SNG_whenMenu li a').click(function () {	
		var selectedWhenItem=$(this).text();
		var dc = $(this).attr("id")
		$("#SNG_when").text(selectedWhenItem);	
		var prevDateCriteria = $("#dateCriteria").val(); 
		$("#dateCriteria").val(dc);
		 SNG_setDateCriteria(dc);
		  if( dc != '5') {
			  SNG_hideWhenMenu();
			  var now3 = new Date();		
			  var now4 = new Date();
			  now3.setHours(0,0,0,0);
			  now4.addDays(6);
			  var date = [new Date(now3), new Date(now4)];
			  $('#widgetCalendar').DatePickerSetDate(date , false);
			  $('div.SNG_choosedDates').hide();
			  $('div.SNG_whereText').show();
		  }else if( dc == '5' && prevDateCriteria != 5){
			  $('div.SNG_choosedDates').hide();
			  $('div.SNG_whereText').show();
		  }
		
	  });
	  
	  $("#defaultLocation").focus(function(){	  
	      $(this).css("border-color", "#FF7171");
	      $(this).css("background-color", "#FFF7C4");
		  $(this).css("color", "#464545");	
		  $(this).val($('#tmp_searchLocation').val());
	  });
	
	 $("#defaultLocation").blur(function(){
		   if((this.value == '')) {
			   $("#searchLocation").val("Where");
			   $('#tmp_searchLocation').val('');
	       } else {
	    	   $('#tmp_searchLocation').val($(this).val());
	    	   this.value = autoEllipseText(this.value, __SEARCH_LOC_MAX_ALLOWED);
	
	       }
		   $(this).css("border-color", "#A4C024");
	       $(this).css("background-color", "#FFFFFF");
		   $(this).css("color", "#464545");
	 }); 
	 
	 $("#defaultLocation").keypress(function(e) {
	     if(e.which == 13) {
	         $(this).blur();
	         SNG_SubmitSearchForm();
	     }
	     
	 });
	 
	 $("#defaultLocation").keyup(function(e){
		 $("#searchLocation").val(this.value);
	 });
	 
 
	 if($("#distanceSlider").length > 0){
		 var prevMiles = 10;
		 // Below min/max value will act as index number for Distance Miles
			// array.
		 $("#distanceSlider").slider({ max: 9, min: 1, step: 1 ,
			 slide: function(event, ui){ 
				value = ui.value;
				value = distanceValueArr[value -1];
				$(".SNG_distanceValue").text(value + ' miles');
			 },start: function(event, ui){
				 prevMiles = distanceValueArr[ ui.value -1];
			 }, stop: function(event, ui){ 
				value = ui.value;
				value = distanceValueArr[ value -1 ];
				$(".SNG_distanceValue").text(value + ' miles');
				if(Math.abs(prevMiles) != Math.abs(value)){
					// If distance values is changed then submit the form.
					SNG_setSearchCriteria();
					$('#radius').val(value);
					$('#pageId').val('0');  // Start from page 1
				    if($('#searchString').val() == $('#searchString').attr("defaultValue") ) $('#searchString').val('');
					if($('#searchLocation').val() == $('#searchLocation').attr("defaultValue")) $('#searchLocation').val('');
					$('#SNG_main').submit();
				}
			 }
		 });
		 
		if($("#searchLocation").val().length > 0 && $("#searchLocation").val() != $("#searchLocation").attr("defaultValue")){	 
			 var maxDistance = $('#distanceSlider').slider('option', 'max');
			 maxDistance = distanceValueArr[maxDistance -1];
			 var radius = $('#radius').val();
			 radius = Math.abs(radius);
			 if(radius && radius < maxDistance){
				 value = getIndexOfRadiusArray(radius) +1;
			 	 $("#distanceSlider").slider('option', 'value', value);
			 }else{
				 radius = maxDistance;
				 value = getIndexOfRadiusArray(radius) +1;
			 	 $("#distanceSlider").slider('option', 'value', value);
			 }
			 	
			 $(".SNG_distanceValue").text(radius + ' miles');
			 
		 }else{
			 $("#distanceSlider").slider('disable');
		 }
		 // End of Distance Slider
			
		 // Sort By
		 $(".SNG_distanceDropDown").click(function () {
	       $(".SNG_distanceMenu").slideToggle("medium");
		   $(".SNG_distanceMenu").css("display", "block");
	     });

		 $(".SNG_distanceMenu li a:first").click(function () {
			var value = $(this).text();
			if($(".SNG_distanceDropDown a:first").text() != value){
				$(".SNG_distanceDropDown a:first").text(value);
				$(this).click();
			}else{
				$(".SNG_distanceDropDown a:first").text(value);
			}
	     });

		 
	 }

	 
	 if($(".SNG_scrollingMap").length > 0){
		 $(".SNG_scrollingMap").scrollFollow({
			 	// container: 'SNG_homeCont_outer',
			 	offset : 10
		 });
	 }
	 
	if($('.SNG_winBannerCloseButton').length > 0){
			$('.SNG_winBannerCloseButton').click(function()
			{
				$('.SNG_notice-wrap').hide();
			});
	}
	

	// If its results page
	if($(".SNG_srArrow").length > 0){
		
		$('.SNG_srArrow').click(function(event) {
			var href= $(this).find("a#link").attr('href');
			if(event.target.href != undefined) {
			   // alert(event.target.href + "::" + event.type + "::" +
				// event.currentTarget);
	           // window.location = event.target.href;
	        }else{
	        	window.location = href;
	        }
	        	
		});
		
		$(".SNG_srArrow").hover(function () {
	      $(this).addClass("SNG_background");
		  $(this).removeClass("SNG_srArrow");
		  idVal = $(this).attr('id');
		  if(idVal)  ShowMarker(idVal);
	    },function () {
	      $(this).addClass("SNG_srArrow");
		  $(this).removeClass("SNG_background");
		  idVal = $(this).attr('id');
		  if(idVal) RemoveMarker(idVal);
		  
	    });
		
		$('.SNG_groupByDataCont').hover(function(){
			$(this).removeClass('SNG_groupByDataCont');
			$(this).addClass('SNG_groupByDataCont_Hover');
		},function(){
			$(this).removeClass('SNG_groupByDataCont_Hover');
			$(this).addClass('SNG_groupByDataCont')
			
		});
	    
	    $(".SNG_srTitleCont").hover(function () {
	    	$(this).css('cursor','pointer');
	      var arrowObj = $(this).parent().find('.SNG_srArrow');
	      arrowObj.addClass("SNG_background");
		  arrowObj.removeClass("SNG_srArrow");
		  idVal = arrowObj.attr('id');
		  if(idVal) ShowMarker(idVal);
	     }, function () {
	      var arrowObj = $(this).parent().find('.SNG_background')
	      arrowObj.addClass("SNG_srArrow");
		  arrowObj.removeClass("SNG_background");
		  idVal = arrowObj.attr('id');
		  if(idVal)RemoveMarker(idVal);
		  
	    });
	    
	    $('.SNG_groupByTitleCont').hover(function () {
	    	// var sib = $(this).siblings('.SNG_groupByDataCont:first');
	    	var sib = $('+ .SNG_groupByDataCont', this);
	    	var firstGR = sib.find('.SNG_srArrow:first');
	    	idVal = firstGR.attr('id');
			if(idVal) ShowMarker(idVal);
			
	    },function () {
	    	var sib = $('+ .SNG_groupByDataCont', this); // Select adjacent
															// sibling w.r.t.
															// this
	    	var firstGR = sib.find('.SNG_srArrow:first');
	    	idVal = firstGR.attr('id');
			if(idVal) RemoveMarker(idVal);
	    	
	    });
	}
	

	$('.SNG_latestNewsClose').click(function(){
		UserManager.closeLatestNewsSection(closeNewsHandler);
	});

	if($('a.zoomOtherLocations').length > 0){
		$('a.zoomOtherLocations').fancybox({
			'hideOnContentClick' : false,
			'hideOnOverlayClick': false,
			'overlayOpacity'	:	0.7,
			'overlayColor'		:	'#666',
			'autoDimensions' 	: true,
			'onStart'			:function(){
				$('#otherLocationsPopup').show();
				}	,
			'onClosed'			:function(){
					$('#otherLocationsPopup').hide();
				}
				
		});
	}
	
	if($('a.submitChangesEdit').length > 0){
		$('a.submitChangesEdit').fancybox({
			'hideOnContentClick' : false,
			'hideOnOverlayClick': false,
			'overlayOpacity'	:	0.7,
			'overlayColor'		:	'#666',
			'autoDimensions' 	: false,
			'height'			: 412,
			'scrolling'			: 'no',
			'onStart'			:function(){
					$('.SNG_submitChangesEditPopup').show();
					$('.SNG_submitChangesPop').show();
					$('.SNG_successSubmitChanges').hide();
					
				},
			'onComplete'		:function(){
					SNG_resizeFancyBox();
				},
			'onClosed'			:function(){
					SNG_hideClearAllErrors();
					$('.SNG_taskComments').val(ST_CHANGES);
					$('.SNG_submitChangesEditPopup').hide();
				}
		});
	}
	
	if($('a#emailToFriend').length > 0){
		$('a#emailToFriend').fancybox({
			'hideOnContentClick' : false,
			'hideOnOverlayClick': false,
			'overlayOpacity'	:	0.7,
			'overlayColor'		:	'#666',
			'autoDimensions' 	: false,
			'height'			: 540,
			'scrolling'			: 'no',
			'onStart'			:function(){
					$('.SNG_emailToFriendPopup').show();
					$('.SNG_emailFriends').show();
					$('.SNG_successEmailFriends').hide();
					SNG_emailFriendBinding();
				},
			'onClosed'			:function(){
					_$id('emailToFriendForm').reset();
					SNG_hideClearAllErrors(); // clear
					SNG_resetCheckBoxes('emailToFriendPopup');
					$('.SNG_emailToFriendPopup').hide().find('input[type="text"]').removeClass('popupTextField').addClass('popupTextFieldBefore');
				}

		});
	}
	
	$('a#anchorAlertPopup').fancybox({
		'hideOnContentClick' : false,
		'hideOnOverlayClick': false,
		'modal'				: false,
		'autoDimensions' 	: true,
		'onStart'			:function(){
					$('.SNG_outerPopup').show();
			},
		'onClosed'			:function(){
					$('.SNG_outerPopup').hide();
					$('.SNG_innertPopup span').html('');
			}

	});
	
	$('.SNG_addEventVenue').hover(function(){
		
		$('.SNG_addEventVenue img.AddEventVenueImg').show();
		$('.SNG_addEventVenue img.plusImg').hide();
		$(this).addClass("SNG_addEventVenueHover");
		$(this).removeClass("SNG_addEventVenue");
		
	},function(){
		$(this).addClass("SNG_addEventVenue");
		$('.SNG_addEventVenue img.AddEventVenueImg').hide();
		$('.SNG_addEventVenue img.plusImg').show();
		$(this).removeClass("SNG_addEventVenueHover");
	});
	
	if($('.SNG_whatsonLink').length > 0){
		$('.SNG_whatsonLink').click(function(event){
			var href= $(this).find("a.SNG_whatsonhereLink");
			if(event.target.href != undefined && event.target.href == ''){
				if($(this).attr('class')=='SNG_whatsonBG'){
					var thisObj = $(this);
					$(this).find('.SNG_whatsOnResult').slideUp("slow", function(){
						thisObj.addClass("SNG_whatsonLink");
						thisObj.removeClass("SNG_whatsonBG");
						thisObj.find('.SNG_showHideBtn a').removeClass('SNG_whatsonActiveBtn');
					});
				}else{
					var thisObj = $(this);
					thisObj.addClass("SNG_whatsonBG");
					thisObj.removeClass("SNG_whatsonLink");
					thisObj.find('.SNG_showHideBtn a').addClass('SNG_whatsonActiveBtn');
					$(this).find('.SNG_whatsOnResult').slideDown("slow", function(){});
				}
			} else if(event.target.href != undefined && event.target.href != ''){
				window.location = event.target.href;
			}
		});
	}
	
	if($('.SNG_edMainImageNav').length > 0){
	   $('.SNG_edMainImageNav a').mouseover(function(){
		   var imgObj = $(this).find('img');
		   var src = imgObj.attr('src').match(/[^\.]+/) + '_h.png';
		   imgObj.attr('src', src);
		   var infoObj = $('+ .hoverinfo', this);
		   infoObj.show();
	   });
	   $('.SNG_edMainImageNav a').mouseout(function(){
		   var imgObj = $(this).find('img');
		   var src = imgObj.attr('src').replace('_h','');
		   imgObj.attr('src', src);
		   var infoObj = $('+ .hoverinfo', this);
		   infoObj.hide();
	   });
	}
	
	if($('.SNG_edDescriptionNo .SNG_addDescription').length > 0){
		   $('.SNG_addDescription').mouseover(function(){
			   var imgObj = $(this).find('img');
			   var src = imgObj.attr('src').match(/[^\.]+/) + '_h.png';
			   imgObj.attr('src', src);
		   });
		   $('.SNG_addDescription').mouseout(function(){
			   var imgObj = $(this).find('img');
			   var src = imgObj.attr('src').replace('_h','');
			   imgObj.attr('src', src);
		   });
		   
		   
	}
	
	if($('a#addDescriptionLink').length > 0 ){
		$('a#addDescriptionLink').fancybox({
			'hideOnContentClick' : false,
			'hideOnOverlayClick': false,
			'overlayOpacity'	:	0.7,
			'overlayColor'		:	'#666',
			'autoDimensions' 	: false,
			'height'			: 412,
			'scrolling'			: 'no',
			'onStart'			:function(){
					$('.SNG_addDescriptionPopup').show();
					$('.SNG_addDescriptionPop').show();
					$('.SNG_successAddDescription').hide();
					
				},
			'onComplete'		:function(){
					SNG_resizeFancyBox();
				},
			'onClosed'			:function(){
					SNG_hideClearAllErrors();
					$('.SNG_taskDescription').val('');
					$('.SNG_addDescriptionPopup').hide();
				}
	    });
	}
	
	if($('.SNG_submittedBY').length > 0 ){
		$('.SNG_submittedBY a').hover(function(){
			var imgObj = $(this).find('img');
			var src = imgObj.attr('src').match(/[^\.]+/) + '_h.png';
			imgObj.attr('src', src);
			$('.SNG_submittedBY .hoverinfo').show();
		},function(){
			var imgObj = $(this).find('img');
		    var src = imgObj.attr('src').replace('_h','');
		    imgObj.attr('src', src);
			$('.SNG_submittedBY .hoverinfo').hide();
		});
	}
	
	if($('.SNG_entitySBReport').length > 0){
		   $('.SNG_entitySBReport a').mouseover(function(){
			   var imgObj = $('.SNG_entitySBReport img');
			   var src = imgObj.attr('src').match(/[^\.]+/) + '_h.png';
			   imgObj.attr('src', src);
			   var infoObj = $('.SNG_entitySBReport .hoverinfo');
			   infoObj.show();
		   });
		   $('.SNG_entitySBReport a').mouseout(function(){
			   var imgObj = $('.SNG_entitySBReport img');
			   var src = imgObj.attr('src').replace('_h','');
			   imgObj.attr('src', src);
			   var infoObj = $('.SNG_entitySBReport .hoverinfo');
			   infoObj.hide();
		   });
		}
	
	if($(".tab_content").length > 0 ) {
		
		// Default Action
		$(".tab_content").hide(); // Hide all content
		$("ul.tabs li a:first").addClass("activeDetailTab").show(); // Activate
																	// first tab
		$(".tab_content:first").show(); // Show first tab content
		
		// On Click Event
		$("ul.tabs li").click(function() {
			$("ul.tabs li a").removeClass("activeDetailTab"); // Remove any
																// "active"
																// class
			$(this).find("a").addClass("activeDetailTab"); // Add "active"
															// class to selected
															// tab
			$(".tab_content").hide(); // Hide all tab content
			var activeTab = $(this).find("a").attr("href"); // Find the rel
															// attribute value
															// to identify the
															// active tab +
															// content
			$(activeTab).fadeIn(); // Fade in the active content
			return false;
		});
	}
	
	if($('.SNG_whatOnNBL').length > 0){
		$('.SNG_whatOnNBL').click(function(){
			var obj = $(this).find("a");
			var sib = $('+ .SNG_whatOnNBDetails', this);
			if(obj.attr('class')=='WONActive'){						
				sib.slideUp("slow", function(){
					obj.removeClass("WONActive");
				});				
			}else{								
				sib.slideDown("slow", function(){
					obj.addClass("WONActive");	
				});
				
			}
		});
	}
	
	if($('.SNG_whatOnNBLEv').length > 0){
		$('.SNG_whatOnNBLEv').mouseover(function(){
			var obj = $(this).find("a");
			var sib = $('+ .SNG_whatOnNBDetails', this);
			if(obj.attr('class')=='WONActive'){						
				sib.slideUp("slow", function(){
					obj.removeClass("WONActive");
				});				
			}else{								
				sib.slideDown("slow", function(){
					obj.addClass("WONActive");	
				});
				
			}
		});
		$('.SNG_whatOnNBLEv').mouseout(function(){
			var obj = $(this).find("a");
			var sib = $('+ .SNG_whatOnNBDetails', this);
			if(obj.attr('class')=='WONActive'){						
				sib.slideUp("slow", function(){
					obj.removeClass("WONActive");
				});				
			}else{								
				sib.slideDown("slow", function(){
					obj.addClass("WONActive");	
				});
				
			}
		});
	}
	
	
	if($('.SNG_edRTitle').length > 0){
		$('.SNG_edRTitle').click(function(){
			if($(this).hasClass('SNG_edRTitleExp')){
				$(this).addClass('SNG_edRTitle');
				$(this).removeClass('SNG_edRTitleExp');
				var sib = $('+ #reviewarea', this);
				sib.slideDown("slow");
			}else{
				var thisObj = $(this);
				var sib = $('+ #reviewarea', this);
				sib.slideUp("slow", function(){
					thisObj.removeClass('SNG_edRTitle');
					thisObj.addClass('SNG_edRTitleExp');	
				});
			}
		});
	}
	
	if(	$('a#signinlink').length > 0){
		$('a#signinlink').fancybox({
			'hideOnContentClick': false,
			'hideOnOverlayClick': false,
			'overlayOpacity'	:	0.7,
			'overlayColor'		:	'#666',
			'autoDimensions' 	: false,
			'height'			: 600,
			'width'				: 575,
			'changeSpeed'		: 10,
			'speedIn'			: 0,
			'speedOut'			: 0,
			'showNavArrows'		: false,
			'scrolling'			: 'no',
			'onStart'			:function(){
					var whichLink = $('#whichLink').val();
					if(whichLink == 'Login' || (whichLink != 'SignUp' && whichLink != 'Facebook')){
						$('#loginMainDiv').removeClass('popupFormContentUnHL');
						if(!$('#signUpMainDiv').hasClass('popupFormContentUnHL')){
							$('#signUpMainDiv').addClass('popupFormContentUnHL')
						}
						_$id('registration_form').reset();
						_$id('signUpForm').reset();
						hideAllSignInUPPops();
						$('#signInUpPopup').show();
						// $('#signUpPopup').hide();
					}else if(whichLink == 'SignUp'){
						$('#signUpMainDiv').removeClass('popupFormContentUnHL');
						if(!$('#loginMainDiv').hasClass('popupFormContentUnHL')){
							$('#loginMainDiv').addClass('popupFormContentUnHL')
						}
						hideAllSignInUPPops();
						$('#signInUpPopup').show();
						_$id('registration_form').reset();
						_$id('signUpForm').reset();
						// $('#signUpPopup').hide();
					}else if(whichLink == 'Facebook'){
						if(!$('#loginMainDiv').hasClass('popupFormContentUnHL')){
							$('#loginMainDiv').addClass('popupFormContentUnHL')
						}
						// //$('#signInUpPopup').hide();
						// $('#signUpPopup').hide();
						_$id('fbSignUpForm').reset();
						hideAllSignInUPPops();
						$('#fbSignUpPopup').show();
					}
					SNG_resetCheckBoxes('signInUpProcess');
					$('#signInUpProcess').show().find('input[type="text"]').removeClass().addClass('popupTextFieldBefore');
					if($('#login_email').val() != SIN_EMAIL){
						$('#login_email').removeClass('popupTextFieldBefore').addClass('popupTextField');
					}
					
					SNG_hideClearAllErrors(); // clear and resize
				},
			'onClosed'			:function(){
					// TODO: Or refresh all fields here... if user Sign in
					hideAllSignInUPPops();
					
				}
		});
		
	}
	

	// SNG_loadContainerBindings();
	
	$('.popupFormContent textarea').focus(function(){
		if($(this).attr('id') == 'message' && trim($(this).val()) == EF_COMMENTS){
			$(this).val('');
		}else if($(this).attr('id') == 'taskComments' && trim($(this).val()) == ST_CHANGES ){
			$(this).val('');
		}
		
		$(this).removeClass('popupTextFieldBefore');
		$(this).addClass('popupTextField');
	});
	
	$('.popupFormContent textarea').blur(function(){
		if($(this).attr('id') == 'message' && trim($(this).val()) == ''){
			$(this).val(EF_COMMENTS);
		}else if($(this).attr('id') == 'taskComments' && trim($(this).val()) == ''){
			$(this).val(ST_CHANGES);
		}
		
		$(this).removeClass('popupTextField');
		$(this).addClass('popupTextFieldBefore');
	});
	
	

	if(	$('a#weeklyAlertLink').length > 0){
		$('a#weeklyAlertLink').fancybox({
			'hideOnContentClick' : false,
			'hideOnOverlayClick': false,
			'overlayOpacity'	:	0.7,
			'overlayColor'		:	'#666',
			'autoDimensions' 	: false,
			'height'			: 322,
			'showNavArrows'		: false,
			// 'scrolling' : 'no',
			'onStart'			:function(){
				SNG_resetCheckBoxes('saveSearchAlertPopup_content');
				SNG_hideClearAllErrors();
				$('#saveSearchAlertPopup').show();
				},
			'onClosed'			:function(){
					$('#saveSearchAlertPopup').hide();
				}
		});
		
	}

	
		$('a#imageUploadingLink').fancybox({
			'hideOnContentClick' : false,
			'hideOnOverlayClick': false,
			// 'modal' : false,
			'overlayColor'		:	'#666',
			'autoDimensions' 	: false,
			// 'height' : 600,
			'width'				: 550,
			'onStart'			:function(){
				    // alert("start");
					$('#imageUploadProcess').show();
					if($('#imageUploadingSource').val() == 'New'){
						SNG_showUploadDlg(); 
						// clearSessionMoreImage();
					}else if($('#imageUploadingSource').val() == 'Edit'){
						editImg(_$id('image2').value);
					}else if($('#imageUploadingSource').val() == 'Delete'){
						showDeleteImg();
					}else if($('#imageUploadingSource').val() == 'Flag'){
						showDivReport(imgs[imgCounter]);
					}
					
				},
			'onComplete'		:function(){
					var hgt = '';
					var changeHeight = true;
					if($('#imageUploadingSource').val() == 'New'){
						hgt = $('#div_upload').height();
					}else if($('#imageUploadingSource').val() == 'Edit'){
						hgt = $('#div_crop').height();
						hgt += 120;
						changeHeight = false;
					}else if($('#imageUploadingSource').val() == 'Delete'){
						hgt = $('#div_delete_pic').height();
					}else if($('#imageUploadingSource').val() == 'Flag'){
						hgt = $('#div_report_pic').height();
					}
					if(changeHeight){
						hgt = $('#chageLocationPopupId').height();
					}
					$('#fancybox-inner').height(hgt );
					$('#fancybox-wrap').height(hgt + 20);
					$.fancybox.center();
					// alert(hgt + ", " + $('#fancybox-inner').height());
				},
			'onClosed'			:function(){
						closeSource = hideAllImageUploadingDivs();
						// alert(closeSource);
						if(closeSource == 'Upload'){
							$('#div_upload').find('.imageUploadClose').click();
						}else if(closeSource == 'Crop'){
							$('#div_crop').find('.imageUploadClose').click();
						}else if(closeSource == 'Delete'){
							$('#div_delete_pic').find('.imageUploadClose').click();
						}else if(closeSource == 'Report'){
							$('#div_report_pic').find('.imageUploadClose').click();
						}else if(closeSource == 'CReport'){
							$('#div_confirm_report').find('.imageUploadClose').click();
						}
						
				}
	
		});
		
		SNG_checkBoxesBinding('emailToFriendPopup');
		
		if($('.SNG_mwMainImageNavCont').length > 0){
			   $('.SNG_mwMainImageNavCont a').mouseover(function(){
				   $('.SNG_addToolTip').show();				   
				   var imgObj = $(this).find('img');				 
				   if(imgObj.length > 0 ) {
					   var src = imgObj.attr('src').match(/[^\.]+/) + '_h.png';
					   imgObj.attr('src', src);
				   }
				   
			   });
			   $('.SNG_mwMainImageNavCont a').mouseout(function(){
				   $('.SNG_addToolTip').hide();				   
				   var imgObj = $(this).find('img');
				   if(imgObj.length > 0 ) {
					   var src = imgObj.attr('src').replace('_h','');
					   imgObj.attr('src', src);
				   }
				   
			   });
			   
			   $('.SNG_imageDeleteLnk').mouseover(function(){
				   $('.SNG_addToolTip').text('Delete your image');
				   $('.SNG_addToolTip').show();	
				   	
				   
				   
			   });
			   $('.SNG_imageDeleteLnk').mouseout(function(){
				   $('.SNG_addToolTip').text('Add an image');
				   $('.SNG_addToolTip').hide();			   
			   });
		}
		
		// venue event promotion page
		if($('a.SNG_prShowHide').length > 0) {
			$('a.SNG_prShowHide').click(function(){
				if($(this).text() == 'Close'){
					var sib = $('.SNG_prDetails');
					sib.slideUp("slow");
					$(this).text('Click for full details')
					$(this).removeClass("SNG_prShowHideUp");
					$(this).addClass("SNG_prShowHide"); 
				}else{					
					var sib = $('.SNG_prDetails');					
					sib.slideDown("slow");
					$(this).text('Close');
					$(this).removeClass("SNG_prShowHide");
					$(this).addClass("SNG_prShowHideUp");
					
				}
			});				
		}
				
		
		
});

function closeNewsHandler(source){
	if(source!='error'){
		$('.SNG_latestNewsCont').hide('slow');
	}else{
		alert("Error closing..");
	}
}


document.onclick = function (evt) {
 var src;
 if (evt && evt.target)
 {
  src = evt.target;
 }else if (window.event)
 {
     src = window.event.srcElement;
 }
   
 if(src.id != 'SNG_when' && src.id != '5') {
    if(isOpen) { 
    	 SNG_hideWhenMenu();
    }
  }  
  
}

function SNG_hideWhenMenu(){
	if(isOpen) { 
        $('ul.SNG_whenMenu').slideToggle('slow');  
        isOpen = false;
	    $("a.SNG_whenMenuCont").css("border-color", "#FF0B32");
    	$("a.SNG_whenMenuCont").css("background-color", "#FFFFFF");
	    $("a.SNG_whenMenuCont").css("color", "#464545");
	    SNG_hideCalender();
    }	
}

function SNG_hideCalender(){
	if(state) {
		$('#widgetCalendar').stop().animate({height: state ? 0 : $('#widgetCalendar div.datepicker').get(0).offsetHeight}, 500);
		state = !state;			
		if(state) $('div.calanderHelp').css('display', '');
		else $('div.calanderHelp').css('display', 'none');	
	}
}

function SNG_hideCalenderFT(){
	if(stateFT) {
		$('#widgetCalendarFT').stop().animate({height: stateFT ? 0 : $('#widgetCalendarFT div.datepickerft').get(0).offsetHeight}, 500);
		stateFT = !stateFT;
	}
}


function SNG_setWhatWhere(searchStr, searchLoc){	
	if(searchStr != '') {
			$('#searchString').val(searchStr);
			$('#tmp_searchString').val(searchStr);
	}
	if(searchLoc != '') {
			$('#searchLocation').val(searchLoc);	
			$('#tmp_searchLocation').val(searchLoc);
	    	
	}
	var dc =  $("#dateCriteria").val();	
	var when = $('#'+dc);
	if(when && !(searchStr == '' && searchLoc == '')) {		
	   $("#SNG_when").text(when.text());	
	}
}

function SNG_setDateCriteria(dc){
	var val = parseInt(dc);
	switch(val) {				
		case 3: SNG_setTomorrowDate(); break;
		case 4: SNG_setWeekendDates(); break;
		case 5: SNG_chooseDates($('#widgetCalendar').DatePickerGetDate(true)); break;
		default: SNG_setDefaultDate();	
	}
}

function SNG_chooseDates(formated) {
	var str = new String(formated);			
	var dates;				
	if( str.indexOf(',') == 10) {					
		dates = str.split(',');	
		$('#SNG_main input[name="when"]').val(dates[0]);
		$('div.SNG_choosedDates p:first').text(SNG_fmtDate(dates[0]) + ' -');
		$('#SNG_main input[name="till"]').val(dates[1]);
		$('div.SNG_choosedDates p:last').text(SNG_fmtDate(dates[1]));
		$('div.SNG_choosedDates').show();
		$('div.SNG_whereText').hide();
	}

}


function SNG_showChooseDates(){
	SNG_chooseDates($('#widgetCalendar').DatePickerGetDate(true));
}
function SNG_setWeekendDates() {
     var dateFrom = new Date();  
     var dateTo = new Date();
	 var FRIDAY = 5;
	 var SATURDAY = 6 ;
	 var SUNDAY = 0;	 	 		   
	 
	  var day = dateFrom.getDay();
	  if( day > SUNDAY && day  <= FRIDAY)  {
	     day = FRIDAY - day;
		 dateFrom.setDate(dateFrom.getDate()+day);
		 dateTo.setDate(dateFrom.getDate() + 2);		 
	  } else if(day == SATURDAY) {
		  dateTo.setDate(dateFrom.getDate() + 1);		 
	  }
	  $('#SNG_main input[name="when"]').val( dateFrom.print("%d/%m/%Y"));   
	  $('#SNG_main input[name="till"]').val(  dateTo.print("%d/%m/%Y"));	 
}

function SNG_setTomorrowDate() {
	var date = new Date();			
	date = new Date(date.getTime() + Date.DAY); 
	var tomorrow =  date.print("%d/%m/%Y");			
	$('#SNG_main input[name="when"]').val(tomorrow);   
	$('#SNG_main input[name="till"]').val(tomorrow);
	
}

function SNG_setDefaultDate(){	
	var date = new Date();	
	var allDate = date.print("%d/%m/%Y");	
	$('#SNG_main input[name="when"]').val(allDate);   
	$('#SNG_main input[name="till"]').val(allDate);	
}

function SNG_SubmitSearchForm() {
	var searchStr = $('#searchString');
	var searchLoc = $('#searchLocation');
	var loc = searchLoc.attr("value");
	var ser = searchStr.attr("value");
	
	if(ser == searchStr.attr("defaultValue") && loc == searchLoc.attr("defaultValue")) {
	     // alert('Please provide search criteria');
		SNG_alert('Please enter a keyword or location');
		 return;
	}        	
	
	if(ser == searchStr.attr("defaultValue")) {
		searchStr.attr("value","");
	}
				
	if(loc == searchLoc.attr("defaultValue")) {
		searchLoc.attr("value","");
	}	

	// Reset the date criteria.
	var dateCriteria = $("#dateCriteria").val();
	if( dateCriteria != '5') {
	   SNG_setDateCriteria(dateCriteria);
	}
			
	// Setting back ellipsis text to original text
	searchStr.attr("value", $('#tmp_searchString').val());
	searchLoc.attr("value", $('#tmp_searchLocation').val());
	
	// $("#SNG_main").submit();
	SNG_searchEvents(true, true);
}
var SNG_daysShort = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];

function SNG_fmtDate(dateStr){
	var format = 'a d/m/Y';
	var dateParts = dateStr.split('/');
	var date = new Date();
	date = Date.parseDate(dateStr,'%e%m%y');
	var m = date.getMonth();
	var d = date.getDate();
	var y = date.getFullYear();
	var wn = date.getWeekNumber();
	var w = date.getDay();
	var s = {};
	var hr = date.getHours();
	var pm = (hr >= 12);
	var ir = (pm) ? (hr - 12) : hr;
	var dy = date.getDayOfYear();
	if (ir == 0) {
		ir = 12;
	}
	var min = date.getMinutes();
	var sec = date.getSeconds();
	var parts = format.split(''), part;
	for ( var i = 0; i < parts.length; i++ ) {
		part = parts[i];
		switch (parts[i]) {
			case 'a':
				part = SNG_daysShort[date.getDay()];
				break;
			case 'A':
				part = date.getDayName(true);
				break;
			case 'b':
				part = date.getMonthName();
				break;
			case 'B':
				part = date.getMonthName(true);
				break;
			case 'C':
				part = 1 + Math.floor(y / 100);
				break;
			case 'd':
				part = (d < 10) ? ("0" + d) : d;
				break;
			case 'e':
				part = d;
				break;
			case 'H':
				part = (hr < 10) ? ("0" + hr) : hr;
				break;
			case 'I':
				part = (ir < 10) ? ("0" + ir) : ir;
				break;
			case 'j':
				part = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy;
				break;
			case 'k':
				part = hr;
				break;
			case 'l':
				part = ir;
				break;
			case 'm':
				part = (m < 9) ? ("0" + (1+m)) : (1+m);
				break;
			case 'M':
				part = (min < 10) ? ("0" + min) : min;
				break;
			case 'p':
			case 'P':
				part = pm ? "PM" : "AM";
				break;
			case 's':
				part = Math.floor(date.getTime() / 1000);
				break;
			case 'S':
				part = (sec < 10) ? ("0" + sec) : sec;
				break;
			case 'u':
				part = w + 1;
				break;
			case 'w':
				part = w;
				break;
			case 'y':
				part = ('' + y).substr(2, 2);
				break;
			case 'Y':
				part = y;
				break;
		}
		parts[i] = part;
	}
	return parts.join('');
}


function autoEllipseText(text, width)
{
   inSpan = document.getElementById('ellipsisSpan');
   inSpan.innerHTML = text;
  // alert($('#ellipsisSpan').width());

   if(inSpan.offsetWidth > width)
   {
      var i = 1;
      inSpan.innerHTML = '';
      while(inSpan.offsetWidth +5 < (width) && i < text.length)
      {
         inSpan.innerHTML = text.substr(0,i) + '...';
         i++;
      }
               
      returnText = inSpan.innerHTML;
      return returnText;
   }
   return text;
} 

	
	function SNG_writeStar(totalRates, ratingUsers, id, link, isVenue) {
	
		cntx = document.getElementById('cntx');
		if(cntx != null) cntx = cntx.value;	
		
	    var starTitle = ["", "Terrible", "Bad", "Just OK","Good","Excellent"];
		var num=0,maxRating =5,curnum = 0,curnumhalf,obj;
		num = ( (ratingUsers==0)? 0 : (totalRates/ratingUsers) );
		num = ((num>maxRating)? maxRating : num );
		var starHtml='';
	    var message;
	
		var rImg = null;
		var rImgCount = 0;
		
        for (curnum = 1; curnum <= maxRating; curnum++) {
			if (num >= curnum) {
				rImgCount++;
			}
			else {
				curnumhalf = curnum - 0.51;
				if (num >= curnumhalf) {
					rImgCount++;
				}
			}
		}	
        if(isVenue){
        	rImg = cntx + 'SNG_images/stars-green' + rImgCount + '.png';
        }else{
        	rImg = cntx + 'SNG_images/stars' + rImgCount + '.png';
        }
        starHtml +='<img src="'+rImg+'" width="68" height="13" />';
        
		message = ratingUsers+' user ratings; average rating: ' + (Math.round(num * 10)/10) + ' (' + starTitle[Math.round(num)] + ')';
		starHtml = '<a href="'+ link + '"  title="' + message + '">' + starHtml + '</a> ' ;
		starHtml += '('+ratingUsers+')'; // <img src="images/spacer.gif"
											// alt="" width="5" height="5" />
											// remove space between stars and
											// counter
	   
		var obj= null;
		if(isVenue && isVenue == true){
			obj = $('#vrating' +id);
		}else{
			obj = $('#rating' +id);// Title rating
		}
	    obj.html(starHtml);        
	    obj.show();
	}
	
	function SNG_changPageSize(pageSize) {
		SNG_setSearchCriteria()     
		$('#pageId').val('0'); 
		$('#pageSize').val(pageSize);
		rememberPref(pageSize);
		$("#SNG_main").submit();
	}

	function SNG_openHideTitleGroup(lnk_group, group, hide_group){
		group.toggle();
		hide_group.toggle();
		lnk_group.toggle();
	}
	
		function getUnselectedMarkerImage(categoryName){
		var imageName = "zoom.png";
		switch(categoryName){
			case 0: 	// "Other":
						imageName = "map_pointer.png";
					 	break;
			case 1101: // "Film":
						imageName = "map_unselected_events_film.png";
					 	break;
			case 1102: // "Classical":
						 imageName = "map_unselected_events_classical.png";
					 	 break;
			case 1103: // "Music":
						 imageName = "map_unselected_events_music.png";
					 	 break;
			case 1104: // "Attraction":
						 imageName = "map_unselected_events_tourist_attractions.png";
					 	 break;
			case 1105: // "Museums":
						 imageName = "map_unselected_events_galleries_and_museums.png";
					 	 break;
			case 1106: // "Opera":
						 imageName = "map_unselected_events_opera.png";
					 	 break;
			case 1107: // "Comedy":
						 imageName = "map_unselected_events_comedy.png";
					 	 break;
			case 1108: // "Clubs":
						 imageName = "map_unselected_events_clubbing.png";
					 	 break;
			case 1109: // "Special Events":
						 imageName = "map_unselected_events_events.png";
					 	 break;
			case 1110: // "Theatre":
						 imageName = "map_unselected_events_theatre.png";
					 	 break;
			case 1111: // "Dance":
						 imageName = "map_unselected_events_dance.png";
					 	 break;
			case 1112: // "Galleries":
						 imageName = "map_unselected_events_galleries_and_museums.png";
					 	 break;
			case 1113: // "Bars":
						 imageName = "map_unselected_events_pubs.png";
					 	 break;
			case 1114: // "Art Centre":
						 imageName = "map_unselected_events_art.png";
					 	 break;
			case 1116: // "Coffee shops":
						 imageName = "map_unselected_events_cafes.png";
					 	 break;
			case 1117: // "Restaurants":
						 imageName = "map_unselected_events_restaurant.png";
					 	 break;
			case 1118: // "Pubs":
						 imageName = "map_unselected_events_pubs.png";
					 	 break;

		}
		
		return imageName;
	}
	
	function getSelectedMarkerImage(categoryName){
		var imageName = "zoom.png";
		switch(categoryName){
			case 1101: // "Film":
						imageName = "map_selected_events_film.png";
					 	break;
			case 1102: // "Classical":
						 imageName = "map_selected_events_classical.png";
					 	 break;
			case 1103: // "Music":
						 imageName = "map_selected_events_music.png";
					 	 break;
			case 1104: // "Attraction":
						 imageName = "map_selected_events_tourist_attractions.png";
					 	 break;
			case 1105: // "Museums":
						 imageName = "map_selected_events_galleries_and_museums.png";
					 	 break;
			case 1106: // "Opera":
						 imageName = "map_selected_events_opera.png";
					 	 break;
			case 1107: // "Comedy":
						 imageName = "map_selected_events_comedy.png";
					 	 break;
			case 1108: // "Clubs":
						 imageName = "map_selected_events_clubbing.png";
					 	 break;
			case 1109: // "Special Events":
						 imageName = "map_selected_events_events.png";
					 	 break;
			case 1110: // "Theatre":
						 imageName = "map_selected_events_theatre.png";
					 	 break;
			case 1111: // "Dance":
						 imageName = "map_selected_events_dance.png";
					 	 break;
			case 1112: // "Galleries":
						 imageName = "map_selected_events_galleries_and_museums.png";
					 	 break;
			case 1113: // "Bars":
						 imageName = "map_selected_events_pubs.png";
					 	 break;
			case 1114: // "Art Centre":
						 imageName = "map_selected_events_art.png";
					 	 break;
			case 1116: // "Coffee shops":
						 imageName = "map_selected_events_cafes.png";
					 	 break;
			case 1117: // "Restaurants":
						 imageName = "map_selected_events_restaurant.png";
					 	 break;
			case 1118: // "Pubs":
						 imageName = "map_selected_events_pubs.png";
					 	 break;

		}
		
		return imageName;
	}
	
function getSNG_EntityRating(entityId, isVenue)  {
	
	cntx = document.getElementById('cntx');
	if(cntx) cntx = cntx.value;
	
   UserManager.getEntityRating(entityId, function(entityRating) {
       if(entityRating) {
          if(isVenue){
        	  SNG_selstar(entityRating.totalRates, entityRating.ratingUsers, true); 
		  }else{
			  SNG_selstar(entityRating.totalRates, entityRating.ratingUsers); 
		  }
		  
       }
   });
}

function SNG_selstar(totalRates,ratingUsers, isVenue) {
	var num=0,maxRating =5,curnum = 0,curnumhalf,obj;
	num = ( (ratingUsers==0)? 0 : (totalRates/ratingUsers) );
	num = ((num>maxRating)? maxRating : num );
	
	var rImg = cntx+'SNG_images/stars-norating.png';

	var ratingNum = 0;
	for (curnum = 1; curnum <= maxRating; curnum++) {

			if (num >= curnum) {
				ratingNum++;
			}
			else {
				curnumhalf = curnum - 0.51;

				if (num >= curnumhalf) {
					ratingNum++;
				}

			}

		}
	if($('#SNG_topRatingBox:visible').length > 0){

	}else{
		$('#SNG_topRatingBox').show();
		$('.SNG_eventTitleCont h6').hide();
	}

	
	if(ratingNum > 0 ) {
		if(isVenue){
				rImg = cntx+'SNG_images/starsV'+ ratingNum +'.png';
		}else{
			rImg = cntx+'SNG_images/starsE'+ ratingNum +'.png';
			
		}
		
	}
	$("#SNG_star").attr("src", rImg);
	if($("#SNG_star2").length > 0 ) {
		$("#SNG_star2").attr("src", rImg);
	}

}	
	

	// Below functions needs to be changed to user jQuery.
	var updateVenueUserReview = false;
	function SNG_updateUserReview(id, isVenue) {
	   var comment =  $('#userComment').val(); 
	   var rating = $('#rating').val();
	   var entityId = $('#entityID').val();
	   var termsAndConditions = _$id('termsAndConditionsReview');
	   if(id != 0 && (comment == ' Add your comments here' || comment.length == 0)) {
		   SNG_alert("Complete your review before submitting. Both rating and comments are compulsory.");
	   } else if (comment.length > 1000) {
		   $('#userComment').val(comment.substring(0,1000));
		   SNG_alert("Comment text can not exceed 1000 characters.");
	   } else if (rating == 0) {
		   SNG_alert("Complete your review before submitting. Both rating and comments are compulsory.");
	   } else if (!(termsAndConditions!=null && termsAndConditions.checked) ) {
		   SNG_alert("You must accept our review terms & conditions before you can submit a review.");
	   }else {
	   	  if(isVenue){
	   		  updateVenueUserReview = true;
		  }else{
		   		isVenue = false;
	   	  }

		  UserManager.updateUserReview(id, comment, rating, entityId, isVenue, SNG_updateUserReviewHandler);
		  userVenueRating = parseInt(rating);
	   }
	}
	
	function SNG_updateUserReviewHandler(source) {
	
		 var entityId = _$id('entityID').value;	
	     var obj= _$id('showcomments');
	     var hide= _$id('hideComments');		 
		 var rate_this_venue = document.getElementById('rate_this_venue');	 
	     if( source == "error" ) 
	    	 SNG_alert("Error processing your request.");		 
	     else {  
	          
	        obj.innerHTML = source;
	        SNG_showCommentArea(false);

			if(_$id('reviewMain') != null ) _$id('reviewMain').style.display = 'none';
			if(_$id('reviewMainBotton') != null ) _$id('reviewMainBotton').style.display = 'none';
			if(_$id('isEdit') != null) _$id('isEdit').value = 'No' ;
			var allComments = _$id('showAllComments');
		    if(allComments) {     	   
		        allComments.style.display = 'none';
		    }
		    if(hide) hide.style.display = 'none';
			if(updateVenueUserReview){
				getSNG_EntityRating(entityId, true);
			}else{
				getSNG_EntityRating(entityId);
			}
			updateVenueUserReview = false;
			if(null != _$id('isVenue')) SNG_showAllReviews();
			if(null != _$id('isEvent')) SNG_showAllComments(_$id('entityID').value,0);
			if(rate_this_venue != null) rate_this_venue.style.display='none';
			
		}
		
	}
	
	var userRating = 0;
	function SNG_addCommentEvent(id, venueId) {
		
			 var comment =  $('#userComment').val(); 
			 var termsAndConditions = _$id('termsAndConditionsReview');
			 var rating = $('#rating').val();
			 var pgId = $('#_pgId').val();
			 pgId = parseInt(pgId);
			 if(id != 0 && (comment == ' Add your comments here' || comment.length == 0)) {
				 SNG_alert("Complete your review before submitting. Both rating and comments are compulsory.");
			 } else if (comment.length > 1000) {
				 SNG_alert("Comment text can not exceed 1000 characters.");
			 } else if (rating == 0) {
				 SNG_alert("Complete your review before submitting. Both rating and comments are compulsory.");
			 } else if (!(termsAndConditions!=null && termsAndConditions.checked) ) {
				 SNG_alert("You must accept our review terms & conditions before you can submit a review.");
			 } else {
				// clearMessage();
				
				UserManager.addUserCommentEvent(id, venueId, pgId, comment, rating, SNG_addUserCommentsHandler);
				userRating = parseInt(rating);
			 }
		
	}

	function SNG_addUserCommentsHandler(source) {
	   var obj= _$id('showcomments');
	   var hide= _$id('hideComments');
	   if( source == "error" ) 
		   SNG_alert("Error processing your request.");	
	   else if(source == "ShowAddCommentArea") {
		   SNG_showCommentArea(true);
	   }
	   else if( source == "logout")  {
		 if(_$id('commentarea') != null) {  
		   	showLoginTable('SubmitRating',_$id('commentarea'));		
			return;
		 }
		  // document.getElementById("aw_tbl_login").style.display = "";
	   }
	   else if( source == "SessionOut")  {
		   SNG_alert("Login session expired.");  		
	   }
	   else  if(source == "AlreadyReviewed" ) {
		   	SNG_alert("You have already reviewed this event.");
			SNG_showCommentArea(false);
	     	_$id('userComment').value ='' ;
	     	SNG_showAllComments(_$id('entityID').value,0);
		 } else {          
	     obj.innerHTML = source;
	     SNG_showCommentArea(false);
	     _$id('userComment').value ='' ;
	     obj.style.display = '';
	     var allComments = _$id('showAllComments');
	     if(allComments) {
	        if(hide) hide.style.display = 'none';
	        allComments.style.display = 'none';
	     }
	     var  reviewArea = _$id('reviewarea');
	     if(reviewArea) {
	        reviewArea.style.display = '';     
	     }
	     var userCommentCount =_$id('userCommentCount').value;
	     var totalRating = _$id('totalRating').value  ;
	     totalRating = parseInt(userRating) + parseInt(totalRating);
	     userCommentCount = parseInt(userCommentCount) +  1;
	     _$id('userCommentCount').value = userCommentCount;
	     SNG_selstar(totalRating , userCommentCount);     
	     if(userCommentCount == 1 ) {
	       _$id('averageReview').style.display = '';   
	       // _$id('firstReview').style.display = 'none';
	      } 
		 _$id('totalReview').innerHTML = userCommentCount ;
		 if(userCommentCount > 1){
			$('.SNG_edRatingText').html('ratings');
		 }else{
			 $('.SNG_edRatingText').html('rating');
		 }
	   }
	}
	
	
	function SNG_getVenueRating(entityId)  {
		   UserManager.getEntityRating(entityId, function(entityRating) {
		       if(entityRating) {
				   SNG_selstarEventVenue(entityRating.totalRates, entityRating.ratingUsers);
		       }
		   });
	}
	
	function SNG_selstarEventVenue(totalRates,ratingUsers) {
		var num=0,maxRating =5,curnum = 0,curnumhalf,obj;
		num = ( (ratingUsers==0)? 0 : (totalRates/ratingUsers) );
		num = ((num>maxRating)? maxRating : num );
		cntx = document.getElementById('cntx').value;
		var rImg = cntx+'SNG_images/stars-norating.png';

		var ratingNum = 0;
		for (curnum = 1; curnum <= maxRating; curnum++) {

				if (num >= curnum) {
					ratingNum++;
				}
				else {
					curnumhalf = curnum - 0.51;

					if (num >= curnumhalf) {
						ratingNum++;
					}

				}

			}
		if(ratingNum > 0 ) {
			rImg = cntx+'SNG_images/starsV'+ ratingNum +'.png';
		}
		
		if($("#SNG_starVenue").length > 0 ) {
			$("#SNG_starVenue").attr("src", rImg);
		}
		
	}
	
	var pageIdVal = 0;
	function SNG_showAllComments(id, pageId) {
	   pageIdVal = pageId;
	   UserManager.showUsersComment(id, pageId, SNG_showCommentsHandler);
	}

	function SNG_showCommentsHandler(source) {
	   var all = $('#showAllComments');
	   var commentCount = parseInt($('#userCommentCount').val());
	   if( source == "error" ) 
	      displayErrorMessage("Error processing your request.");	   
	   else   {          
	     all.html(source);  
	     all.show(); 
	     if($('.SNG_edRTitle').css('display', 'none')){
	    	 $('.SNG_edRTitle').show();
	     }
	     $('#showcomments').hide();
			 if(null != _$id('isRegisteration') && $('#isRegisteration').val() == "Yes") 
				 SNG_showCommentArea(false);
			 if( commentCount > 3 )
				 $('#hideComments').html('<a href="#" onclick="SNG_getLayer(\'showcomments\', \'showAllComments\');SNG_changeReviewLink(\'show\'); return false;">Hide review</a>');
	     	if(pageIdVal==1){ // check for showing review in edit mode
	     		var userCommentId = $('#editCommentId').val();
	     		if(userCommentId > 0 ){
	     			SNG_edituserReview(userCommentId, false);
	     		}
	     	}
		 }
	}
	
	/* Method to Bookmark event/venues - START */
	function SNG_bookmark(venueId, titleId, pgId, entityName) {
		UserManager.addUserBookmark(venueId, titleId, pgId, entityName, addUserBookmarkHandler);
		
		function addUserBookmarkHandler(data) {
			if (data == "logout") {
				if ($('#bookmarkMyWozzonId').length > 0) {
				 	showLoginTable('addUserBookMark', _$id('bookmarkMyWozzonId'));
					return;
				}
			} else if (data == 'Yes') {
				if (venueId != 0 && titleId == 0 && pgId == 0) { // Venues
					var popup_msg = 'Your venue has been bookmarked...';
				} else if (venueId == 0 && titleId != 0 && pgId == 0) { // Titles
					var popup_msg = 'Your title has been bookmarked...';
				} else { // Events
					var popup_msg = 'Your event has been bookmarked...';
				}
			} else if (data == 'Exist') {
				if (venueId != 0 && titleId == 0 && pgId == 0) {
					var popup_msg = 'You have already bookmarked this venue.';
				} else if (venueId == 0 && titleId != 0 && pgId == 0) {
					var popup_msg = 'You have already bookmarked this title.';
				} else {
					var popup_msg = 'You have already bookmarked this event.';
				}
			} else {
				if (venueId != 0 && titleId == 0 && pgId == 0) {
					var popup_msg = 'Error while bookmarking venue.';
				} else if (venueId == 0 && titleId != 0 && pgId == 0) {
					var popup_msg = 'Error while bookmarking tilte.';
				} else {
					var popup_msg = 'Error while bookmarking event.';
				}
			}
			SNG_alert(popup_msg,'Success'); 
		}
	}
	
	// To show/hide the Add/show comments Div
	function SNG_getLayer(show, hide) {
		$('#' + show).show();// Show
		$('#' + hide).hide();// Hide
	}
	
	// Highlight stars for rating
	function SNG_selstarRate(num, isVenue) {
		cntx = document.getElementById('cntx');
		if(cntx != null) cntx = cntx.value;
		
		var rImg = null, wImg = cntx+'SNG_images/star_white.png';

		if(isVenue){
			rImg = cntx+'SNG_images/star_green.png';
		}else{
		rImg = cntx+'SNG_images/star_yellow.png';
		}
			var curnum = 0;
			for (curnum = 1; curnum <= 5; curnum++) {
				if (num >= curnum) {
					document.getElementById('star0'+curnum).src = ''+rImg;
				} 
				else {
					curnumhalf = curnum - 0.51;
					if (num >= curnumhalf) {
						document.getElementById('star0'+curnum).src = ''+rImg;
					} 
					else {
						document.getElementById('star0'+curnum).src = ''+wImg;
					}
				}
			}
	}
	
	function SNG_rateIt(rating, isVenue) {
		
	    var obj = _$id('rating');
	    var rateStar = _$id('rateStar');
	    var starHtml='';
	    var message;
	    var messages = ["", "Terrible", "Bad", "Just OK","Good","Excellent"];
		cntx = document.getElementById('cntx');
		if(cntx != null)cntx = cntx.value;
		
	    if(obj) {
	        obj.value = rating;      
	        message = _$id('star0'+rating).title;
	        
			if(isVenue){/* venue */
				for (curnum = 1; curnum <= 5; curnum++) {
					if (rating >= curnum){
						starHtml +='<a href="#" onclick="return SNG_rateIt('+ curnum +', true)">' +
						'<img src="'+cntx+'SNG_images/star_green.png" title="'+messages[curnum]+'" width="16" height="15"  id="star0'+curnum+'" onmouseover="SNG_selstarRate('+curnum+', true);" onmouseout="SNG_selstarRate('+rating+', true);"/> </a>';
					}
					 else{
						starHtml +='<a href="#" onclick="return SNG_rateIt('+ curnum +', true)">' +
						'<img src="'+cntx+'SNG_images/star_white.png" title="'+messages[curnum]+'" width="16" height="15"  id="star0'+curnum+'" onmouseover="SNG_selstarRate('+curnum+', true);" onmouseout="SNG_selstarRate('+rating+', true);"/> </a>';
					 }
				}
			}else{/* incase of title display yello stars */
				for (curnum = 1; curnum <= 5; curnum++) {
					if (rating >= curnum){
						starHtml +='<a href="#" onclick="return SNG_rateIt('+ curnum +')">' +
						'<img src="'+cntx+'SNG_images/star_yellow.png" title="'+messages[curnum]+'" width="16" height="15"  id="star0'+curnum+'" onmouseover="SNG_selstarRate('+curnum+');" onmouseout="SNG_selstarRate('+rating+');"/> </a>';
					}
					 else{
						starHtml +='<a href="#" onclick="return SNG_rateIt('+ curnum +')">' +
						'<img src="'+cntx+'SNG_images/star_white.png" title="'+messages[curnum]+'" width="16" height="15" id="star0'+curnum+'" onmouseover="SNG_selstarRate('+curnum+');" onmouseout="SNG_selstarRate('+rating+');"/> </a>';
					 }
				}
			}
			/* venue */
			
			
	        rateStar.innerHTML = starHtml;
	        _$id('rateMessage').innerHTML = '<span>'+message+'</span>';
	        // _$id('rateMessage').innerHTML = '<span
			// style="padding-left:40px;border:#000066 thin
			// dashed">'+message+'</span>';
	        _$id('rateMessage').style.color='#000000';
	        _$id('canelLink').style.display='';
	        _$id('userComment').focus();
	    }
	    
	    return false;
	}
	
	// Use for refreshing event page after user sign in
	function SNG_refreshEventPage(){
		SNG_refreshImageSection();
		SNG_refreshCommentSection();
	}
	
	function SNG_refreshImageSection(){
		// alert('SNG_refreshImageSection')
	}
	
	function SNG_refreshCommentSection(){}
	
	
	function SNG_hideReviewBoxAlreadyRated(){
		var entityId = 0;
		if($('#titleId').length > 0 && $('#titleId').val() > 0){
			entityId = $('#titleId').val();
		}else if($('#venueId').length > 0 && $('#venueId').val() > 0){
			entityId = $('#venueId').val();
		}
		
		if(entityId > 0 ){
			UserManager.hasAlreadyReviewed(entityId, function(source){
				if(source=='notReviewed'){
					SNG_showCommentArea(true);
				}else if(source=='logout'){
					// $('#commentarea').hide();
				}else if(source=='alreadyReviewed'){
					SNG_showCommentArea(false);
				}
				
			});
		}
	}
	
	function SNG_showCommentArea(isShow){
		if(isShow){
			$('#editUserReviewLink').hide();
			$('#commentarea').show();
			if($('.SNG_cmntsContNoBG').length > 0){
			    	$('.SNG_cmntsContNoBG').addClass('SNG_cmntsCont');
			    	$('.SNG_cmntsContNoBG').removeClass('SNG_cmntsContNoBG');
			}
		}else{
			$('#editUserReviewLink').show();
			$('#commentarea').hide();
		    if($('.SNG_cmntsCont').length > 0){
		    	$('.SNG_cmntsCont').addClass('SNG_cmntsContNoBG');
		    	$('.SNG_cmntsCont').removeClass('SNG_cmntsCont');
		    }
		}
	}
	
	// Event Detail Submit Changes (AJAX)
	function SNG_submitTask(taskId) {
		var description = $('.SNG_taskComments').val();
		description = trim(description)
		if(description.length <=0 || description== ST_CHANGES) {
			SNG_displayLoginError($('.SNG_taskComments'), "Provide values for changes.");
			return false;
		}else{
			var entityId = $('#entityID').val();
			UserManager.submitTask(description, taskId, entityId, SNG_submitTaskHandler);
		}
	}
	
	function SNG_submitTaskHandler(source) {
		
		if(null != source) {
			if(source == "error") {
				SNG_alert("Error processing your request.");
			} else {
				$('#submitChanges').hide();
				$('#successSubmitChanges').show();
				window.setTimeout("SNG_closeFancyBox()", 500);
			}
		}
	}
	
	// Event/Venue Detail add Description (AJAX)
	function SNG_submitDescription(taskId) {
		var description = $('.SNG_taskDescription').val();
		description = trim(description)
		if(description.length <=0) {
			SNG_displayLoginError($('.SNG_taskDescription'), "Provide values for changes.");
			return false;
		}else{
			var entityId = $('#entityID').val();
			UserManager.submitTask(description, taskId, entityId, SNG_submitDescriptionTaskHandler);
		}
	}
	
	function SNG_submitDescriptionTaskHandler(source) {
		
		if(null != source) {
			if(source == "error") {
				SNG_alert("Error processing your request.");
			} else {
				$('#addDescription').hide();
				$('#successAddDescription').show();
				window.setTimeout("SNG_closeFancyBox()", 500);
			}
		}
	}

	
	function SNG_closeFancyBox(){
		$('#fancybox-close').click();
	}
	// End
	
	function SNG_sendFriendsEmail(){
		
		var venueId = $('#venueId').val();
		var titleId = $('#titleId').val();
		var isSelf = $('#self').is(':checked');
		var formUserName = $('#userName').val();
		if(formUserName == EF_MYNAME){
			formUserName= '';
		}
		var friendsEmail = $('#friendsEmail').val();
		var userEmail = $('#userEmail').val();
		var formMessage = $('#message').val();
		var gdpMessage = $('.subject').html();
		gdpMessage  = trim(gdpMessage);
		if(SNG_validateEmailToFriends(userEmail, friendsEmail, formMessage)){
			UserManager.sendEventEmail(venueId, titleId, isSelf, formUserName, friendsEmail, userEmail,
					formMessage, gdpMessage, SNG_sendFriendsEmailHandler);
		}
	}
	
	function SNG_sendFriendsEmailHandler(source){
		
		if(source == ""){
			$('.SNG_emailFriends').hide();
			$('.SNG_successEmailFriends').show();
			window.setTimeout("SNG_closeFancyBox()", 500);
		}else{
			SNG_alert(source);
		}
	}

	function SNG_validateEmailToFriends(userEmail, friEmails, msg){
		 
		
		 if ( friEmails == EF_FRIENDSEMAIl ) 
		     friEmails = '';
		 
		 if ( userEmail == EF_MYEMAIL ) 
			 userEmail = '';
		 
		 if ( msg == EF_COMMENTS ) 
			 msg = '';
		 
		 if(friEmails.length==0 ){
			    SNG_displayLoginError($('#friendsEmail'), "Please enter atleast one email address.");
			    return false;			
		 }
		 else {
			   var emails = friEmails.split(',');
			   var i;
			   for(i=0;i<emails.length;i=i+1){
				   if(!checkEmail(trim(emails[i]))){
					   SNG_displayLoginError($('#friendsEmail'), "Please enter a valid email address.");
					   return false;
				  }
			   }		   			
		   }
		   
		   if( userEmail.length==0 ){
			    SNG_displayLoginError($('#userEmail'), "Please enter My Email address.");
				return false;			
		   } else if(!checkEmail(userEmail)) {
			   SNG_displayLoginError($('#userEmail'), "My Email address is not valid.");
			   return false;
		   } else {
		      msg = trim(msg);
		      if( msg.length ==0){
		    	   SNG_displayLoginError($('#message'), "Please enter add your comments.");
				   return false;
			  }
		      
		      return true; 
		   }
		  
	}
	
	
	function SNG_resizeFancyBox(){
		$.fancybox.resize();
	}
	
	function SNG_closeFancyBox(){
		$.fancybox.close();
	}

	function SNG_showSubmitChanges(value) {
		if (value == 1) {
			$('.submitChangesEdit').click();
			$('#successSubmitChanges').hide();
			$('#taskComments').val('');
		} else if (value == 2) {
			_$id('submitChanges').style.display = 'none';
		}
	}
	
	function SNG_showSubmitDescription(value) {
		if (value == 1) {
			$('#addDescriptionLink').click();
			$('#successAddDescription').hide();
			$('#taskDescription').val('');
		} else if (value == 2) {
			_$id('addDescription').style.display = 'none';
		}
	}
	
	function SNG_newAlert(message){
		$('.SNG_innerPopup span').html(message);
		$('a#anchorAlertPopup').click();
	}
	
	function SNG_reportUnsuitable(){
		
		var hlink = window.location.href;
		var qrStr = hlink.substr(0, hlink.indexOf('?'));
		
		hlink = qrStr + "?"  + getValue('eventURL'); // + "venueId="
														// +venueId+"&titleId="
														// + titleId;
        hlink = escape(hlink);
		
		var subject = "Report Unsuitable Information on Wozzon";
		var email = "feedback@wozzon.com" ;
		var body = "I would like to report Unsuitable information on Wozzon.com: " ;
		var message = " %0DType here any comments:%0D";	
		var comp ="mailto:"+email+"?subject="+subject+"&body="+ body + hlink+message;
		
		win = window.open(comp,'emailWindow');
		if (win && win.open &&!win.closed) win.close();
		
	}
	
	function SNG_writeCertificateText(text){
		$('p.SNG_certificate').addClass('SNG_certificateNF');
		$('p.SNG_certificate').html(text);
	}
	
	
	function SNG_writeCertImgTitle(text, thisObj){
		if(text == 'U'){
			thisObj.title = CERT_TITLE_U;	
		}else if(text == 'PG'){
			thisObj.title = CERT_TITLE_PG;	
		}else if(text == '12A'){
			thisObj.title = CERT_TITLE_12A;	
		}else if(text == '15'){
			thisObj.title = CERT_TITLE_15;	
		}else if(text == '18'){
			thisObj.title = CERT_TITLE_18;	
		}else{
			thisObj.title = text;
		}
		 
	}
	
	function getIndexOfRadiusArray(val){
		val = Math.abs(val);
		for(count =0 ; count  < distanceValueArr.length; count++){
			if(distanceValueArr[count] == val){
				return count;
			} 
		}
		return 0;
	}
	
	function SNG_loginAjax(id) {
		var emailId = "";
		var password = "";
		var isRemember = "";
		if(id == '1') {
			document.getElementById('login_form').identity.value = '1';
			emailId = trim($('#login_email').val());
			password = trim($('#login_password').val());
			if(document.getElementById('login_form').chk_rememberMe.checked)
				isRemember = "Y";
		} 
		
		if(password == SIN_PASSWORD){
			// $('#login_password').val('');
			password = '';
		}
		if(emailId == SIN_EMAIL){
			emailId = '';
			// $('#login_email').val('');
		}
		
		var emailCorrect = false;
		if((emailCorrect= checkEmail(emailId)) && password != "" ){
			 setCookie("login_source", "whitelabel", 1);
			 if(userFromLink!='Linked')
				 userFromLink = 'Login';
			 UserManager.login(emailId,password,isRemember, SNG_checkLoginHandler);
		}else{ 
			if(id == '1') {
				if(!emailCorrect || emailId==''){
					// $('#login_email').val(emailId);
					// $('#login_password').val(password);
					SNG_displayLoginError($('#login_email'), 'Please enter your email address');
				}else if(password==''){
					SNG_displayLoginError($('#login_password'), 'Please enter password');
					$('#login_password_text').focus();
				}
				// document.getElementById('loginError').style.display = '';
				// document.getElementById('loginError').innerHTML = "The email
				// address or password you provided does not match our
				// records.";
			}	
		}
		
	}
	
	function SNG_signUpStep1(){
		var emailId = trim($('#signup_email1').val());
		var postCode = trim($('#signup_postcode1').val());		
		var termsChecked = $('input[name=termsAndConditions]', '#registration_form').is(':checked');		
		if(emailId == SIN_EMAIL){
			emailId = '';
		}
		if(postCode == SUP_POSTCODE){
			postCode = '';
		}
		
		if(emailId == ''){
			SNG_displayLoginError($('#signup_email1'), 'Please enter your email address to Sign Up');
		}else if(!(emailCorrect = checkEmail(emailId))){
			SNG_displayLoginError($('#signup_email1'), 'Please enter a valid email address');
		}else if(postCode == ''){
			SNG_displayLoginError($('#signup_postcode1'), 'Please enter your postcode');
		}else if(!validatePostCode(postCode)){
			SNG_displayLoginError($('#signup_postcode1'), 'Please enter a valid postcode');
		}else if(!termsChecked){
			SNG_displayLoginError($('#termsAndConditions'), 'Please accept the woZZon Terms & Conditions');
		}else{
			UserManager.checkAccountStatus(emailId, function(source){
				if(source == 'exists'){
					SNG_displayLoginError($('#signup_email1'), 'There is already an account associated with this email');
					$('#login_email').val($('#signup_email1').val()).focus();
				}else if(source=='not_exists' || source=='deleted'){
										
					if( $('#whichLink').val() == "earnByAddEvents" ) {
						$('#signInUpPopup').hide();										 
						 SNG_loadContainer("SNG_loadContainerVEPBindings();", "venue_event_pro");
					} else {
						$('#signInUpPopup').hide();
						$('#signUpPopup').show();
						SNG_displayLoginSuccess($('#signup_email'));
						$('#signup_email').val(emailId).removeClass().addClass('popupTextFieldOK');
						SNG_displayLoginSuccess($('#signup_postcode'));
						$('#signup_postcode').val(postCode).removeClass().addClass('popupTextFieldOK');
						SNG_resizeFancyBox();
					}
					
				}
			});
		}
		
		// $('#signup_email').val(emailId);
		// $('#signup_postcode').val(postCode);
	}
	function SNG_hideClearAllErrors(){
		$('.popupErrorMsgCont').hide().find('.popupErrorMessage').val('');
		$('.popupErrorMsgContUN').hide().find('.popupErrorMessageUN').val('');
		$('.popupErrorMsgContVEP').hide().find('.popupErrorMessageVEP').text('');
		SNG_resizeFancyBox();
	}
	
	function SNG_hideLoginError(sibSource){
		var obj = $('+ .popupErrorMsgCont', sibSource).hide();
		obj.find('.popupErrorMessage').val('');
		obj.find('img').attr('src', GLOBAL_CNTX_PATH + 'SNG_images/icons/error-popup.png');
		SNG_resizeFancyBox();
	}
	
	function SNG_displayLoginError(sibSource, message){
		$('.popupErrorMsgCont').hide().find('.popupErrorMessage').val('');
		var obj = $('+ .popupErrorMsgCont', sibSource).show();
		obj.find('.popupErrorMessage').html(message);
		obj.find('img').attr('src', GLOBAL_CNTX_PATH + 'SNG_images/icons/error-popup.png');
		// sibSource.removeClass().addClass('popupTextFieldError')
		SNG_resizeFancyBox();
		if(sibSource.focus) sibSource.focus();
	}
	
	function SNG_displayLoginError2(errorId, message){
		$('.popupErrorMsgCont').hide().find('.popupErrorMessage').val('');
		var obj = $('#' + errorId).show();
		obj.find('.popupErrorMessage').html(message);
		obj.find('img').attr('src', GLOBAL_CNTX_PATH + 'SNG_images/icons/error-popup.png');
		SNG_resizeFancyBox();
		sibSource.focus();
	}
	
	function SNG_displayLoginSuccess(sibSource, message, hideOthers){
		if(hideOthers){
			$('.popupErrorMsgCont').hide().find('.popupErrorMessage').val('');
		}
		if(message == undefined){
			message = '';
		}
		var obj = $('+ .popupErrorMsgCont', sibSource).show();
		obj.find('.popupErrorMessage').html(message);
		obj.find('img').attr('src', GLOBAL_CNTX_PATH + 'SNG_images/icons/tick-popup-small.png');
		SNG_resizeFancyBox();
	}
	
	
	function SNG_checkLoginHandler(source) {
		
		var cntx = document.getElementById('cntx');
		if(cntx == null) cntx = "";
		else cntx = cntx.value;
				
		  if( source == "error" ) 
			SNG_alert("Error processing your request.");
		  else if( source == "Inactive")   
			  SNG_alert("Please activate your account");   
		  else if( source == "Invalid_ID") {
			 $('#login_password').val('');
			 SNG_passwordOnBlur(_$id('login_password'));
			 $('#signup_email1').val($('#login_email').val());
	    	 SNG_displayLoginError($('#login_email'), 'Email address not recognised, would you like to Sign Up instead?');
	      }else if( source == "Invalid_PSWD") {
	    	  var fieldSource = $('#login_password');
	    	  fieldSource.val('');
			  SNG_displayLoginError(fieldSource, 'The password you have entered is incorrect');
	      }else {  
			// hideDivs('tbl_login');
			// hideDivs('tbl_existing_account');
	    	if(userFromLink != 'Linked' && userFromLink!=''){
	    		SNG_closeFancyBox();
	    	}else if(userFromLink == 'Linked'){
	    		hideAllSignInUPPops();
				$('#fbLinkSuccess').show();
				SNG_resizeFancyBox();
	    	}
	    	
	    	
			if(_$id('login_form').identity.value == '1')  { 
			   checkRemember('login_form');
	 	    } 
			if(_$id('tbl_addCommentLogin') != null) 
				 hideDivs('tbl_addCommentLogin');
			
			// check user sync account for display sync banner.
			checkUserSyncAccount();
			
			// call to jQuery function, this will be used to perform tasks
			// require after a user sign in
			// SNG_callAfterSignin();
			
			if(_$id('welcomenote')&& source != 'UserLogged') {
				
				source =  "Welcome:  <span><a href='"+ cntx + "controller.web?method=myWozzon'>" + source +  '</a></span><span class="SNG_welcomepadding"></span>' + $("#welcomenote").html(); 
				$("#welcomenote").html(  source); 			
				$('#wozzon_header_facebook').hide();
				$('#wozzon_header_signup').hide();
				$('#isUserLogged').val('Yes');
			} 
			
			if(_$id('commentarea')){
				SNG_hideReviewBoxAlreadyRated();
			}
			if($("#wozzon_header_logStatus"))  {
				
				$("#wozzon_header_myWozzonStatus").html("<a id='id_myWozzon' href='" + cntx + "controller.web?method=myWozzon'>My woZZon</a>");
				$("#wozzon_header_logStatus").html('<a href="javascript:logout(1)">Sign out</a>');
			}
			if(_$id("h_addEventLink") != null){
				
				_$id("h_addEventLink").innerHTML = "<a href='"+cntx+"controller.web?method=addVenueEvent'><img height='101' width='124' alt='Add your event or venues' src='"+cntx+"images/add_block3.jpg'/></a>";
			}
			if(_$id("london_addEventLink") != null){
				_$id("london_addEventLink").innerHTML = "<a href='"+cntx+"controller.web?method=addVenueEvent'>Add your own<br /> venue or event</a>";
			}
			if( _$id('upload_link')){
				if(_$id('isUserLogged')) _$id('isUserLogged').value ='Yes';
			}
			
			var isreviewEvent = _$id('isReviewEvent')
			if(_$id('isReview') && _$id('isReview').value == "Yes") {
					SNG_closeFancyBox();
				  document.getElementById('isReview').value == "No"	;
				  if(document.getElementById('venueId') != null) 
				      addReviewForVenue(document.getElementById('venueId').value);  
			} else if(isreviewEvent && isreviewEvent.value == "Yes") {
					SNG_closeFancyBox();
	       			 isreviewEvent.value == "No"	;       			
	       			if(_$id('titleId') != null)  {
					  var titleId = _$id('titleId').value;
					  var venueId = _$id('venueId').value;			
					  SNG_addCommentEvent(titleId, venueId);  
				   }
				}
				
			if(_$id('whichLink').value == "showSubmitChanges"){
				// to take user direct to edit the venue if the same venue is
				// owned by him, otherwise just submit changes.
				if(null != _$id('VenueNickName') && trim(_$id('VenueNickName').value).length > 0)  { 
					var nName = _$id('VenueNickName').value;
					if((source).indexOf(nName)!=-1 ) editThisVenue();
				}
				if($('#isUserLogged').val()=='Yes'){
					SNG_closeFancyBox();
					window.setTimeout('SNG_showSubmitChanges(1)', 500); // displaying
																		// box
																		// to
																		// submit
																		// changes.
				}else{
					SNG_closeFancyBox();
					SNG_showSubmitChanges(1);
				}
			}else if(_$id('whichLink').value == "showSubmitDescription"){
				
				if($('#isUserLogged').val()=='Yes'){
					SNG_closeFancyBox();
					window.setTimeout('SNG_showSubmitDescription(1)', 500); // displaying
																			// box
																			// to
																			// submit
																			// changes.
				}else{
					SNG_closeFancyBox();
					SNG_showSubmitDescription(1);
				}
			}
			else if(_$id('whichLink').value == "AddEvent" || _$id('whichLink').value == "AddEventOnMap" || _$id('whichLink').value == 'addEventLink') {
				var cntx = document.getElementById('cntx');
				if(cntx == null) cntx = "";
				else cntx = cntx.value;
				window.location = cntx+"controller.web?method=addVenueEvent";
			} else if(_$id('whichLink').value == "AddEventforVenue" && document.forms.w_venue) {
	          		document.forms.w_venue.submit();
			}else if(_$id('whichLink').value == "signup_promo"){
				var cntx = document.getElementById('cntx');
				if(cntx == null) cntx = "";
				else cntx = cntx.value;
				window.location = cntx+"controller.web?method=home";
			}else if(_$id('whichLink').value == "MyWozzon") {
				var cntx = document.getElementById('cntx');
				if(cntx == null) cntx = "";
				else cntx = cntx.value;
				window.location = cntx+"controller.web?method=myWozzon";
			} else if(_$id('whichLink').value == "AddEventRight" ) {
				var cntx = document.getElementById('cntx');
				if(cntx == null) cntx = "";
				else cntx = cntx.value;
				window.location = cntx+"controller.web?method=addVenueEvent";
			 } else if(_$id('whichLink').value == "addUserBookMark" ) {
				SNG_closeFancyBox();
			 	var venueId = document.getElementById('_venueId').value;
			 	var titleId = document.getElementById('_titleId').value;
			 	var pgId = document.getElementById('_pgId').value;
			 	var entityName = document.getElementById('_entityName').value;
		 		bookmark(venueId, titleId, pgId, entityName);
			 }else if(_$id('whichLink').value == "RateEntity" ) {
				SNG_closeFancyBox();
			 	doFocus();
			 }else if(_$id('whichLink').value == "AddRateEntity" ) {
				SNG_closeFancyBox();
			 	doFocus();
			 }else if(_$id('whichLink').value == "show_upload_img" ){
				 // SNG_showUploadDlg();
				 SNG_closeFancyBox();
				 window.setTimeout("SNG_uploadImage('New')", 500);
			 }else if(_$id('whichLink').value == "earnByReviewReg"){
				isEarnPoundReviewer();
			 }else if(_$id('whichLink').value == "earnByReviewReg_home"){
				 populateFLName();
				 registerEarnPound();
			 }else if(_$id('whichLink').value == "earnByAddEvents"){				 
				 SNG_loadContainerVEP();
			 }
			
			// SNG_closeFancyBox();
			
		  }	
		  
		  
	}
	
	var user_nickName ="";
	function SNG_registerNowAjax(id, promotionalReg) {
		var emailId = "";
		var nickName = "";
		var regPassword = "";
		var postCode = "";
		var retypePass = "";
		
		var div = "";
		if(id == '1' ) {
			div = "registerationError" ;
			var regForm = $('#registration_form');
			regForm.find('#identity').val('1');
			emailId = trim($('#signup_email').val());
			postCode = trim($('#signup_postcode').val());
			nickName = trim($('#signup_nickname').val());
			regPassword = trim($('#signup_password').val());
			retypePass = trim($('#signup_conf_password').val());
			
		}
		
		if(emailId == SIN_EMAIL) emailId = "";
		if(postCode == SUP_POSTCODE) postCode = "";
		if(nickName == SUP_NICKNAME) nickName = "";
		if(regPassword == SIN_PASSWORD) regPassword = "";
		if(retypePass == SUP_CONF_PASSWORD) retypePass = "";
		
		if(emailId == ''){
			SNG_displayLoginError($('#signup_email'), 'Please enter your email address');
		}else if(!(emailCorrect = checkEmail(emailId))){
			SNG_displayLoginError($('#signup_email'), 'Please enter a valid email address');
		}else if(postCode == ''){
			SNG_displayLoginError($('#signup_postcode'), 'Please enter your postcode');
		}else if(!validatePostCode(postCode)){
			SNG_displayLoginError($('#signup_postcode'), 'Please enter a valid postcode');
		}else if(nickName == ""){
			SNG_displayLoginError($('#signup_nickname'), 'Please enter a Nickname');
		}else if(SNG_checkNickname(nickName)){
			SNG_displayLoginError($('#signup_nickname'), NICK_NAME_INVALID_CHAR);
		}else if(regPassword == ""){
			SNG_displayLoginError($('#signup_password'), 'Please enter a password');
			$('#signup_password_text').focus();
		}else if(regPassword.length <5 ){
			$('#signup_password').val('');
			$('#signup_conf_password').val('');
			SNG_passwordOnBlur(_$id('signup_conf_password'));
			SNG_displayLoginError($('#signup_password'), 'Password must be at least 5 characters long');
		}else if(regPassword != retypePass){
			$('#signup_password').val('');
			$('#signup_conf_password').val('');
			SNG_passwordOnBlur(_$id('signup_conf_password'));
			SNG_displayLoginError($('#signup_password'), 'The passwords you entered do not match');
		}else{
			var isRemember = "N";
			var remFlag = false;

			var reg_form_chkbox = $('#signup_chk_rememberMe');
			
			if(reg_form_chkbox.length > 0 && reg_form_chkbox.is(':checked'))
				isRemember = "Y";
			
			var productServicesChkBox = $('#productServices');
			
			if(promotionalReg != null && productServicesChkBox.length> 0 && productServicesChkBox.is(':checked')){
			remFlag = true;
			}else{remFlag = false;}
			var regPg = document.getElementById('reg_page');
			if(regPg != null){
				regPg = regPg.value;
			}else{
				regPg='wozzon/default'
			}
			
			UserManager.register(remFlag, emailId, postCode, nickName, regPassword, isRemember, regPg, SNG_registerationHandler);
			
			user_nickName = nickName;
		}
	}
	
	function SNG_registerationHandler(source) {
		var obj = _$id("registerationError");
		var div = "";
		div = "registerationError";	
		showDivs(div);	
		if( source == "1" ) SNG_displayLoginError($('#signup_email'), 'There is already a user associated with this email address');
		else if(source == "2")   SNG_displayLoginError($('#signup_nickname'), 'Nickname already in use, please enter another Nickname');
		else if( source == "3") SNG_displayLoginError($('#signInUpErrorDiv').show(), 'Error while registering');
		else if(source == "4")	SNG_displayLoginError($('#signup_nickname'), 'Please enter a Nickname');
	    else if(source == "5" ) SNG_displayLoginError($('#signup_password'), 'Please enter a password');
	    else if(source == "6" )SNG_displayLoginError($('#signup_email'), 'Please enter your email address');
	    else if(source == "11" ) SNG_displayLoginError($('#signup_postcode'), 'Please enter your postcode');

	    else if(source == "Registered" || source == "ReRegistered")  {		
				
				// checkRemember('registration_form'); // if remmeber me checked
				// save username
				 // var productServicesChkBox = _$id('productServices');
				// if comming from comptetion registeration page
	 	 		
				   // removeUserInfo() ;
				   var submitForm = document.getElementById('compete_form');
				   if(submitForm != null){
					   checkRemember('registration_form'); // if remmeber me
															// checked save
															// username
					   submitForm.submit();
					   return ;
				   }
					
		  		
		  	// hideDivs('tbl_registration');
			checkRemember('signUpForm'); // if remmeber me checked save
											// username
			var isreviewEvent = _$id('isReviewEvent')
			var isreview =_$id('isReview')
					
			if( !( (isreview && isreview.value == "Yes") ||  (isreviewEvent && isreviewEvent.value == "Yes") || 
						  ( _$id('whichLink').value == "showSubmitChanges" ) )  ) {		
			   
				hideAllSignInUPPops();
				$('.successUserNickname').html($('#signup_nickname').val());
				$('#signUpSuccess').show();
				SNG_resizeFancyBox();
			}
			SNG_checkLoginHandler(user_nickName);
		 } else  {          
		  	obj.innerHTML = source;
		}
	}
	
	function SNG_checkNickname(nickName){
		if(nickName.indexOf('_') > -1){
			return true;
		}
		
		return false;
	}
	function hideAllSignInUPPops(){
		$('#signInUpPopup').hide();
		$('#signUpPopup').hide();
		$('#fbSignUpPopup').hide();
		$('#signUpSuccess').hide();
		$('#fbLinkSuccess').hide();
		// $('#signInUpProcess').hide();
	}
	
	function SNG_passwordOnBlur(obj){
		var objId = obj.id;
		var hideThis = false;
		if(trim(obj.value)==''){
			hideThis = true;
		}
		
		if(hideThis){
			var textObj = '';
			if(obj.id=='reset_password' || obj.id=='reset_re_password'){
				$('.SNG_messagePopup input[id="' + objId + '"]').hide();
				textObj = $('.SNG_messagePopup input[id="'+ objId +'_text"]');
			}else{
				$('#' + objId).hide();			
				textObj = $('#'+ objId +'_text');
			}
			
			
			textObj.addClass('popupTextFieldBefore');
			textObj.removeClass('popupTextField');
			textObj.show();	
		}
		
	}
	
	function SNG_alert(message, topic){
		if($('.SNG_alertPopup:visible').length > 0 ){
			SNG_closeAlert();
		}
		if(topic==undefined){
			topic = 'Oops!';
		}
		
		var alertCont = "<div id='fancyalertbox-wrap' class='SNG_alertPopup' style='width: 490px; height: 175px;'>";
		alertCont +="<div id='fancyalertbox-outer'><div id='fancyalert-bg-n' class='fancyalert-bg'></div>";
		alertCont +="<div id='fancyalert-bg-ne' class='fancyalert-bg'></div>";
		alertCont +="<div id='fancyalert-bg-e' class='fancyalert-bg'></div>";
		alertCont +="<div id='fancyalert-bg-se' class='fancyalert-bg'></div>";
		alertCont +="<div id='fancyalert-bg-s' class='fancyalert-bg'></div>";
		alertCont +="<div id='fancyalert-bg-sw' class='fancyalert-bg'></div>";
		alertCont +="<div id='fancyalert-bg-w' class='fancyalert-bg'></div>";
		alertCont +="<div id='fancyalert-bg-nw' class='fancyalert-bg'></div>";
		alertCont +="<div id='fancyalertbox-inner' class='SNG_alertPopup-inner'  style='width: 470px; height: 155px;'>";
		alertCont +="<div class='SNG_chageLocationPopup'>";
		alertCont +="<div class='SNG_chageLocationPopupTop'><h1 class='alertHead'>" + topic + "</h1></div>";/*
																											 * Header
																											 * Content
																											 */
		alertCont +='<div class="popupFormContent" style="background: none;" ><p class="SNG_RPPassText">' + message + '</p>';/*
																																 * Center
																																 * Content
																																 */
		alertCont +='<a href="javascript:SNG_closeAlert();" style="">';
		alertCont +='<img border="0" alt="Close" src="' + GLOBAL_CNTX_PATH + 'SNG_images/btn-popup-close.png"></a></div></div></div>';
		alertCont +="<a id='fancyalertbox-close' href='javascript:SNG_closeAlert();' style='display: inline;'></a>";
		alertCont +="</div></div>";
		$(document.body).append( alertCont);
		x = getScrollWidth();
		y = getScrollHeight();
		$('.SNG_alertPopup').show();
		var newHeight = $('.SNG_alertPopup-inner .SNG_chageLocationPopup').height();
		var newWidth = $('.SNG_alertPopup-inner .SNG_chageLocationPopup').width();
		$('.SNG_alertPopup-inner').height(newHeight).width(newWidth);
		$('.SNG_alertPopup').height(newHeight+20).width(newWidth+20).css('left', x + 350 + 'px').css('top',  y + 250  + 'px');

	}
	
	 function SNG_closeAlert(){
		 $('.SNG_alertPopup').empty().remove();
	 }
	 
	 function SNG_closeMessage(){
		 $('.SNG_messagePopup').empty().remove();
	 }
	 

	 function SNG_resetCheckBoxes(divId){
		 $('#' + divId+' input[type="checkbox"]').each(function(){
			 var chkId = $(this).attr('id');
			 var chkImg = $('#' + chkId + '_img');
			 var srcStr = '';
	         var isChecked = $(this).is(':checked');
	         
	         if(isChecked){
	        	 srcStr = GLOBAL_CNTX_PATH + "SNG_images/icons/checkBox_tick.png";
	         }else{
	        	 srcStr = GLOBAL_CNTX_PATH + "SNG_images/icons/checkBox.png";
	         }
	         
	         chkImg.attr("src", srcStr);
		 });
		 
	 }
	 
	 function SNG_messagePopup(divId){
			
			var alertCont = "<div id='fancyalertbox-wrap' class='SNG_messagePopup' style='width: 490px; height: 175px;'>";
			alertCont +="<div id='fancyalertbox-outer'><div id='fancyalert-bg-n' class='fancyalert-bg'></div>";
			alertCont +="<div id='fancyalert-bg-ne' class='fancyalert-bg'></div>";
			alertCont +="<div id='fancyalert-bg-e' class='fancyalert-bg'></div>";
			alertCont +="<div id='fancyalert-bg-se' class='fancyalert-bg'></div>";
			alertCont +="<div id='fancyalert-bg-s' class='fancyalert-bg'></div>";
			alertCont +="<div id='fancyalert-bg-sw' class='fancyalert-bg'></div>";
			alertCont +="<div id='fancyalert-bg-w' class='fancyalert-bg'></div>";
			alertCont +="<div id='fancyalert-bg-nw' class='fancyalert-bg'></div>";
			alertCont +="<div id='fancyalertbox-inner' class='SNG_messagePopup-inner' style='width: 470px; height: 155px;'>";
			
			alertCont += $('#' + divId ).html(); // Center content of that
													// div is added to this
													// popup.
			
			alertCont +="</div><a id='fancyalertbox-close' href='javascript:SNG_closeMessage();' style='display: inline;'></a></div></div>";
			$(document.body).append( alertCont);
			x = getScrollWidth();
			y = getScrollHeight();
			$('.SNG_messagePopup').show();
			SNG_resizeMessagePopup();
			$('.SNG_messagePopup').css('left', x + 350 + 'px'); 
			$('.SNG_messagePopup').css('top',  y + 250  + 'px');

	}
	 
	function SNG_resizeMessagePopup(){
		var newHeight = $('.SNG_messagePopup .SNG_chageLocationPopup').height();
		var newWidth = $('.SNG_messagePopup .SNG_chageLocationPopup').width();
		$('.SNG_messagePopup-inner').height(newHeight).width(newWidth);
		$('.SNG_messagePopup').height(newHeight+20).width(newWidth+20);	
	}
	 
	 function SNG_resetPassAjax(id) {
		var emailId = "";
		var emailObj = $('.SNG_messagePopup input[id="resetPassword_email"]');
		 if ( id == '1') {
			 $('.SNG_messagePopup input[id="resetPassword_identity"]').val('1');
	 		 emailId = emailObj.val();
		 } 
		 if(emailId == RP_EMAIL){
			 emailId = ''; 
		 }
		 
		 if(checkEmail(emailId)) {
			UserManager.resetPassword(emailId, SNG_resetPasswordHandler);	 
		 } else {
			 if(emailId == ''){
			 	SNG_displayLoginError(emailObj,'Please enter your email address')
			 }else{
				 SNG_displayLoginError(emailObj,'Please enter a valid email address')
			 } 
		 }
	}
	function SNG_resetPasswordHandler(source) {
		  if( source == "error" )
			  SNG_alert("Error processing your request.");	
		  else if(source == "Unmatched")  {
			  SNG_alert("The entered email address does not match our records. Please re-enter your email address");
		  }else if( source == "EmailSent") {
			SNG_closeFancyBox();
	    	SNG_closeMessage();
	    	SNG_messagePopup('resetPasswordEmailSent');
		  }
		  else   {          
			  SNG_alert(source);
	      }
	}
	
	function SNG_doResetPassAjax(){
		
		var resetPass = $('.SNG_messagePopup input[id="reset_password"]');
		var confResetPass = $('.SNG_messagePopup input[id="reset_re_password"]');
		if(resetPass.val()==SIN_PASSWORD ){
			resetPass.val('');
		}
		
		if(confResetPass.val() == SUP_CONF_PASSWORD){
			confResetPass.val('');
		}
		
		if(resetPass.val() == ''){
			SNG_displayLoginError(resetPass, 'Please enter password');
		}else if(confResetPass.val() == ''){
			SNG_displayLoginError(confResetPass, 'Please enter confirm password');
		}
		if(resetPass.val().length <=4 ||
				(resetPass.val() != confResetPass.val() )){
			
			if(resetPass.val().length <=4 ){
				SNG_displayLoginError(resetPass, 'The password must be at least 5 characters long')
			}else if(resetPass.val() != confResetPass.val() ){
				SNG_displayLoginError(resetPass, 'The entered passwords do not match.')		
			}
		}else{
			var newPassword = resetPass.val();
			var resetToken = $('.SNG_messagePopup input[id="resetPasstoken"]').val();
		 	UserManager.doResetPass(newPassword, resetToken, SNG_doResetPassHandler);
		}
	}
	
	function SNG_doResetPassHandler(source) {
		var pass = $('.SNG_messagePopup input[id="reset_password"]').val();
		SNG_closeMessage();

		if( source == "error" )
			SNG_alert("Error processing your request.");	
		else if(source.indexOf("@") > 0) {
			SNG_messagePopup('resetPasswordSuccess');
			$('#login_email').val(source);
			$('#login_password').val(pass);
			SNG_loginAjax('1');
		} else if(source == "already_activated") {
			SNG_messagePopup('resetPasswordAlreadyReset');
	    }else{
	    	SNG_alert(source);
	    }
	}
	
	
	/*
	 * This focus & blur function are used, because these element are created at
	 * runtime, so jquery focus/blur wont work
	 */
	function SNG_textFocus(obj){
		if(obj.id == 'resetPassword_email' && trim(obj.value) == RP_EMAIL){
			obj.value = '';
		}else if(obj.id == 'reset_password_text' ){
			$('.SNG_messagePopup input[id="' + obj.id + '"]').hide();
			$('.SNG_messagePopup input[id="reset_password"]').show().focus();
		}else if(obj.id == 'reset_re_password_text' ){
			$('.SNG_messagePopup input[id="' + obj.id + '"]').hide();
			$('.SNG_messagePopup input[id="reset_re_password"]').show().focus();
		}
		obj.className = 'popupTextField';
	}
	
	function SNG_textBlur(obj){
		if(obj.id == 'resetPassword_email' && trim(obj.value) == ''){
			obj.value = RP_EMAIL;
		}
		
		obj.className = 'popupTextFieldBefore';
	}
	
	function SNG_uploadImage(sourceName){
		$('#imageUploadingSource').val(sourceName);
		$('#imageUploadingLink').click();	
	}
	
	function hideAllImageUploadingDivs(){
		var closeSource = '';
		

		
		if($('#div_upload').is(':visible')){
			$('#div_upload').hide();
			closeSource = 'Upload';
		}else if($('#div_crop').is(':visible')){
			$('#div_crop').hide();
			closeSource = 'Crop';
		}else if($('#div_delete_pic').is(':visible')){
			$('#div_delete_pic').hide();
			closeSource = 'Delete';
		}else if($('#div_report_pic').is(':visible')){
			$('#div_report_pic').hide();
			closeSource = 'Report';
		}else if($('#div_confirm_report').is(':visible')){
			$('#div_confirm_report').hide();
			closeSource = 'CReport';
		}
		
		if($('#imageUploadProcess').is(':visible')){
			$('#imageUploadProcess').hide();
		}
		
		return closeSource;
	}
	
	function SNG_checkLength(countMe) {
        
        var escapedStr = encodeURI(countMe)
        if (escapedStr.indexOf("%") != -1) {
            var count = escapedStr.split("%").length - 1
            if (count == 0) count++  // perverse case; can't happen with real
										// UTF-8
            var tmp = escapedStr.length - (count * 3)
            count = count + tmp
        } else {
            count = escapedStr.length
        }
        // alert(escapedStr + ": size is " + count)
        return count;
     }

	function SNG_takeLocation(){
		if($('a#takeLocationLink').length > 0){
			$('a#takeLocationLink').fancybox({
				'hideOnContentClick' : false,
				'hideOnOverlayClick': false,
				'padding'			: 0,
				'overlayOpacity'	: 0.7,
				'overlayColor'		: '#666',
				'autoDimensions' 	: false,
				'height'			: 408,
				'width'				: 590,
				'onStart'			:function(){
					$('.SNG_homePopup').show();
					}	,
				'onClosed'			:function(){
						$('.SNG_homePopup').hide();
					}
					
			});
			$('#takeLocationLink').click();
		}
		
		
	}
	
	function SNG_nearBySearchMethods(venueId, lat, lon) {
		UserManager.nearBySearch(venueId,lat,lon, function(source) {
			if( source != 'error'){
				$('#nearBySearch').html(source);
				SNG_nearByUIMethods();
			}
		});
	
	}
	
	function SNG_nearMeSearchMethods(lat, lon) {
		UserManager.nearMeSearch(lat,lon, function(source) {
			if( source != 'error'){
				$('#nearMeSearch').html(source);
				SNG_nearByUIMethods();
				
			}
		});
	
	}
	
	function SNG_nearByUIMethods(){
		$('#accordion li a').mouseover(function() {
				if($(this).hasClass('firstElement')){
					$('.SNG_alsoShowingAt').css("background-color", "#FF0B32");
				}
				$(this).addClass('ASActive');
				$(this).find('p').show();
				return false;
		});

		$('#accordion li a').mouseout(function() {
				if($(this).hasClass('firstElement')){
					$('.SNG_alsoShowingAt').css("background-color", "#FFFFFF");
				}
				$(this).removeClass('ASActive');
				$(this).find('p').hide();
				return false;
		});		
	}	
	
	function SNG_alsoShowingMethods(titleId, venueId){
		UserManager.alsoShowingAt(titleId, venueId, function(source) {
			if( source != 'error'){
				$('#alsoShowingAt').html(source);
				if($("#alsoShowingAppearingAt").length > 0){
					SNG_alsoShowingUIMethods();
				}
			}
		});
	}
	
	function SNG_alsoShowingUIMethods(){		
		$('#accordion li a').mouseover(function() {
				if($(this).hasClass('firstElement')){
					$('.SNG_alsoShowingAt:first').css("background-color", "#FF0B32");
				}
				$(this).addClass('ASActive');
				$(this).find('p').show();
				return false;
		});

		$('#accordion li a').mouseout(function() {
				if($(this).hasClass('firstElement')){
					$('.SNG_alsoShowingAt:first').css("background-color", "#FFFFFF");
				}
				$(this).removeClass('ASActive');
				$(this).find('p').hide();
				return false;
		});
		$(".SNG_appearAtMore_t").hide();
	}	

	function appearAt(more){
		if(more) {    	
			$(".SNG_appearAt").show();
			$(".SNG_appearAtMore_t").show();
			$(".SNG_appearAtMore").hide();
		} else {   		
			$(".SNG_appearAt").hide();
			$(".SNG_appearAtMore_t").hide();
			$(".SNG_appearAtMore").show();
			var resultTopOffset = Math.floor($('#alsoShowingAppearingAt').offset().top);
			$('html,body').animate({scrollTop: resultTopOffset}, 1000);
		}
		
	}
	
	function SNG_loadContainer(callbackMethod, container){

		var url = GLOBAL_CNTX_PATH + 'controller.web?method=loadPopups&containerId=' + container
		jQuery.ajax({
			   type: "GET",
			   url: url,
			   cache: true,
			   dataType: "html",
			   success: function(data) {
			
					if(container == 'signIn'){
						$('#signInUpProcess').append(data);
					}else if(container == 'myWozzon'){
						$('#myWozzonContainerDiv').html(data);
					}else if(container == 'venue_event_pro'){
						$('#divId').html(data);
					}else{
						$('.SNG_popupsContainerDIV').append(data);
					}
					
					if(callbackMethod!=null)
						eval(callbackMethod);

			   }
			});

	}
	
	function SNG_loadContainerSIUBindings(){
		
		$('.popupFormContent input:password').focus(function(){
			if($(this).attr('id') == 'login_password'){
				$('#loginMainDiv').removeClass('popupFormContentUnHL');
				$('#signUpMainDiv').addClass('popupFormContentUnHL');
			}else if($(this).attr('id') == 'password_exst_woz'){
				$('#fbLoginMainDiv').removeClass('popupFormContentUnHL');
				$('#fbSignUpMainDiv').addClass('popupFormContentUnHL');
			}
		});
		
		$('.popupFormContent input:text').focus(function(){
			var emailFriend = false;
			var objectId = $(this).attr('id');
			var objectVal = trim($(this).val());
			
			if(objectId == 'login_email' && objectVal == SIN_EMAIL ){
				$(this).val('');
			}else if(objectId == 'login_password_text'){
				$(this).hide();
				$('#login_password').show().focus();
			}else if(objectId == 'signup_email1' && objectVal == SIN_EMAIL ){
				$(this).val('');
			}else if(objectId == 'signup_postcode1' && objectVal == SUP_POSTCODE ){
				$(this).val('');
			}else if(objectId == 'signup_email' && objectVal == SIN_EMAIL ){
				$(this).val('');
			}else if(objectId == 'signup_postcode' && objectVal == SUP_POSTCODE ){
				$(this).val('');
			}else if(objectId == 'signup_nickname' && objectVal == SUP_NICKNAME ){
				$(this).val('');
			}else if(objectId == 'signup_password_text' ){
				$(this).hide();
				$('#signup_password').show().focus();
			}else if(objectId == 'signup_conf_password_text' ){
				$(this).hide();
				$('#signup_conf_password').show().focus();
			}else if(objectId == 'email_exst_woz' && objectVal == SIN_EMAIL ){
				$(this).val('');
			}else if(objectId == 'password_exst_woz_text' ){
				$(this).hide();
				$('#password_exst_woz').show().focus();
			}else if(objectId == 'email_fb' && objectVal == SIN_EMAIL ){
				$(this).val('');
			}else if(objectId == 'postcode_fb' && objectVal == SUP_POSTCODE ){
				$(this).val('');
			}else if(objectId == 'nickName_fb' && objectVal == SUP_NICKNAME ){
				$(this).val('');
			}
			
			if(objectId == 'login_email' || objectId == 'login_password_text'){
				$('#loginMainDiv').removeClass('popupFormContentUnHL');
				$('#signUpMainDiv').addClass('popupFormContentUnHL');
			}else if(objectId == 'signup_email1' || objectId == 'signup_postcode1'){
				$('#signUpMainDiv').removeClass('popupFormContentUnHL');
				$('#loginMainDiv').addClass('popupFormContentUnHL');
			}else if(objectId == 'email_exst_woz' || objectId == 'password_exst_woz_text'){
				$('#fbLoginMainDiv').removeClass('popupFormContentUnHL');
				$('#fbSignUpMainDiv').addClass('popupFormContentUnHL');
			}else if(objectId == 'email_fb' || objectId == 'postcode_fb' || objectId == 'nickName_fb'){
				$('#fbSignUpMainDiv').removeClass('popupFormContentUnHL');
				$('#fbLoginMainDiv').addClass('popupFormContentUnHL');
			}else if(objectId == 'friendsEmail' || objectId == 'userEmail' || objectId == 'userName' ){
				emailFriend=true;
			}
			
			if(!emailFriend){
				$(this).removeClass();
			}else{
				$(this).removeClass('popupTextFieldBefore');
			}
			$(this).addClass('popupTextField');
		});
		
		$('.popupFormContent input:text').blur(function(){
			var objectId = $(this).attr('id');
			var objectVal = trim($(this).val());
			
			if(objectId == 'login_email' && objectVal == ''){
				$(this).val(SIN_EMAIL);
				// $(this).removeClass();
				$(this).addClass('popupTextFieldBefore');
				$(this).removeClass('popupTextField');
			
			}else if(objectId == 'signup_email1' && objectVal == ''){
				$(this).val(SIN_EMAIL);
				$(this).addClass('popupTextFieldBefore');
				$(this).removeClass('popupTextField');
			}else if(objectId == 'signup_postcode1' && objectVal == ''){
				$(this).val(SUP_POSTCODE);
				$(this).addClass('popupTextFieldBefore');
				$(this).removeClass('popupTextField');
			}else if(objectId == 'signup_email' && objectVal == ''){
				$(this).val(SIN_EMAIL);
				$(this).addClass('popupTextFieldBefore');
				$(this).removeClass('popupTextField');
			}else if(objectId == 'signup_postcode' && objectVal == ''){
				$(this).val(SUP_POSTCODE);
				$(this).addClass('popupTextFieldBefore');
				$(this).removeClass('popupTextField');
			}else if(objectId == 'signup_nickname' && objectVal == ''){
				$(this).val(SUP_NICKNAME);
				$(this).addClass('popupTextFieldBefore');
				$(this).removeClass('popupTextField');
			
			}else if(objectId == 'email_exst_woz' && objectVal == ''){
				$(this).val(SIN_EMAIL);
				$(this).addClass('popupTextFieldBefore');
				$(this).removeClass('popupTextField');
			
			}else if(objectId == 'email_fb' && objectVal == ''){
				$(this).val(SIN_EMAIL);
				$(this).addClass('popupTextFieldBefore');
				$(this).removeClass('popupTextField');
			}else if(objectId == 'postcode_fb' && objectVal == ''){
				$(this).val(SUP_POSTCODE);
				$(this).addClass('popupTextFieldBefore');
				$(this).removeClass('popupTextField');
			}else if(objectId == 'nickName_fb' && objectVal == ''){
				$(this).val(SUP_NICKNAME);
				$(this).addClass('popupTextFieldBefore');
				$(this).removeClass('popupTextField');
			}
			
			if(objectId == 'signup_email' && $(this).val() != $('#signup_email1').val()){
				SNG_hideLoginError($(this));
			}
			if(objectId == 'signup_postcode' && $(this).val() != $('#signup_postcode1').val()){
				SNG_hideLoginError($(this));
			}
			
			
		});
		
		SNG_checkBoxesBinding('signInUpProcess');
	}
	
	function SNG_emailFriendBinding(){
		
		$('#emailToFriendPopup input:text').focus(function(){
			var emailFriend = false;
			var objectId = $(this).attr('id');
			var objectVal = trim($(this).val());
			
			if(objectId == 'friendsEmail' && objectVal == EF_FRIENDSEMAIl ){
				$(this).val('');
			}else if(objectId == 'userEmail' && objectVal == EF_MYEMAIL ){
				$(this).val('');
			}else if(objectId == 'userName' && objectVal == EF_MYNAME ){
				$(this).val('');
			}
		});		
		
		$('#emailToFriendPopup input:text').blur(function(){
			var objectId = $(this).attr('id');
			var objectVal = trim($(this).val());
			
			if(objectId == 'friendsEmail' && objectVal == '' ){
				$(this).val(EF_FRIENDSEMAIl);
				$(this).addClass('popupTextFieldBefore');
				$(this).removeClass('popupTextField');
			}else if(objectId == 'userEmail' && objectVal == '' ){
				$(this).val(EF_MYEMAIL);
				$(this).addClass('popupTextFieldBefore');
				$(this).removeClass('popupTextField');
			}else if(objectId == 'userName' && objectVal == '' ){
				$(this).val(EF_MYNAME);
				$(this).addClass('popupTextFieldBefore');
				$(this).removeClass('popupTextField');
			}
			
		});
	}
	
	function SNG_checkBoxesBinding(bindToId){
		$('#' + bindToId +' img.checkboximg').click(function(){
			 
	         var srcStr = $(this).attr("src");
	         var isChecked = false;
	         if(srcStr.indexOf('_tick')==-1){
	        	 srcStr = $(this).attr("src").match(/[^\.]+/) + "_tick.png";
	        	 isChecked = true;
	         }else{
	        	 srcStr = $(this).attr("src").replace("_tick", "");
	        	 isChecked = false;
	         }
	         $(this).attr("src", srcStr);
	         // $('+ input[type="checkbox"]',
				// $(this).parent()).attr('checked',isChecked);
	         var chkId = $(this).attr('id').replace('_img','');
	         $('#' + chkId).attr('checked',isChecked);
		});
	}
	
	function SNG_loadContainerAlertBinding(){
		
		$('#saveSearchAlertPopup input:text').focus(function(){
			var objectId = $(this).attr('id');
			var objectVal = trim($(this).val());
			if(objectId == 'alert_email' && objectVal == SIN_EMAIL ){
				$(this).val('');
			}
		});
		
		$('#saveSearchAlertPopup input:text').blur(function(){
			var objectId = $(this).attr('id');
			var objectVal = trim($(this).val());
			if(objectId == 'alert_email' && objectVal == '' ){
				$(this).val(SIN_EMAIL);
				$(this).addClass('popupTextFieldBefore');
				$(this).removeClass('popupTextField');
			}
		});
		SNG_checkBoxesBinding('saveSearchAlertPopup');
	}
	

	
	function SNG_loadPublicProfile(){
		
		// Near By Section scripts.
		SNG_nearByUIMethods();
		// Default Action
		$(".tab_content_mv").hide(); // Hide all content
		$("ul.mwTabs li a:first").addClass("activeDetailTab").show(); // Activate
																		// first
																		// tab
		$(".tab_content_mv:first").show(); // Show first tab content
		
		// On Click Event
		$("ul.mwTabs li").click(function() {
			$("ul.mwTabs li a").removeClass("activeDetailTab"); // Remove any
																// "active"
																// class
			$(this).find("a").addClass("activeDetailTab"); // Add "active"
															// class to selected
															// tab
			$(".tab_content_mv").hide(); // Hide all tab content
			var activeTab = $(this).find("a").attr("href"); // Find the rel
															// attribute value
															// to identify the
															// active tab +
															// content
			$(activeTab).fadeIn(); // Fade in the active content
			return false;
		});
		
		$(".SNG_mwSubTab ul li a").click(function() {
		     var ulObj  = $(this).parent().parent();
		     ulObj.find("a").removeClass("ActveSubMenuTabs");			
		     $(this).addClass("ActveSubMenuTabs");
			 var text = $(this).text();
		 	 var tabId = ulObj.parent().parent().attr("id");
			if(tabId == "tab4") {
				if(text == 'Events') {
	    			$(".venueadded").hide();
	        		$(".titleadded").show();		
	    		} else if(text == 'Venues') {
	    			$(".venueadded").show();
	        		$(".titleadded").hide();
	    		} else {
	    			$(".venueadded").show();
	        		$(".titleadded").show();
	    		}		
			} else {
	    		if(text == 'Events') {
	    			$(".venuereview").hide();
	        		$(".titlereview").show();		
	    		} else if(text == 'Venues') {
	    			$(".venuereview").show();
	        		$(".titlereview").hide();
	    		} else {
	    			$(".venuereview").show();
	        		$(".titlereview").show();
	    		}
			}
			
		});	
		
		if ($('#reportAnchor').length > 0 )  {  
			$('#reportAnchor').fancybox({
				'hideOnContentClick' : false,
				'hideOnOverlayClick': false,				
				'overlayColor'		:	'#666',
				'autoDimensions' 	: false,
				'height'			: 400,
				'width'				: 550,
					'onStart'			:function(){
							$('#imageUploadProcess').show();
							$('#div_report_pic').show();
							$('#div_confirm_report').hide();
							 $('#img_report_txt').val('');
						},
					'onClosed'			:function(){
							SNG_closeMessage();
							$('#imageUploadProcess').hide();
							$('#div_report_pic').hide();
							$('#div_confirm_report').hide();
						}
			 });
		}
		
		 $('#dummyAnchor').mouseover(function(){
			   $('.SNG_mwProfileHover').show();				   
			   var imgObj = $(this).find('img');				 
			   if(imgObj.length > 0 ) {
				   var src = imgObj.attr('src').match(/[^\.]+/) + '_h.png';
				   imgObj.attr('src', src);
			   }
			   
		   });
		   
		   $('#dummyAnchor').mouseout(function(){
			   $('.SNG_mwProfileHover').hide();				   
			   var imgObj = $(this).find('img');
			   if(imgObj.length > 0 ) {
				   var src = imgObj.attr('src').replace('_h','');
				   imgObj.attr('src', src);
			   }				   
		   });
		   
		   $('#dummyAnchor').fancybox({
				'hideOnContentClick' : false,
				'overlayOpacity'	:	0.7,
				'overlayColor'		:	'#666',
				'autoDimensions' 	: false,
				'height'			: 375,
				'width'				: 425,
				'onStart'	:function(){
						$('#dummyPopup').show();
						$('#report_profile').show();
						$('#confirm_report').hide();
						 $('#report_txt').val('');
					},
				'onClosed'	:function(){
						SNG_closeMessage();
						$('#dummyPopup').hide();	
						$('#report_profile').hide();
						$('#confirm_report').hide();
					}
		 });
		 	
		
	}
	
	function SNG_loadMyWozzon(){
		
		// Near By Section scripts.
		// SNG_nearByUIMethods();
		
		// Default Action
		$(".tab_content_mv").hide(); // Hide all content
		$("ul.mwTabs li a:first").addClass("activeDetailTab").show(); // Activate
																		// first
																		// tab
		$(".tab_content_mv:first").show(); // Show first tab content
		
		// On Click Event
		$("ul.mwTabs li").click(function() {
			$("ul.mwTabs li a").removeClass("activeDetailTab"); // Remove any
																// "active"
																// class
			$(this).find("a").addClass("activeDetailTab"); // Add "active"
															// class to selected
															// tab
			$(".tab_content_mv").hide(); // Hide all tab content
			var activeTab = $(this).find("a").attr("href"); // Find the rel
															// attribute value
															// to identify the
															// active tab +
															// content
			$(activeTab).fadeIn(); // Fade in the active content
			return false;
		});
		
		$(".SNG_mwSubTab ul li a").click(function() {
		     var ulObj  = $(this).parent().parent();
		     ulObj.find("a").removeClass("ActveSubMenuTabs");			
		     $(this).addClass("ActveSubMenuTabs");
			 var text = $(this).text();
		 	 var tabId = ulObj.parent().parent().attr("id");
			if(tabId == "tab4") {
				if(text == 'Events') {
	    			$(".venueadded").hide();
	        		$(".titleadded").show();		
	    		} else if(text == 'Venues') {
	    			$(".venueadded").show();
	        		$(".titleadded").hide();
	    		} else {
	    			$(".venueadded").show();
	        		$(".titleadded").show();
	    		}
			}  else if(tabId == "tab2") {
	    		if(text == 'Events') {
	    			$(".venuebookmark").hide();
	        		$(".eventbookmark").show();		
	    		} else if(text == 'Venues') {
	    			$(".venuebookmark").show();
	        		$(".eventbookmark").hide();
	    		} else {
	    			$(".venuebookmark").show();
	        		$(".eventbookmark").show();
	    		}
			} else {
	    		if(text == 'Events') {
	    			$(".venuereview").hide();
	        		$(".titlereview").show();		
	    		} else if(text == 'Venues') {
	    			$(".venuereview").show();
	        		$(".titlereview").hide();
	    		} else {
	    			$(".venuereview").show();
	        		$(".titlereview").show();
	    		}
			}
			
		});	
		 	
		$("#myTown").focus(function(){
			  if(this.value == this.defaultValue) {
			    this.value = '';
			  }	    
		});
		 
		$("#myTown").blur(function(){
			   if(this.value == '') {
			     this.value = this.defaultValue;
			   }		 
		});	
		
		$("#myPostcode").focus(function(){
			  if(this.value == this.defaultValue) {
			    this.value = '';
			  }	    
		});
		 
		$("#myPostcode").blur(function(){
			   if(this.value == '') {
			     this.value = this.defaultValue;
			   }		 
		});
		
		$('#dummyAnchor').fancybox({
				'hideOnContentClick' : false,
				'overlayOpacity'	:	0.7,
				'overlayColor'		:	'#666',
				'autoDimensions' 	: false,
				'height'			: 1000,
				'width'				: 600,
				'onStart'			:function(){
			            SNG_hideClearAllErrors();
						$('#dummyPopup').show();
						window.setTimeout("SNG_resizeFancyBox()", 500);
						
					},
				'onClosed'			:function(){
						SNG_closeMessage();
						$('#dummyPopup').hide();						 
						 $(':input[type="password"]','#editUserDetail').val("");
						 $(':input[type="text"]','#editUserDetail').each( function() {
							    this.value = this.defaultValue; 
							    if ($(this).hasClass('.SNG_SPTextFieldActive')) {
							    	$(this).removeClass('SNG_SPTextFieldActive');
							    }

						 });
						 
					}
		 });
		 
		 /*
			 * $(".ellipsisSpan").each(function(index) {
			 * $(this).text(autoEllipseText($(this).text(), 200)); });
			 */
		
	}
	function SNG_nearMeSearch(lat, lon) {
		UserManager.nearUserSearch(lat,lon, function(source) {
			if( source != 'error'){
				$('#nearMeSearch').html(source);				
				if($('#whatsNickname').length > 0)
				$('#whatsNickname').text('Near ' + nickname + ':');			
				SNG_nearByUIMethods();
			}
		});
	
	}
	function MM_jumpMenu(targ,selObj,restore){ // v3.0
		eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
		if (restore) selObj.selectedIndex=0;
	}
	

	function SNG_loadUserBookmarks(){
		UserManager.getAllUserBookmarks(function(source) {
			if( source != 'error'){
				$('#myWozzonBookmarks').html(source);			
			}
		});
	}
	
	function SNG_loadUserSearchAlerts(){
		UserManager.getUserSearchAlerts(function(source) {
			if( source != 'error'){
				$('#tab3').html(source);
				alertListHover();
			}
		});
	}
	
	function SNG_loadUserInterest(uid){
		UserManager.getUserInterests(uid, function(source) {
			if( source != 'error'){
				$('#userInterest').html(source);
				if($('#interestNickname').length > 0) 
					$('#interestNickname').text(nickname + "'s");
			}
		});
	}
	
	function SNG_loadMyInterest(){
		UserManager.getMyInterests("", function(source) {
			if( source != 'error'){
				$('#myWozzonInterest').html(source);
			}
		});
	}
	
	function SNG_loadAllInterest(){
		UserManager.getAllInterests(function(source) {
			if( source != 'error'){
				$('#SNG_stp2menuCont').html(source);
				SNG_intrstCBsBndng('SNG_stp2menuCont');
			}
		});
	}
	
	function SNG_loadUserComments(val){
		var uid = 0;
		if (val) uid = val;
		UserManager.getUserComments(uid, function(source) {
			if( source != 'error'){
				$('#myWozzonReviews').html(source);
				if(uid > 0 && $('.SNG_mwReviewMsg').length > 0) {
					 $('#myWozzonReviews').hide();
					 $('#tab1').hide();
					 $('#reviewsTab').hide();
				 } else if(uid > 0) {
					 $("#reviewsTab").show().find("a").addClass("activeDetailTab").show();
					 $('#tab1').show();
					 			 
				 }
			}
			$('#myWozzonMainTabDIV').show();
		});
	}
	
	function SNG_loadUserAddedEventVenues(val){
		var uid = 0;
		if (val) uid = val;
		UserManager.getUserAddedEventsVenues(uid, function(source) {
			if( source != 'error'){
				 $('#myWozzonAddedEventVenues').html(source);
				 if(uid > 0) {
					 if( $('.SNG_mwAddedTop').length > 0) {
						 $('#myWozzonAddedEventVenues').hide();					 
						 $('#tab4').hide();	
						 $('#addedTab').hide();
					 } else if($('.SNG_mwReviewMsg').length > 0) {
						 $("#addedTab").show().find("a").addClass("activeDetailTab").show();
						 $('#tab4').show();
					 } else {
						 $("#addedTab").show().find("a").show();						
					 }
				 }
					 
				 $(".ellipsisSpan").each(function(index) {	    
						$(this).text(autoEllipseText($(this).text(), 200));
				 });
			}
		});
	}
	
	
	function SNG_updateUserPostcode() {
		var postcode = $('#myPostcodeFT').val();
		postcode = jQuery.trim(postcode);	
		
		if( postcode == $('#myPostcodeFT').attr("defaultValue"))
			postcode = '';
		
		
		if(postcode == '' ) {
			SNG_alert('Please Enter your postcode');
		} else {
			UserManager.updateUserPostCode(postcode, function(source){
				if(source == "logout") {
					SNG_alert('Login session expired');
				} else if(source == "error" ) {
					SNG_alert('Error during update your location');
				} else {						
					$('#myPostcode').val(postcode);
					$('.SNG_st2C h3').html(postcode);
					 $('#postcodeArea').text(postcode);
					 $('#locationArea').show();
					 SNG_UserProfileCompletion();
					 if( source != "success") {
						 var pc = source.split(",");					 
						 load(pc[0], pc[1]);
						 var link = '<a href="javascript:void(0)" onclick="window.open(\''+ $("#cntx").val() +'controller.web?method=getLargeMap&';
						 link += 'latitude='+ pc[0] +'&longitude='+ pc[1] + '&postCode='+  postcode;
						 link += '\',\'Large Map\',\'scrollbars=no,resizable=no,width=700,height=500\')">View large map</a>' ;
						 $('#largeMap').html(link);
						 $('#largeMap').show();					 
						 $('#postcode').val(postcode);
						 if($('#alertPostcode').length > 0)
							 $('#alertPostcode').val(postcode);
						 
						 SNG_nearMeSearchMethods(pc[0], pc[1]);
						 SNG_loadAllInterest();
						 $('#myWozzonStep1').hide();
						 $('#myWozzonStep2').show();						 
					 }
					 
				} 
				
			});
		}
	}
	
	function SNG_intrstCBsBndng(bindToId){
		$('#' + bindToId +' img.checkboximg').click(function(){
			 
	         var srcStr = $(this).attr("src");
	         var isChecked = false;
	         if(srcStr.indexOf('_tick')==-1){
	        	 // srcStr = $(this).attr("src").match(/[^\.]+/) +
					// "_tick.png";
	        	 srcStr = $(this).attr("src").replace(".png", "_tick.png");
	        	 $(this).css('margin', '0px');
	        	 isChecked = true;
	         }else{
	        	 srcStr = $(this).attr("src").replace("_tick", "");
	        	 $(this).css('margin', '4px 0 0 5px');
	        	 isChecked = false;
	         }
	         $(this).attr("src", srcStr);
	         // $('+ input[type="checkbox"]',
				// $(this).parent()).attr('checked',isChecked);
	         var chkId = $(this).attr('id').replace('_img','');
	         $('.' + chkId).attr('checked',isChecked);
		});
	}
	
	function SNG_alertCBsBndng(bindToId){
		$('#' + bindToId +' img.checkboximg').click(function(){
			 
	         var srcStr = $(this).attr("src");
	         var isChecked = false;
	         if(srcStr.indexOf('_tick')==-1){
	        	 // srcStr = $(this).attr("src").match(/[^\.]+/) +
					// "_tick.png";
	        	 srcStr = $(this).attr("src").replace(".png", "_tick.png");
	        	 isChecked = true;
	         }else{
	        	 srcStr = $(this).attr("src").replace("_tick", "");
	        	 isChecked = false;
	         }
	         $(this).attr("src", srcStr);
	         // $('+ input[type="checkbox"]',
				// $(this).parent()).attr('checked',isChecked);
	         var chkId = $(this).attr('id').replace('_img','');
	         $('.' + chkId).attr('checked',isChecked);
		});
	}
	
	function SNG_myIntrstCBsBndng(){
		$('.SNG_myInterests img.checkboximg').click(function(){
			 
	         var srcStr = $(this).attr("src");
	         var isChecked = false;
	         if(srcStr.indexOf('_tick')==-1){
	        	 // srcStr = $(this).attr("src").match(/[^\.]+/) +
					// "_tick.png";
	        	 srcStr = $(this).attr("src").replace(".png", "_tick.png");
	        	 $(this).css('margin', '0px');
	        	 isChecked = true;
	         }else{
	        	 srcStr = $(this).attr("src").replace("_tick", "");
	        	 $(this).css('margin', '4px 0 0 5px');
	        	 isChecked = false;
	         }
	         $(this).attr("src", srcStr);
	         // $('+ input[type="checkbox"]',
				// $(this).parent()).attr('checked',isChecked);
	         var chkId = $(this).attr('id').replace('_img','');
	         $('.' + chkId).attr('checked',isChecked);
		});
	}
	
	
	function SNG_updateUserInterests(){
		var values = new Array();
		$("#SNG_stp2menuCont input:checked").each(function() {
			if($(this).attr('id') != 'chkOtherInterest'){
				values.push($(this).val());
			}
		});
		
		var otherInterestBox = $('#otherInterest');
		if(values.length > 0 || ($('#chkOtherInterest').is(':checked') && trim(otherInterestBox.val()).length > 0 )){
			var otherInterest = trim(otherInterestBox.val());
			$('.SNG_stg2TPCont').hide();
			UserManager.updateUserInterests(values, otherInterest, function(source){
				if(source == 'hasFoundAlerts'){
					SNG_UserProfileCompletion();
					SNG_userCmpltProfMsg();
					SNG_scrollPageToTop();					
				}else if(source != "error"){					
					SNG_loadMyInterest();
					SNG_UserProfileCompletion();
					$('#SNG_stp2menuContAlerts').html(source);
					$('#myWozzonStep2').hide();
					$('.SNG_completeYourProfLnk a').attr('onclick')
					SNG_alertCBsBndng('SNG_stp2menuContAlerts');
					$('#myWozzonStep3').show();
					SNG_scrollPageToTop($('#myWozzonContainerDiv'));					
				}else{
					SNG_alert("Error while saving your interest.");
				}
			}); 
		}else{
			// if($('#chkOtherInterest').is(':checked') &&
			// trim(otherInterestBox.val()).length > 0 ))
			// SNG_alert("Please select a interest.");
			$('.SNG_stg2TPCont').show();
		}
	}
	
	function SNG_opnEdtUsrIntrst(){
		UserManager.getUsersInterestEditable(function(source){
			if(source != "error"){
				$('.SNG_myInterests').html(source);
				SNG_myIntrstCBsBndng();
			}else{
				SNG_alert("Error while editing interest");
			}
		}); 
	}
	
	function SNG_updateMWUserInterests(){
		var values = new Array();
		$(".SNG_myInterests input:checked").each(function() {
			if($(this).attr('id') != 'chkOtherInterest'){
				values.push($(this).val());
			}else{
				values.push(0);
			}
		});
		
		var otherInterestBox = $('.SNG_myInterests #otherInterest');
		if(values.length > 0 || ($('#chkOtherInterest').is(':checked') && trim(otherInterestBox.val()).length > 0 )){
			var otherInterest = trim(otherInterestBox.val());
			var deleteOther = 0;
			if(!$('#chkOtherInterest').is(':checked')){
				deleteOther =1;
			}
			UserManager.updateMWUserInterests(values, otherInterest, deleteOther,  function(source){
				if(source != "error"){
					$('.SNG_myInterests').html(source);
				}else{
					SNG_alert("Error while saving your interest.");
				}
			}); 
		}else{
			SNG_alert("Please select atleast one interest");
		}
	}
	
	function SNG_show3Step(stepId){
		SNG_loadContainer("SNG_show3StepCont("+stepId+");", "myWozzon");
	}
	function SNG_show3StepCont(stepId){
		$('#myWozzonCompleteProfDiv').hide();
		$('#myWozzonStep1').hide();
		$('#myWozzonStep2').hide();
		$('#myWozzonStep3').hide();
		
		if(stepId == 1){
			$('#myWozzonStep1').show();
		}else if(stepId == 2){
			$('.SNG_st2C h3').html($('#postcodeArea').html());
			$('#myWozzonStep2').show();
			SNG_loadAllInterest();
		}else if(stepId == 3){
			$('.SNG_st2C h3').html($('#postcodeArea').html());	
			loadSearchAlertByInterest();
			$('#myWozzonStep3').show();
		}
		 SNG_scrollPageToTop($('#myWozzonContainerDiv'));
	}
	
	function loadSearchAlertByInterest(){
		UserManager.getSearchAlertByInterest(function(source){
			if(source!='error'){
				$('#SNG_stp2menuContAlerts').html(source);
				SNG_alertCBsBndng('SNG_stp2menuContAlerts');
			}else{
				SNG_alert("Error while saving your interest.");
			}
		});
	}
	
	function SNG_finishProfileLater(stepId){
		$('#myWozzonContainerDiv').html("");
		$('.SNG_completeYourProfLnk').click(function(){
			SNG_show3Step(stepId);
		});
		SNG_scrollPageToTop();
		$('#myWozzonCompleteProfDiv').show();
		if($('#myWozzonMainTabDIV:visible').length == 0 ){
			SNG_loadMyWozzonTabs();
		}
	}
	
	function SNG_scrollPageToTop(objToScroll){
		var scrollTopPos = 0;
		if(objToScroll != null){
			scrollTopPos = objToScroll.offset().top - 5;
		}
		$('html,body').animate({scrollTop: scrollTopPos}, 0);
	}
	
	
	function SNG_updateUserSearchAlert(){
		var catIdAndSrchStr = new Array();
		$("#SNG_stp2menuContAlerts input:checked").each(function() {
			var searchlabel = $("#" + $(this).attr("class") + "_txt").text();
			if($(this).val() == 1103){
				catIdAndSrchStr.push("1103,1102/"+searchlabel+"/music");
			}else{
				catIdAndSrchStr.push($(this).val()+"/"+searchlabel);	
			}
		});
		
		if(catIdAndSrchStr.length > 0){
			UserManager.updateUserSearchAlerts(catIdAndSrchStr, function(source){
				if(source != 'error'){
					SNG_userCmpltProfMsg();
					SNG_scrollPageToTop();
					if($('#myWozzonMainTabDIV:visible').length == 0 ){
						SNG_loadMyWozzonTabs();
					}else{
						SNG_loadUserSearchAlerts();
					}
					SNG_UserProfileCompletion();
				}else{
					SNG_alert("Error while saving your alerts.");
				}
			}); 
		}else{
			SNG_alert("Please select a search alert.");
		}
	}
	
	function SNG_userCmpltProfMsg(){
		$('#myWozzonContainerDiv').html('');
		$('#myWozzonCompleteProfDiv').html('');
		// SNG_alert("Thanks for completing your detail.");
	}
	
	function SNG_profileCompletionBar(proCompBar) {
		var proBar = 1.32 * proCompBar  - 132.0 ;
		proBar =  "" + Math.round(proBar) + "px 0px"				
		$(".SNG_profileCP").css({backgroundPosition: proBar})
	}
	
	function  SNG_UserProfileCompletion() {
		UserManager.userProfileCompletion(function(proCompBar){
			if( proCompBar != '0' ) {
				$('.SNG_profileCP').html( proCompBar + '% Completed');				
				SNG_profileCompletionBar(proCompBar)
			}
		});	
	}
	
	function SNG_textCounter(field,cntfield,maxlimit, fieldName) {
		var fieldValLength = SNG_checkLength(field.value);
		if (fieldValLength > maxlimit)  {
			field.value = field.value.substring(0, maxlimit-1);
			if(fieldName!=null && fieldName!=''){
				SNG_alert(" '"+fieldName+"' can not be more than " + maxlimit +  ' characters.');
			}
			else if(field.name == "eventName")
				SNG_alert(" 'Event Name' can not be more than " + maxlimit +  ' characters.');
		}
	}
	
	function  SNG_searchInterest(thisObj,catId, searchStr){
		var searchLoc = '';
		
		if(trim($("#postcodeArea").text())!=''){
			searchLoc = $("#postcodeArea").text();
		}else if(trim($("#townArea").text())!=''){
			searchLoc = $("#townArea").text();
		}
		
		if(catId == 1103){
			SNG_setURLNoString(thisObj, '1103,1102', '0', null, 'music', searchLoc);
		
		}else if(searchStr!= null && searchStr!=""){
			SNG_setURLNoString(thisObj, '0', '0', null, searchStr, searchLoc);
		}else {
			var searchType = null;
			if(catId == 1117 || catId == 1105 || catId == 1115 || catId == 1113 || catId == 1116){
				searchType = 3;
			}
			SNG_setURLNoString(thisObj, catId, '0', searchType,'', searchLoc);
		}
		
	}
	
	function  SNG_showUserImage(userImage){			
		var iPath =  '/media/profile/'+ userImage + '?state='+new Date().getTime();		
		hideDivs('div_upload')
		hideDivs('div_crop')		
		var imageHtml = '<img id="userImage"  src="'  + iPath + '"  alt="" onload="scaleMyImage(this, \'userImage\');" />' ;
		$('.SNG_edMainImage').html(imageHtml);
		$('.SNG_imageDeleteLnk').show();
	}
	
	function  SNG_delUserImage(userImage){
		SNG_closeFancyBox();
		 var iPath = GLOBAL_CNTX_PATH + 'SNG_images/andro_image.png';
		UserManager.deleteUserImage(function(data){
			if( data == 'success' ) {
				var imageHtml ='<a href="javascript:void(0);" onClick="SNG_uploadImage(\'New\'); clearSessionMoreImage(); return false;">'
				imageHtml += '<img id="userImage"  src="'  + iPath + '"  alt="" height="171" width="228" /> </a>' ;
				$('.SNG_edMainImage').html(imageHtml);
				$('.SNG_imageDeleteLnk').hide();
				SNG_UserProfileCompletion();				
			} else if( data == 'error' ) {
				SNG_alert("Error while deleting your image.");
			} else if (source == "logout") {
				SNG_alert('Login session expired');
			}			
		});	
						
	}
	
	// Venue Events Promotion start
	function SNG_loadContainerVEP(){
		
		UserManager.isRegisterForCampaign(function(source){
			if(source=='error'){
				SNG_alert("Error while checking for user registeration.");
			}else if(source=='No'){
				if($('#promotion_form').length  == 0 ) {
					SNG_loadContainer("SNG_loadContainerVEPBindings();", "venue_event_pro");
				} else if ($('#isUserLogged').val() == 'Yes' && $('#promotion_form input[name="identity"]').val() == 'newUser' ){
					SNG_loadContainer("SNG_loadContainerVEPBindings();", "venue_event_pro");			
				} else {			
					$('a#popupAnchor').click();	
				}				
			}else {
				$('#nicknameSpanReg').html(source);
		    	SNG_messagePopup("promotionAlreayReg"); 
			}
		});
		
	}
	
	function SNG_loadContainerVEPBindings(){
		$('#popupAnchor').fancybox({
			'hideOnContentClick' : false,
			'hideOnOverlayClick': false,
			'overlayOpacity'	:	0.7,
			'overlayColor'		:	'#666',
			'autoDimensions' 	: true,
			'onStart'			:function(){
				$('#divId').show();
				SNG_hideClearAllErrors();
				window.setTimeout("SNG_resizeFancyBox()", 500);
			},				
			'onClosed'			:function(){
				 $('#divId').hide();
				 $(':input[name="genderCheckbox"]','#promotion_form').removeAttr('checked')
				 $(':input[type="password"]','#promotion_form').val("");
				 $('.popupErrorMsgContVEP').hide().find('.popupErrorMessageVEP').text('');
				 $(':input[type="text"]','#promotion_form').each( function() {
					    this.value = this.defaultValue;
					    if ($(this).hasClass('.SNG_SPTextFieldActive')) {
					    	$(this).removeClass('SNG_SPTextFieldActive');
					    }
				 });
				 		  
				 if( $('#regPage').length > 0 )  {
					 $('#regPage').val("");
					 $('#whichLink').val("");
				 }


				
			}
				
		});
		
		// TODO
		// new user register for promotion
		if($('div.SNG_PRAgeGroupMenu').length > 0)   {
			
			$('div.SNG_PRAgeGroupMenu a').click(function(){
				var old = $(".activeAgeGroup");
				if(old.length > 0) {
					old.removeClass("activeAgeGroup");
				}
								
				$("#age").val($(this).find("span").text());
				$(this).addClass("activeAgeGroup");				
			});
			
		}
		
		$(':input[name="genderCheckbox"]').click(function(){
			if($(this).attr('checked')) {
				$(':input[name="genderCheckbox"]').filter(':checked').not(this).removeAttr('checked');	
				$("#gender").val($(this).val()); 
			} else if(!$(':input[name="genderCheckbox"]').is(':checked')) {
				$("#gender").val('');
			}
			
		});	
		
		if($('#password').length > 0  && $('#signup_postcode1').length > 0 
				&& trim($('#signup_postcode1').val()).length > 0)   {
			$('#postcode').val($('#signup_postcode1').val());		
			$('#postcode').removeClass('popupTextFieldBefore').addClass('popupTextField');
		}
		
		
		$('#promotion_form input').blur(function(){
			
			var name = $(this).attr('name');
		    var val = trim($(this).val()); 
		    if(name == 'nickName' && val == '' ) {
		    	$(this).val(MW_NICKNAME);
		    	$(this).removeClass('popupTextField').addClass('popupTextFieldBefore');		    
		    } else if(name == 'postcode' && val == '' ) {
		    	$(this).val(MW_POSTCODE);
		    	$(this).removeClass('popupTextField').addClass('popupTextFieldBefore');		    
		    }else if(name == 'phone' && val == '' ) {
		    	$(this).val(MW_MOBILENUM);
		    	$(this).removeClass('popupTextField').addClass('popupTextFieldBefore');
		    }else if(name == 'email' && val == '' ) {
		    	$(this).val(VEP_EMAIL);
		    	$(this).removeClass('popupTextField').addClass('popupTextFieldBefore');		    
		    }else if(name == 'townCity' && val == '' ) {
		    	$(this).val(VEP_TOWNCITY);
		    	$(this).removeClass('popupTextField').addClass('popupTextFieldBefore');
		    }else if(name == 'paypalEmail' && val == '' ) {
		    	$(this).val(VEP_PAYPAL_EMAIL);
		    	$(this).removeClass('popupTextField').addClass('popupTextFieldBefore');
		    }else if(name == 'firstName' && val == '' ) {
		    	$(this).val(VEP_FIRST_NAME);
		    	$(this).removeClass('popupTextField').addClass('popupTextFieldBefore');
		    }else if(name == 'lastName' && val == '' ) {
		    	$(this).val(VEP_LAST_NAME);
		    	$(this).removeClass('popupTextField').addClass('popupTextFieldBefore');
		    }
		    
			
		});
		
		$('#promotion_form input').focus(function(){
			
			var name = $(this).attr('name');
		    var val = trim($(this).val()); 
		    if(name == 'nickName' ) {
		    	$(this).removeClass('SNG_SPTextFieldActive');
		    	if( val == MW_NICKNAME) {
			    	$(this).val('');		    	
			    	$(this).removeClass('popupTextFieldBefore').addClass('popupTextField');    	
		    	}
		    } else if(name == 'postcode' && val == MW_POSTCODE ) {
		    	$(this).val('');
		    	$(this).removeClass('popupTextFieldBefore').addClass('popupTextField');	    
		    }else if(name == 'phone' && val == MW_MOBILENUM ) {
		    	$(this).val('');
		    	$(this).removeClass('popupTextFieldBefore').addClass('popupTextField');		   
		    }else if(name == 'townCity' && val == VEP_TOWNCITY ) {
		    	$(this).val('');
		    	$(this).removeClass('popupTextFieldBefore').addClass('popupTextField');
		    }else if(name == 'email' && val == VEP_EMAIL ) {
		    	$(this).val('');
		    	$(this).removeClass('popupTextFieldBefore').addClass('popupTextField');
		    }else if(name == 'paypalEmail' && val == VEP_PAYPAL_EMAIL ) {
		    	$(this).val('');
		    	$(this).removeClass('popupTextFieldBefore').addClass('popupTextField');
		    }else if(name == 'firstName' && val == VEP_FIRST_NAME) {
		    	$(this).val('');
		    	$(this).removeClass('popupTextFieldBefore').addClass('popupTextField');
		    }else if(name == 'lastName' && val == VEP_LAST_NAME ) {
		    	$(this).val('');
		    	$(this).removeClass('popupTextFieldBefore').addClass('popupTextField');
		    }else if(name == 'password_text' ){
				$(this).hide();
				$('#password').show().focus();
		    }else if(name == 'conf_password_text' ){
				$(this).hide();
				$('#conf_password').show().focus();
		    }
		    
			
		});
		$('a#popupAnchor').click();
		
	
	}
	
	
	
	function SNG_promotionAddEvent(){		
		SNG_hideClearAllErrors();
		
		var frmName = _$id('promotion_form');
		var firstName = frmName.firstName.value;
		var lastName = frmName.lastName.value;
		var nickName = frmName.nickName.value;	
		var postCode = frmName.postcode.value;
		var phone = frmName.phone.value;		
		var townCity = frmName.townCity.value;
		var paypalEmail = frmName.paypalEmail.value;
		var userAge = frmName.age.value;
		var gender =  frmName.gender.value;
		var identity = frmName.identity.value;		
		var isReceiveEmail = "N";	
		var password = "";
		var isRemember = "N";
		var isNewUser = false;
		if($('#receiveEmailCheckBox').is(':checked'))
			isReceiveEmail = "Y";
		
		postCode = trim(postCode);
		if(postCode == MW_POSTCODE) postCode = '';
		
		phone = trim(phone);
		if(phone == MW_MOBILENUM)  phone= '';
		
		nickName = trim(nickName);
		if( nickName == MW_NICKNAME) nickName = '';
		
		paypalEmail = trim(paypalEmail);
		if(paypalEmail == VEP_PAYPAL_EMAIL) paypalEmail = '';			
				
		townCity= trim(townCity);
		if(townCity ==  VEP_TOWNCITY) townCity = '';
				
		firstName = trim(firstName);
		if( firstName == VEP_FIRST_NAME ) firstName = '';
		
		lastName = trim(lastName);
		if( lastName == VEP_LAST_NAME ) lastName = '';
		
		 if(frmName.password && identity == "newUser") {
			   if(nickName.length == 0) {
				   SNG_displayVEPError($("#text_nickName"),"Please provide nick name.");		
					return false;
				}else if(SNG_checkNickname(nickName)){
					SNG_displayVEPError($("#text_nickName"), NICK_NAME_INVALID_CHAR);		
					return false;
				}
				else if($('#nickNameAlreadyExist').val() == "1") {
					SNG_displayVEPError($("#text_nickName"),"There is already an account associated with this nick name.");
					return false;
				}
				
				password = frmName.password.value;
				var conf_password = frmName.conf_password.value;
				if(password.length == 0 ){
					SNG_displayVEPError($('#password'), 'Please provide a password.');
					$('#password_text').focus();
					return false;
				} else if(conf_password.length == 0 ){
					SNG_displayVEPError($('#conf_password'), 'Please confirm password.');
					$('#conf_password_text').focus();
					return false; 	
				}else if(password.length < 5 ){
					$('#password').val('');
					$('#conf_password').val('');
					SNG_passwordOnBlur(_$id('password'));
					SNG_displayVEPError($('#password'), 'Password must be at least 5 characters long.');
					return false;
				}else if(password != conf_password){
					$('#password').val('');
					$('#conf_password').val('');
					SNG_passwordOnBlur(_$id('password'));
					SNG_displayVEPError($('#password'), 'The passwords you entered do not match.');
					return false;
				} else {								
					if($('#chk_rememberMe').is(':checked'))
						isRemember = "Y";
				}				
				isNewUser = true;
				
			}
				
		if(gender.length  == 0 ){
			SNG_displayVEPError($("#genderCheckbox"),"Please select your gender.");		
			return false;
		}
		else if(userAge.length  == 0 ){
			SNG_displayVEPError($("#ageCheckbox"),"Please select your age group.");		
			return false;
		}		
		else if(firstName.length  == 0 ){
			SNG_displayVEPError($("#firstName"),"Please provide first name.");		
			return false;
		}
		else if(lastName.length  == 0 ){
			SNG_displayVEPError($("#lastName"),"Please provide last name.");		
			return false;
		}		
		else if( paypalEmail.length == 0) {			 
			SNG_displayVEPError($("#paypalEmail"),  "Please provide your PayPal email address.");
			return false;
		}
		else if( !checkEmail(paypalEmail)) {
			SNG_displayVEPError($("#paypalEmail"), "Please provide a valid  email addres.");
			return false;
		} else if(townCity.length == 0  ) {
			SNG_displayVEPError($('#townCity'), 'Please provide your Town/City.');
			return false;			
		} else if(postCode.length == 0  ) {
			SNG_displayVEPError($('#postcode'), 'Please enter your postcode.');
			return false;
		} else if(phone.length > 0 && !validateNumber(phone)){
			SNG_displayVEPError($("#phone"),"Characters in the phone number field need to be numeric.");		
			return false;
		}
		else if(! $('input[name=termsAndConditions]', '#promotion_form').is(':checked') ){			
			SNG_displayVEPError("#messagesib", "Please accept the woZZon Terms & Conditions.");			
			$('input[name=termsAndConditions]', '#promotion_form').focus();
			return false;
		}
			   
		var user = new NewUser(firstName,lastName, nickName, postCode, phone, townCity, paypalEmail, userAge, gender,password);
		UserManager.registerEarnByAddEvent(user,isNewUser, isRemember, isReceiveEmail, function(source){
			if( source == "1" ) SNG_displayVEPError($('#paypalEmail'), 'There is already a user associated with this email address.');
			else if(source == "2") SNG_displayVEPError($("#text_nickName"),"There is already an account associated with this nickname.");
			else if( source == "3") SNG_displayVEPError($('#signInUpErrorDiv').show(), 'Error while registering.');
			else if(source == "4")	SNG_displayVEPError($('#text_nickName'), 'Please enter a Nickname.');
		    else if(source == "5" ) SNG_displayVEPError($('#password_text'), 'Please provide a password.');
		    else if(source == "6" ) SNG_displayVEPError($("#paypalEmail"), "Please provide your PayPal email address.");
		    else if(source == "7" ) SNG_displayVEPError($("#firstName"),"Please provide first name.");		
		    else if(source == "8" ) SNG_displayVEPError($("#lastName"),"Please provide last name.");
		    else if(source == "9" ) SNG_displayVEPError($("#paypalEmail"), "Please provide your PayPal email address.");
		    else if(source == "10" ) SNG_displayVEPError($("#paypalEmail"), "There is already another user associated with the Paypal email address you have specified.");
		    else if(source == "11" ) SNG_displayVEPError($('#postcode'), 'Please enter your postcode.');
		    else if(source == "12" )  {
		    	SNG_closeFancyBox();
		    	$('#nicknameSpanReg').html(nickName);
		    	SNG_messagePopup("promotionAlreayReg"); 
		    }else if(source == "Registered") {
		    	SNG_closeFancyBox();
		    	$('#nicknameSpan').html(nickName);
		    	SNG_messagePopup("promotionSuccess");
		    	if(isNewUser) {
			    	$('.successUserNickname').html(nickName);
			    	$('#whichLink').val("");		  
			        $('#regPage').val("");	
			    	SNG_checkLoginHandler(nickName);
			    	$('#isUserLogged').val('Yes');
		    	}
		    	window.setTimeout("SNG_cmpgnSucesRdrct()", 3000);
			}
		});	
			
		
	}
	
	function SNG_cmpgnSucesRdrct(){
		
		window.location = $('#cntx').val() + CAMPAIGN_REDIRECT_URL;
	}
	
	function NewUser(firstName,lastName, nickName, postCode, phone, townCity, paypalEmail, userAge, gender,password) {
		this.firstName = firstName;
		this.lastName  = lastName;
		this.nickName = nickName;
		this.postCode = postCode;
		this.phone = phone;		
		this.townCity = townCity;		
		this.paypalEmail = paypalEmail;
		this.userAge = userAge;
		this.gender = gender ;
		this.password = password;
		
	}
	
	function SNG_displayVEPError(sibSource, message) {
		$('.popupErrorMsgContVEP').hide().find('.popupErrorMessageVEP').text('');
		$('.popupErrorMsgCont').hide().find('.popupErrorMessage').text('');
		var obj = $('+ .popupMustSign', sibSource);
		var popup = $('+ .popupErrorMsgContVEP', obj).show();
		popup.find('.popupErrorMessageVEP').html(message);	
		SNG_resizeFancyBox();		
		if(sibSource.focus) sibSource.focus();
	}
	
	function  SNG_checkUserNickName(str, oldNickName, email) {
		var nickName = trim(str);
		if(MW_NICKNAME != nickName && nickName.length > 0 && nickName != oldNickName )
			if(SNG_checkNickname(nickName)){
				SNG_displayNickNameError($('#text_nickName'), NICK_NAME_INVALID_CHAR);
			}else{
				UserManager.checkNickNameSuggest(nickName, email , function(source){
					if(source == "error")
						SNG_displayNickNameError($("#text_nickName"),"Error processing request for checking availability of nick name.");
					else if(source == "Exists") {
						$('#nickNameAlreadyExist').val("1");
						SNG_displayNickNameError($("#text_nickName"),"There is already an account associated with this nickname");					
					} else if(source == nickName) {
						$('#nickNameAlreadyExist').val("0");
						SNG_displayNickNameSuccess($('#text_nickName'), '', true);
					} else {
						var link =  "<a  class='suggested' href=\"javascript:SNG_selectNickName('" + source + "')\">"  + source + "</a>" ;
						SNG_displayNickNameExists($("#text_nickName"),"Oh no! Someone has already nicked that name! How about: " + link + "?");	
					}
				});
			}
		else if ( nickName == oldNickName ) {
			$('#nickNameAlreadyExist').val("0");
			$('.popupErrorMsgContUN').hide();
		}
	}
		
	function SNG_displayNickNameExists(sibSource, message){
		$('.popupErrorMsgContUN').hide().find('.popupErrorMessageUN').val('');
		var obj = $('+ .popupErrorMsgContUN', sibSource).show();
		obj.find('.popupErrorMessageUN').html(message);
		obj.find('img').attr('src', GLOBAL_CNTX_PATH + 'SNG_images/icons/error-popup.png');
		sibSource.addClass("SNG_SPTextFieldActive");
		SNG_resizeFancyBox();
	}
	
	function SNG_displayNickNameError(sibSource, message){
		$('.popupErrorMsgContUN').hide().find('.popupErrorMessageUN').val('');
		var obj = $('+ .popupErrorMsgContUN', sibSource).show();
		obj.find('.popupErrorMessageUN').html(message);
		obj.find('img').attr('src', GLOBAL_CNTX_PATH + 'SNG_images/icons/error-popup.png');
		sibSource.addClass("SNG_SPTextFieldActive");
		SNG_resizeFancyBox();		
		if(sibSource.focus) sibSource.focus();

	}
	
	function SNG_displayNickNameSuccess(sibSource, message, hideOthers){
		if(hideOthers){
			$('.popupErrorMsgCont').hide().find('.popupErrorMessage').val('');
		}
		if(message == undefined){
			message = '';
		}
		var obj = $('+ .popupErrorMsgContUN', sibSource).show();
		obj.find('.popupErrorMessageUN').html(message);
		obj.find('img').attr('src', GLOBAL_CNTX_PATH + 'SNG_images/icons/tick-popup-small.png');
		SNG_resizeFancyBox();
	}
	
	function  SNG_selectNickName(source) {
		$('#text_nickName').val(source).focus();
		$('#nickNameAlreadyExist').val("0");
		$('.popupErrorMsgContUN').hide();
		SNG_displayNickNameSuccess($('#text_nickName'), '', true);
	}
	// Venue Events Promotion end
	
	
	function SNG_onEnterKeyLogin(e,id) {
		if(Number(e) == 13) {
			SNG_loginAjax(id);
		}
	}
	
	/* Wozzon Event / Venue Submission process scripts */
		function SNG_checkVenue(pageNo) {
			
			var name = $('#SNG_SPFotmCont #name').val();
			var town = $('#SNG_SPFotmCont #townCity').val();
			var postcode = $('#SNG_SPFotmCont #postcode').val();
			
			if (name) name = trim(name);
			if (town) town = trim(town);
			if (postcode) postcode = trim(postcode);
			
			if (town.length <= 0 || town == SP_V_CITY) town  = '';
			if (postcode.length <= 0 || postcode == SP_V_POSTCODE) postcode  = '';
			
			if ( name.length <= 0 || name == SP_V_VENUE_NAME ) {
				$('#SNG_SPErrorCont').show();
				$('#SNG_SPErrMsg').html("<h2>What's the place called?</h2>");
				
			} else {
				UserManager.checkVenue(name, town, postcode, pageNo, SNG_checkVenueHandler);
			}
		}
		function SNG_checkVenueHandler(source) {
			  if( source == "error" ) 
			      SNG_alert("Error processing your request.");	
			   else if( source == "logout")   
				   SNG_alert("Your login session has expired");
			   else if( source == "notfound")   
				   SNG_alert("Your login session has expired");   
			   else   {          
				   $('#SNG_SPErrorCont').show();
				   $('#SNG_SPErrMsg').html(source);
				   if(source.indexOf("Congratulations") > -1){
					   $('#SNG_venueForm1Submit').hide();
					   $('#SNG_venueForm1SubmitNewV').show();
				   }else{
					   $('#SNG_venueForm1Submit').addClass("SNG_SPADDBtnDisable");
				   }
			   }
		}

		function SNG_notInList(){
			if($('#SNG_SPFormHead').html() == SP_V_HEAD_FIRST ){
				$('#SNG_SPFormHead').html(SP_V_HEAD_NOT_IN_LIST);
			}
			$('#SNG_SPErrorCont').hide();
			$('#SNG_SPErrMsg').html('');
			$('#SNG_venueForm1Submit').removeClass("SNG_SPADDBtnDisable").hide();
			$('#SNG_venueForm1SubmitNewV').show();
			SNG_scrollPageToTop();
		}
		
		function SNG_addVenue_Event(id, isPrev){			
			if(isPrev && id > 0){ 
				document.forms['add_venue_event'].venueId.value=id;
		    	document.forms['add_venue_event'].submit();
		    	
			}else if(id > 0 ) {
				var venueName = "";
				var cityTown = "";
				var postcode = "";
		    	
		    	if($('#SNG_SPFotmCont #name').val() != SP_V_VENUE_NAME)
		    		venueName = $('##SNG_SPFotmCont #name').val();
		    	document.add_venue_event.searchVenueName.value=venueName;
		    	
		    	if($('#SNG_SPFotmCont #townCity').val() != SP_V_CITY)
		    		cityTown = $('#SNG_SPFotmCont #townCity').val();
				document.add_venue_event.searchTownCity.value = cityTown;
				
				if($('#SNG_SPFotmCont #postcode').val() != SP_V_POSTCODE)
					postcode = $('#SNG_SPFotmCont #postcode').val();
				document.add_venue_event.searchPostcode.value=postcode;
				
			    document.forms['add_venue_event'].venueId.value=id;
		    	document.forms['add_venue_event'].submit();

				
			}	else {
				document.add_event_form.action="v_controller.web";
				document.add_event_form.method.value="venueDetail";
				document.add_event_form.submit();
			}
		}
		
		// For Event Pagination
		function SNG_showPagedEvents(pageNo) {
			var venueId = $('#venueId').val();
			UserManager.eventPager(pageNo,venueId, function(source){
				// var obj = _$id('eventPager');
				// _$id('firstListOfEvents').style.display = 'none';
				$('.SNG_spTAEventsPage').html(source);		
			});
		}
		
		function SNG_addEvent(){
			document.forms.venue_detail_form.action="e_controller.web";
			document.forms.venue_detail_form.method.value="addEventForm";
			document.forms.venue_detail_form.submit();
		}
		
		function SNG_showShortEventDetail(titleId) { // For a short ajax
														// based detail of event
														// in an overlay.
			if(document.add_event_form.quickAddEventId) {
				document.add_event_form.method.value="showEventDetail";
				document.add_event_form.titleId.value=titleId;
				document.add_event_form.submit();		
			}else {
				UserManager.showEventDetail(titleId, function(source){
					
					if(source == "error") {
						SNG_alert("Error processing your request.");
					} else {
						$('#SNG_SPTEventPrewMain').html(source);
						$('#SNG_STPEventDLink').click();
					}
				});
			}
		}
		
		function SNG_backToSearch(){
			document.add_event_form.action='controller.web';
			document.add_event_form.method.value='addVenueEvent';
			document.add_event_form.submit();
		}
		
		function SNG_addNewVenue() {
				    	
	    	if(trim($('#SNG_SPFotmCont #name').val()) == SP_V_VENUE_NAME)
	    		$('#SNG_SPFotmCont #name').val("");
	    	
	    	if(trim($('#SNG_SPFotmCont #townCity').val()) == SP_V_CITY)
	    		$('#SNG_SPFotmCont #townCity').val("");
			
			if(trim($('#SNG_SPFotmCont #postcode').val()) == SP_V_POSTCODE)
				$('#SNG_SPFotmCont #postcode').val("");
			
			document.forms.event_venue_main.submit();
		}

		function SNG_venueAddVMsg(vTop, message){
			if($('.SNG_SP7AlertCont:visible').length == 0){
				$('.SNG_SP7AlertCont').show();
			}
			$('.SNG_SPRErrMsg').css("top",  (vTop -26) + 'px');
			$('.SNG_SPRErrMsg').text(message);
			
			SNG_scrollPageToTop($('.SNG_SPFotmContSt7'));
		}
		
		function SNG_checkVenueDetail(){
			
			var name = trim($('#name').val());
			var town = trim($('#townCity').val()); 
			var pnum = trim($('#enquiresPhNum').val());
			var vDesc = trim($('#description').val());
			// var vCategory = trim($('#selVenueCategory').text());
			var vCategory = $("#venueCategory").val();
			var webAdd = trim($('#webAddress').val());
			var address = trim($('#address1').val());
			var usefulInfo = trim($('#usefulInfo').val());
			var tags = trim($('#venueTag').val());
			var email = trim($('#email').val());
			var postcode = trim($('#postcode').val());
			var termsChk = $('#venueAddTermsChk').is(':checked');
			
			if(name == SP_VADD_VENUE_NAME || name.length  <= 0){
				var vnTop = $('#name').offset().top;
				SNG_venueAddVMsg(vnTop, 'Please provide Venue Name');
				return false;
			}else if(address == SP_VADD_ADDRESS || address.length <= 0){
				var vnTop = $('#address1').offset().top;
				SNG_venueAddVMsg(vnTop, 'Is there a number, building or street name you can include here?');
				return false;
			}else if(town == SP_VADD_TOWN || town.length <= 0){
				var vnTop = $('#townCity').offset().top;
				SNG_venueAddVMsg(vnTop, "Please fill the town name.");
				return false;
			}else if(pnum != SP_VADD_PNO && pnum.length > 0 &&  !(validateNumber(pnum))){
				var vnTop = $('#enquiresPhNum').offset().top;
				SNG_venueAddVMsg(vnTop, "Phone number should be numeric.");
				return false;
			}else if(email != SP_VADD_EMAIL && email.length > 0 && !checkEmail(email)){
				var vnTop = $('#email').offset().top;
				SNG_venueAddVMsg(vnTop, "Please provide valid email address.");
				return false;
			}else if( vCategory <= 0 || (vCategory.indexOf(SP_VADD_OCAT)!= -1)){
				var vnTop = $('#selVenueCategory').offset().top;
				SNG_venueAddVMsg(vnTop, "Please specify venue category.");
				return false;
		    }else if(vDesc == SP_VADD_DESC || vDesc.length <= 0){
				var vnTop = $('#description').offset().top;
				vnTop = vnTop + 20;
				SNG_venueAddVMsg(vnTop, 'Please provide Venue Description.');
				return false;
			}else {
				$('.SNG_SP7AlertCont').hide();
				if(termsChk){
					if(tags.indexOf(SP_VADD_TAGS) != -1) $('#venueTag').val('');
					if(email.indexOf(SP_VADD_EMAIL) != -1) $('#email').val('');
					if(pnum.indexOf(SP_VADD_PNO) != -1) $('#enquiresPhNum').val('');
					if(postcode.indexOf(SP_VADD_POSTCODE) != -1) $('#postcode').val('');
					if(usefulInfo.indexOf(SP_VADD_UI) != -1) $('#usefulInfo').val('');
					if(webAdd.indexOf(SP_VADD_WEBADD) != -1) $('#webAddress').val('');
						
					document.forms.add_venue_form.submit();
				}else{
					SNG_alert("You must certify that you are entitled to post this venue or event on woZZon.");
				}
			}	
			
		}
		
		function SNG_editVenueForm(){
			document.venue_detail_form.method.value="editVenueForm";
			document.venue_detail_form.submit();
		}
		
		function SNG_submitVenue(){
			document.forms.venue_detail_form.method.value="submitVenue";
			document.forms.venue_detail_form.submit();
		}
		
		function SNG_editEventForm() {

		  document.add_event_form.method.value = "editEvent";
		  document.add_event_form.submit();
		}
		
		function SNG_updateAdminFee(thisObj){
			var thisObjId = thisObj.id;
			var id = $('#'+thisObjId.replace('_img','')).val();
		    var val ='0';
			if(id == 1){
			    _$id('priceDiv').style.display='';
				_$id('SNG_SPOtherPrice').style.display='';				
			}else if(id == 2){
		    	_$id('priceDiv').style.display='none';
				_$id('SNG_SPOtherPrice').style.display='none';
				_$id('otherPrice').style.display='none';
				
			} else {
		    	_$id('priceDiv').style.display='none';    	
		    	val ='';			
			}
			SNG_setValue('fullPrice',val);
			SNG_setValue('child',val);
			SNG_setValue('familyPrice',val);
			SNG_setValue('memFriPrice',val);
			SNG_setValue('concession',val);
			SNG_setValue('seniorCitizen',val);
			SNG_setValue('groupPrice',val);
			
		}

		function SNG_setValue(id,val)
		{
		   var obj= _$id(id);
		   if(obj)
		   {
		     obj.value=val;
		   }
		   else 
		   {
		     obj = _name(id);
		     if(obj)
		       obj.value=val;     
		   }   
		}
		
		function SNG_eventFormCBBinding(){
			$('#SNG_SPFormAreaCont img.checkboximg').click(function(){
				 
		         var srcStr = $(this).attr("src");
		         var isChecked = false;
		         if(srcStr.indexOf('_tick')==-1){
		        	 srcStr = $(this).attr("src").match(/[^\.]+/) + "_tick.png";
		        	 isChecked = true;
		         }else{
		        	 srcStr = $(this).attr("src").replace("_tick", "");
		        	 isChecked = false;
		         }
		         $(this).attr("src", srcStr);
		         var chkId = $(this).attr('id').replace('_img','');
		         $('#' + chkId).attr('checked',isChecked);
			});
		}
		
		function SNG_evtFrmAddRBtnBinding(){
			$('#SNG_SPFormAreaCont img.radioaddfeeimg').click(function(){
				 var newSrcStr = $('img.radioaddfeeimg').attr("src").replace("_tick", "");
				 $('img.radioaddfeeimg').attr("src", newSrcStr);
		         
		         var srcStr = $(this).attr("src").match(/[^\.]+/) + "_tick.png";
	        	 $(this).attr("src", srcStr); 
		         
		         var chkId = $(this).attr('id').replace('_img','');
		         $('#' + chkId).attr('checked', true);
			});
		}
		
		function SNG_evtFrmDateRBtnBinding(){
			$('#SNG_SPFormAreaCont img.radiodateimg').click(function(){
				var newSrcStr = $('img.radiodateimg').attr("src").replace("_tick", "");
				 $('img.radiodateimg').attr("src", newSrcStr);
		         
		         var srcStr = $(this).attr("src").match(/[^\.]+/) + "_tick.png";
	        	 $(this).attr("src", srcStr); 
		         
		         var chkId = $(this).attr('id').replace('_img','');
		         $('#' + chkId).attr('checked', true);
			});
		}
		
		function SNG_evtFrmDaysRBtnBinding(){
			$('#SNG_SPFormAreaCont img.radiodaysimg').click(function(){
				var newSrcStr = $('img.radiodaysimg').attr("src").replace("_tick", "");
				 $('img.radiodaysimg').attr("src", newSrcStr);
		         
		         var srcStr = $(this).attr("src").match(/[^\.]+/) + "_tick.png";
	        	 $(this).attr("src", srcStr); 
		         
		         var chkId = $(this).attr('id').replace('_img','');
		         $('#' + chkId).attr('checked', true);
			});
		}
		
		function SNG_evtFrmDaysChkBoxBinding(){
			$('#SNG_SPFormAreaCont img.checkdaysimg').click(function(){
				 var srcStr = $(this).attr("src");
		         var isChecked = false;
		         if(srcStr.indexOf('_tick')==-1){
		        	 srcStr = $(this).attr("src").match(/[^\.]+/) + "_tick.png";
		        	 isChecked = true;
		         }else{
		        	 srcStr = $(this).attr("src").replace("_tick", "");
		        	 isChecked = false;
		         }
		         $(this).attr("src", srcStr);
		         var chkId = $(this).attr('id').replace('_img','');
		         $('#' + chkId).attr('checked',isChecked);
		         
		         
			});
		}
		
		
		function SNG_evtFrmHourRBtnBinding(){
			$('#SNG_SPFormAreaCont img.radiohoursimg').click(function(){
				var newSrcStr = $('img.radiohoursimg').attr("src").replace("_tick", "");
				 $('img.radiohoursimg').attr("src", newSrcStr);
		         
		         var srcStr = $(this).attr("src").match(/[^\.]+/) + "_tick.png";
	        	 $(this).attr("src", srcStr); 
		         
		         var chkId = $(this).attr('id').replace('_img','');
		         $('#' + chkId).attr('checked', true);
			});
		}
		function SNG_submitEvent(){
			   
				var eventName = trim($('#eventName').val());
				var descp = trim($('#descp').val()); 
				var shortDescription = trim($('#shortDescription').val());
				var eCategory = $("#category").val();
				
				var termsChk = $('#eventAddTermsChk').is(':checked');
			
				if(trim(eventName) == SP_EADD_EVENT_NAME || trim(eventName) == 0 ){
					var vnTop = $('#eventName').offset().top;
					SNG_venueAddVMsg(vnTop, 'Please enter event name');
					return false;
				}else if(trim(descp) == SP_EADD_DESC || trim(descp) == 0){
					var vnTop = $('#descp').offset().top;
					vnTop = vnTop + 20;
					SNG_venueAddVMsg(vnTop, "Please enter description");
					return false;
				}else if(trim(shortDescription) > 75){
					var vnTop = $('#shortDescription').offset().top;
					vnTop = vnTop + 20;
					SNG_venueAddVMsg(vnTop, "Short description can not be more then 75 characters.");
					return false;
				}else if( $("#categoryId option:selected").val() == 0 ){
					var vnTop = $('.SNG_SPTextFieldComb').offset().top;
					SNG_venueAddVMsg(vnTop, "Please select a category");
					return false;
			    } else if( $("#categoryId option:selected").val() ==-1 && (eCategory.indexOf(SP_EADD_ECAT)!= -1 || trim($('#category').val()) == '')){
					var vnTop = $('#category').offset().top;
					SNG_venueAddVMsg(vnTop, "Please enter other category");
					return false;
				} else if(!validateEventPrice(document.forms.add_event_form)) {
					return;
				} else if(!validateEventTimingRows()) {
					return;
				} else if(! (($('#openDates_2_1:checked').length > 0 && $('#whenfrom_1').val() != '') || 
							($('#CDopenAllWeek_1:checked').length > 0 && $('.SNG_SPCompDays input[name="chkChooseDay_1"]:checked').length > 0) || 
							($('#CHhour_1:checked').length > 0) ) ){
					
					var vnTop = $('#rowTimingRow1').offset().top;
					SNG_venueAddVMsg(vnTop, "Please choose at least one detail from Dates, Days or Hours.");
					return false;
				} else {
					removeDefaultData();
					if(termsChk){
						if(trim(shortDescription) == SP_EADD_SHORTD){
							$('#shortDescription').val('');
						}
						if(trim($('#tags').val()) == SP_EADD_TAGS){
							$('#tags').val('');
						}
						if(trim($('#timingNotes').val()) == SP_EADD_TNOTES){
							$('#timingNotes').val('');
						}
						if($("#categoryId option:selected").val() > 0 ){
							$('#category').val($("#categoryId option:selected").val());
						}
						document.forms.add_event_form.method.value="eventDetail";
						
						document.forms.add_event_form.submit();
					}else{
						SNG_alert("You must certify that you are entitled to post this venue or event on woZZon.");
					}
				}	  
			   
			}
		
		
		function SNG_clearHours(rowId){
			$('#startHour_'+rowId).val(0);
			$('#startMin_'+rowId).val(0);
			$('#startFormat_'+rowId).val(0);
			$('#endHour_'+rowId).val(0);
			$('#endMin_'+rowId).val(0);
			$('#endFormat_'+rowId).val(0);
		}
		
		
	/* End Wozzon Event / Venue Submission process scripts */
	
	
/***********************************************
* Email Validation script-  Dynamic Drive (www.dynamicdrive.com)
* This notice must stay intact for legal use.
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/
 var cntx = null;
<!--
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function pausecomp(millis) 

{
            date = new Date();

            var curDate = null;
            do 
            { 
            var curDate = new Date(); 
            }while(curDate-date < millis);

}
function scrollUp()

{
	
		window.scrollTo(0,0);
	
            /*var s_top = document.documentElement.scrollTop;

            if(s_top == 0)
                        s_top = document.documentElement.scrollTop;
            if(s_top == 0)
                        return;

            var s_diff = 1;
            if(s_top > 100)
                        s_diff = Number(s_top/100);
            for(var cnt=s_top-s_diff;cnt>=0;cnt-=s_diff)

            {           
                        window.scrollTo(0, /*0);
            }

            pausecomp(5);*/
}

function trim(str)
{
	return str.replace(/^\s*|\s*$/g,"");
}

function replaceAll(txt, replace, with_this) {
	return txt.replace(new RegExp(replace, 'g'),with_this);
}

// Error Layer Functions.
var errorTimer;
function displayMessage(msg) 
{
	scrollUp();
	var errObj = document.getElementById('errorDiv');
	if(msg){
		errObj.innerHTML=msg;
	}else{
		errObj.innerHTML = 'Please provide one or more search criteria.';
	}
    errObj.style.display = '';
}

function clearMessage() 
{
    var lsd = _$id('loginStatusDiv');
	if(lsd)
	{
		lsd.style.display = 'none';
	}
	if(_$id('statusDiv') != null)
	_$id('statusDiv').style.display='none'
	
	var ediv= _$id('entityDetailErrorDiv');
	if(ediv) ediv.style.display = 'none';
	var ldiv= _$id('loginErrorDiv');
	if(ldiv) ldiv.style.display = 'none';
	

}

function getDaysInMonth(month,year)  {
	var days;
	if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)  days=31;
	else if (month==4 || month==6 || month==9 || month==11) days=30;
	else if (month==2)  {
	if (isLeapYear(year)) { days=29; }
	else { days=28; }
	}
	return (days);
}
function isLeapYear (Year) {
  if (((Year % 4)==0)) {
      return (true);
  }else { return (false); }
}


function getCheckedValue(radioObj) {
	if(!radioObj) return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function setFromTo(gdp_main) {
	var val =getCheckedValue(gdp_main.gdp_when);	
	val = parseInt(val);
	var date = new Date();
	var when = "";
	var till = "";
	switch(val) {      
	  case 2:   when =  date.print("%d/%m/%Y"); till = when;  break;
	  case 3:   when = gdp_main.selectDate.value;  till = when;  break; 
	}	
	
	if(trim(when) == '' ) {
	   when =  date.print("%d/%m/%Y"); till = when; 
	}
	gdp_main.when.value = trim(when);
	gdp_main.till.value = trim(till);	
	gdp_main.dateCriteria.value = val;	
	
}

function activeDate(date,years,months,daysnum) {

  var today = new Date();
  var day   = today.getDate();
  var month = today.getMonth();
  var year  = today.getYear() ;  
  if (year < 2000) year += 1900; 	
  if( (years > year ) ||  (years == year  && months > month )  ||  (years == year  && months == month && daysnum >= day ) )
		return false;
  
	return true;
}

function setWhenFrom(cal) {
	var date = cal.date;
	var time = date.getTime()       
	var field = document.getElementById("gdp_whenfrom");
	if (field == cal.params.inputField) {          
		field = document.getElementById("when");
		var date2 = new Date(time);
		field.value = date2.print("%d/%m/%Y");
	} 		
	
}

function setWhenTo(cal) {
    var date = cal.date;
    var time = date.getTime()       
    var field = document.getElementById("gdp_whento");
    if (field == cal.params.inputField) {
         field = document.getElementById("till");
		 var date2 = new Date(time);
		 field.value = date2.print("%d/%m/%Y");
     } 
        
}

function _$id(id) 
{
   return document.getElementById(id);
}

function _name(id) 
{
   return document.getElementsByName(id);
}

function getValue(id)
{
   var obj= _$id(id);
   if(obj)
   {
    return obj.value;
   }
   else 
   {
     obj = _name(id);
     if(obj)
       return obj.value;
     else 
       return null;
   }   
}

// Highlighting Functions.
function highlightTextField(element) 
{
	element.style.border="2px solid #FF0000";
}
function clearHighlightingTextField(element) 
{
	element.style.border="1px solid #666666";
}

function checkEmail(email) 
{
   var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i	
   var goodEmail = emailfilter.test(email);
   return goodEmail;
}

function validateEmail(){
 var userEmail = getValue('userEmail');
 var friEmails = getValue('friendsEmail');
 var msg = getValue('message');
 if ( friEmails == 'Multiple emails separated by comma' ) 
     friEmails = ''; 
 
 if(friEmails.length==0 ){
		displayErrorMessage('Please enter atleast one email address');			
 	    highlightTextField(_$id('friendsEmail'));
		return false;			
 }
 else {
	   var emails = friEmails.split(',');
	   var i;
	   for(i=0;i<emails.length;i=i+1){
		   if(!checkEmail(trim(emails[i]))){
			  displayErrorMessage('Please enter a valid email address');			
			  highlightTextField(_$id('friendsEmail'));
		   	  return false;
		  }
	   }
	   clearHighlightingTextField(_$id('friendsEmail'));   
   			
   }
   
   if( userEmail.length==0 ){
		displayErrorMessage('Please enter My Email address');			
		highlightTextField(_$id('userEmail'));
		return false;			
   } else if(!checkEmail(userEmail)) {
	 displayErrorMessage('My Email address is not valid');			
	 highlightTextField(_$id('userEmail'));
	 return false;
   } else {
      clearHighlightingTextField(_$id('userEmail'));
      msg = trim(msg);
     if( msg.length ==0){
		   displayErrorMessage('Please enter add your comments');
 	       highlightTextField(_$id('message'));
		   return false;
	   }
	   clearHighlightingTextField(_$id('message'));
      return true; 
   }
      
  

} 
    

function displayErrorMessage(message) 
{
	var sp = _$id('errorDiv');
	scrollUp();
	sp.innerHTML = message;
    sp.style.display = '';
    //if(errorTimer != 'undefined')
      //  clearTimeout(errorTimer);
    //errorTimer=setTimeout('clearMessage()', 5000);
}

function displayEntityErrorMessage(divId, message) 
{
	var sp = _$id(divId);
	sp.innerHTML = message;
    sp.style.display = '';
}



function displayMsg(divname, message) 
{
	var sp = _$id(divname);
	sp.innerHTML = message;
    sp.style.display = '';
   // if(errorTimer != 'undefined')
     //   clearTimeout(errorTimer);
  //  errorTimer=setTimeout('clearMessage()', 5000);
}

function errorMessages(divname, msg){
	if(divname == null){
		displayErrorMessage(msg)
		displayMsg('loginErrorDiv','&nbsp;')
	}else{
		displayErrorMessage('&nbsp;')
		displayMsg(divname,msg)
	}
}
// Wozzon

function getDiv(show, hide) {
	if(show!=null)
		document.getElementById(show).style.display = '';
	if(hide!=null)
		document.getElementById(hide).style.display = 'none';	
}

function remove() {
  eraseCookie("userPref");
}

function rememberPref(a) {   
   createCookie("userPref", a, 365);
   
   
}
function createCookie(name, value, days)
{
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name)
{
  var ca = document.cookie.split(';');
  var nameEQ = name + "=";
  for(var i=0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
  }
  return null;
}

function readUserPref(_form)
{

  var pageSize=_form.pageSize;
  var a= readCookie("userPref");
  
  if(a != null) {    
     pageSize.value  = a;
  } else {
     pageSize.value  = 10;
  }

}

function SNG_changeReviewLink(message) {
   var hide= _$id('hideComments');
   if(message == 'hide')
       hide.innerHTML = '<a href="#" onclick="SNG_getLayer(\'showcomments\', \'showAllComments\'); SNG_changeReviewLink(\'show\');return false;">Hide review</a>';
    else
       hide.innerHTML = '<a href="#" onclick="SNG_getLayer(\'showAllComments\', \'showcomments\'); SNG_changeReviewLink(\'hide\'); return false;">Show all reviews</a>';

}
function addComment(id) {
	if(null != _$id('isRegisteration') && _$id('isRegisteration').value == "No") {
		 var comment =  _$id('userComment').value 
		 var rating = _$id('rating').value;
		 if(id != 0 && (comment == ' Add your comments here' || comment.length == 0)) {
			displayErrorMessage("Please add comment.");
		 } else if (comment.length > 1000) {
			 _$id('userComment').value = comment.substring(0,1000);
			 displayErrorMessage("Comment text can not exceed 1000 characters.");
		 } else if (rating == 0) {
			 displayErrorMessage("Please rate the venue.");
		 }else {
			UserManager.addUserComment(id, comment, rating, addUserCommentsHandler);
		 }
	}
}

function showCommentArea() {
	SNG_showCommentArea(true);
}

function selstarRate(num, isVenue) {
	cntx = document.getElementById('cntx');
	if(cntx != null) cntx = cntx.value;
	
	var rImg = null, wImg = cntx+'images/stars_white.jpg';

	if(isVenue){
		rImg = cntx+'images/stars_green.jpg';
	}else{
	rImg = cntx+'images/stars_yellow.jpg';
	}
		var curnum = 0;
		for (curnum = 1; curnum <= 5; curnum++) {
			if (num >= curnum) {
				document.getElementById('star0'+curnum).src = ''+rImg;
			} 
			else {
				curnumhalf = curnum - 0.51;
				if (num >= curnumhalf) {
					document.getElementById('star0'+curnum).src = ''+rImg;
				} 
				else {
					document.getElementById('star0'+curnum).src = ''+wImg;
				}
			}
		}
}

function selstar(totalRates,ratingUsers, isVenue) {
		var num=0,maxRating =5,curnum = 0,curnumhalf,obj;
		num = ( (ratingUsers==0)? 0 : (totalRates/ratingUsers) );
		num = ((num>maxRating)? maxRating : num );
		
		var rImg = null, wImg = cntx+'images/stars_white.jpg';
		if(isVenue){
				rImg = cntx+'images/stars_green.jpg';
		}else{
			rImg = cntx+'images/stars_yellow.jpg';
			
		}
		
		for (curnum = 1; curnum <= maxRating; curnum++) {
 		   var obj = document.getElementById('star'+curnum)

			if (num >= curnum) {
				obj.src = rImg;
			}
			else {
				curnumhalf = curnum - 0.51;

				if (num >= curnumhalf) {
        	      obj.src = rImg;
				} else {
		  	      obj.src = wImg;
				}

			}

		}

}

function rateIt(rating, isVenue) {
	
    var obj = _$id('rating');
    var rateStar = _$id('rateStar');
    var starHtml='';
    var message;
    var messages = ["", "Terrible", "Bad", "Just OK","Good","Excellent"];
	cntx = document.getElementById('cntx');
	if(cntx != null)cntx = cntx.value;
	
    if(obj) {
        obj.value = rating;      
        message = _$id('star0'+rating).title;
        
		if(isVenue){/* venue */
			for (curnum = 1; curnum <= 5; curnum++) {
				if (rating >= curnum){
					starHtml +='<a href="#" onclick="return rateIt('+ curnum +', true)">' +
					'<img src="'+cntx+'images/stars_green.jpg" title="'+messages[curnum]+'" width="12" height="12" id="star0'+curnum+'" onmouseover="selstarRate('+curnum+', true);" onmouseout="selstarRate('+rating+', true);"/> </a>';
				}
				 else{
					starHtml +='<a href="#" onclick="return rateIt('+ curnum +', true)">' +
					'<img src="'+cntx+'images/stars_white.jpg" title="'+messages[curnum]+'" width="12" height="12" id="star0'+curnum+'" onmouseover="selstarRate('+curnum+', true);" onmouseout="selstarRate('+rating+', true);"/> </a>';
				 }
			}
		}else{/*incase of title display yello stars*/
			for (curnum = 1; curnum <= 5; curnum++) {
				if (rating >= curnum){
					starHtml +='<a href="#" onclick="return rateIt('+ curnum +')">' +
					'<img src="'+cntx+'images/stars_yellow.jpg" title="'+messages[curnum]+'" width="12" height="12" id="star0'+curnum+'" onmouseover="selstarRate('+curnum+');" onmouseout="selstarRate('+rating+');"/> </a>';
				}
				 else{
					starHtml +='<a href="#" onclick="return rateIt('+ curnum +')">' +
					'<img src="'+cntx+'images/stars_white.jpg" title="'+messages[curnum]+'" width="12" height="12" id="star0'+curnum+'" onmouseover="selstarRate('+curnum+');" onmouseout="selstarRate('+rating+');"/> </a>';
				 }
			}
		}
		/* venue */
		
		
        rateStar.innerHTML = starHtml;
        _$id('rateMessage').innerHTML = '<span>'+message+'</span>';
        //_$id('rateMessage').innerHTML = '<span style="padding-left:40px;border:#000066 thin dashed">'+message+'</span>';
        _$id('rateMessage').style.color='#000000';
        _$id('canelLink').style.display='';
        _$id('userComment').focus();
    }
    
    return false;
}

function showUserReview(id,size, isVenue){
	if(isVenue == null) isVenue='';
  UserManager.showUserReview(id, size, isVenue, showUserReviewHandler);
}

function showUserReviewHandler(source) {
   var obj= _$id('showcomments');   
   var  reviewArea = _$id('reviewarea');
   if( source != "error" )  {
     obj.innerHTML = source;
     obj.style.display = ''; 
     if(_$id('openCommentInEdit')!=null && _$id('openCommentInEdit').value=='yes'){
     	var userCommentId = document.getElementById('editCommentId').value;
   		if(userCommentId > 0 ){
   			SNG_edituserReview(userCommentId, false);
   			_$id('openCommentInEdit').value='no';
   		}
     }
     if(reviewArea) {
        //reviewArea.style.display = '';     
     }
   }
}


function SNG_cancelReview(isVenue) {   
	cntx = document.getElementById('cntx');
	if(cntx != null) cntx = cntx.value;
	$('#isEdit').val('');
	SNG_showCommentArea(false);
	$('#userComment').val('');
    	
	var rateStar = $('#rateStar');
    var starHtml='';
    var message = ["", "Terrible", "Bad", "Just OK","Good","Excellent"];
    for (curnum = 1; curnum <= 5; curnum++) {
         if(isVenue){
    	 	starHtml +='<a href="#" onclick="return SNG_rateIt('+ curnum +', true)"><img src="'+cntx+'SNG_images/star_white.png" title="'+message[curnum]+'" width="16" height="15" id="star0'+curnum+'" onmouseover="SNG_selstarRate('+curnum+', true);" onmouseout="SNG_selstarRate(0, true);"/> </a>';			 
		 }else{
			 starHtml +='<a href="#" onclick="return SNG_rateIt('+ curnum +')"><img src="'+cntx+'SNG_images/star_white.png" title="'+message[curnum]+'" width="16" height="15" id="star0'+curnum+'" onmouseover="SNG_selstarRate('+curnum+');" onmouseout="SNG_selstarRate(0);"/> </a>';			 
		 }
    }
    $('#rateMessage').html('');
    rateStar.html(starHtml);
    $('#canelLink').hide();

    return false;
}

function getRating(entityId, id,link)  {
   UserManager.getEntityRating(entityId, function(entityRating) {
       if(entityRating) {
            if(entityRating.ratingUsers > 0 ) { 
              // alert(entityRating.entityId);            
              writeStar(entityRating.totalRates, entityRating.ratingUsers, id,link );              
            }
       } else {         
       }
   });
}

function writeStar(totalRates,ratingUsers, id,link, isVenue) {

		cntx = document.getElementById('cntx');
		if(cntx != null) cntx = cntx.value;	
		
        var starTitle = ["", "Terrible", "Bad", "Just OK","Good","Excellent"];
		var num=0,maxRating =5,curnum = 0,curnumhalf,obj;
		num = ( (ratingUsers==0)? 0 : (totalRates/ratingUsers) );
		num = ((num>maxRating)? maxRating : num );
		var starHtml='';
        var message;

		var rImg = null, wImg = cntx+'images/stars_white.jpg';
		if(isVenue){
				rImg = cntx+'images/stars_green.jpg';
		}else{
			rImg = cntx+'images/stars_yellow.jpg';
			
		}
		
        for (curnum = 1; curnum <= maxRating; curnum++) {
			if (num >= curnum) {
				starHtml +='<img src="'+rImg+'" width="12" height="12" />';
			}
			else {
				curnumhalf = curnum - 0.51;
				if (num >= curnumhalf) {
        	      starHtml +='<img src="'+rImg+'" width="12" height="12" />'
				} else {
		  	     starHtml +='<img src="'+wImg+'"  width="12" height="12" />'
				}

			}

		}	
		
		
		message = ratingUsers+' user ratings; average rating: ' + (Math.round(num * 10)/10) + ' (' + starTitle[Math.round(num)] + ')';
		starHtml = '<a href="'+ link + '"  title="' + message + '">' + starHtml + '</a> ' ;
		starHtml += '('+ratingUsers+')'; // <img src="images/spacer.gif" alt="" width="5" height="5" /> remove space between stars and counter
        var obj= null;
		if(isVenue && isVenue == true){
		 obj = _$id('vrating' +id);
		}else{
		obj = _$id('rating' +id);// Title rating
		}
        obj.innerHTML = starHtml;        
        obj.style.display = '';
}


function addReviewEventWhileRegisteration(id,emaiId) {
	//set flag
	_$id('isRegisteration').value = "Yes";
   var comment =  _$id('userComment').value 
   var rating = _$id('rating').value;
   UserManager.addReviewWhileRegisteration(id, comment, rating, emaiId, addReviewEventWhileRegisterationHandler);
}

function addReviewEventWhileRegisterationHandler(source) {
	if(null != source) {
		if(source == "error")
			displayErrorMessage("Error processing your request.");  		
		if( source == "SessionOut")  {
   		 displayErrorMessage("Login session expired.");  		
   		}
		emailId = document.getElementById('registration_form').email.value;
		regPassword = document.getElementById('registration_form').password.value;
		UserManager.login(emailId,regPassword,"Y", checkLoginHandler);
		SNG_cancelReview();
		SNG_showAllComments(_$id('entityID').value,0);
		SNG_showCommentArea(false);
			
	}
	
}

function selstarVenue(totalRates,ratingUsers, isVenue) {
	
		cntx = document.getElementById('cntx');
		if(cntx != null) cntx = cntx.value;

		var rImg = null, wImg = cntx+'images/stars_white.jpg';
		if(isVenue){
				rImg = cntx+'images/stars_green.jpg';
		}else{
			rImg = cntx+'images/stars_yellow.jpg';
		}
		

		var num=0,maxRating =5,curnum = 0,curnumhalf,obj;
		num = ( (ratingUsers==0)? 0 : (totalRates/ratingUsers) );
		num = ((num>maxRating)? maxRating : num );
		for (curnum = 1; curnum <= maxRating; curnum++) {
 		   var obj = document.getElementById('star_v'+curnum)

			if (num >= curnum) {
				obj.src = rImg;
			}
			else {
				curnumhalf = curnum - 0.51;

				if (num >= curnumhalf) {
        	      obj.src = rImg;
				} else {
		  	      obj.src = wImg;
				}
			}
		}
}

function getEntityRating(entityId, isVenue)  {
	
	cntx = document.getElementById('cntx');
	if(cntx != null) cntx = cntx.value;
	
   UserManager.getEntityRating(entityId, function(entityRating) {
       if(entityRating) {
          if(isVenue){
			  selstar(entityRating.totalRates, entityRating.ratingUsers, true); 
		  }else{
			  selstar(entityRating.totalRates, entityRating.ratingUsers); 
		  }
		  
       }
   });
}

function getVenueRating(entityId, isVenue)  {
   UserManager.getEntityRating(entityId, function(entityRating) {
       if(entityRating) {
		   if(isVenue){
			   selstarVenue(entityRating.totalRates, entityRating.ratingUsers, true); 
		   }else{
			   selstarVenue(entityRating.totalRates, entityRating.ratingUsers); 
		   }
          
       }
   });
}

function checkRemember(f) { 
  var frm = _$id(f);
  var emailId = frm.email.value;
  var password = frm.password.value;
  if(frm.chk_rememberMe != null && frm.chk_rememberMe.checked) {
	  remember(emailId,password);
  } else removeUserInfo() ;

}
function checkRememberCampaign(f) { 
  var frm = _$id(f);
  var emailId = frm.email_.value;
  var password = frm.password_.value;
  if(frm.chk_rememberMe_ != null && frm.chk_rememberMe_.checked) {
	  remember(emailId,password);
  } else removeUserInfo() ;

}

var userInfoForm ;
function readUserInfo(f)
{
  var frm = _$id(f); 
  userInfoForm = frm; 
  var a= readCookie("wozzonuser");
  if(a != null && frm != null) { 
	 var emailId = frm.email;
     var password = frm.password;     
     var rem=a.split(',');
     emailId.value = rem[0];   
     UserManager.decryptText(rem[1], decryptHandler);
     frm.chk_rememberMe.checked=true;   
  } else {
		 if(frm != null) { //Will forcefully empty both the text boxes.(email n password)
			// frm.reset();
			// frm.login_email.value = '';
			// frm.login_password.value = '';     
		 }
	}

}
var email_a_cookie;
function remember(a,b) {
	email_a_cookie = a;
	UserManager.encryptText(b, encryptHandler);
}

function decryptHandler(data){
	var password = userInfoForm.password; 
	password.value = data;
	showDivs(userInfoForm.login_password.id);
	hideDivs(userInfoForm.login_password_text.id);
}

function encryptHandler(data){
  	var enc=(email_a_cookie+','+data);
    createCookie("wozzonuser",enc,365);
}

function removeUserInfo() {
  eraseCookie("wozzonuser");
}

function eraseCookie(name){
  createCookie(name, "", -1);
}

function displayGrayText(obj, msg){//onblus                
     if(trim(obj.value).length == 0 ){
         obj.style.color='#999999';
         obj.style.fontVariant='small-caps'
         obj.value =  msg;
     }
}
function displayRegularText(obj, msg){//onfocus
     if (obj.value==msg){
         obj.value=''        
     }               
     obj.style.fontVariant='normal'
	 obj.style.color='#000000'; 
}

function validateSearchLocation(searchLocation, latObj, longObj){
	if(searchLocation.length > 1)
	{
	return false;
	}
	else if(latObj.value.length > 1 && longObj.value.length > 1)
	{
	return false;
	}else{
	return true;
	}
}
function onRefreshGrayText(_formObj)
{
    if(_formObj != null)
    {
        
        var objSearchString = _formObj.searchString;
        var objSearchLocation = _formObj.searchLocation;
        var objSearchVenue = _formObj.searchVenue;
        if(objSearchString != null && objSearchString.value==' event or keyword')
        {
                        objSearchString.style.fontVariant='small-caps';
                        objSearchString.style.color='#999999';
        }
        
        if(objSearchLocation != null && objSearchLocation.value==' postcode or town')
        {
                        objSearchLocation.style.fontVariant='small-caps';
                        objSearchLocation.style.color='#999999';
        }

        if(objSearchVenue != null && objSearchVenue.value==' venue name')
        {
                        objSearchVenue.style.fontVariant='small-caps';
                        objSearchVenue.style.color='#999999';
        }
    }
}

//-->
//Map View related js n Ajax [ Ammar ]


//Home Page Related JS

function populateCookies(_form) {
	var gdpForm = _form;
	if (gdpForm.searchLocation.value != "") {
		var currentSearchLocation = gdpForm.searchLocation.value;
		var cookieValue = getCookie("searchLocation");
		if (cookieValue.toLowerCase().indexOf(currentSearchLocation.toLowerCase()) != -1) {
			return;
		}
		var cookieArray = null;
		if (cookieValue == "" && cookieValue.length == 0) {
			cookieArray = new Array();
		} else {
			cookieArray = cookieValue.split(",");
		}
		if (cookieArray.length < 5) {
			cookieArray.push(currentSearchLocation);
		} else {
			if (cookieArray.length == 5) {
				cookieArray.shift();
				cookieArray.push(currentSearchLocation);
			}
		}
		cookieValue = cookieArray.toString();
		setCookie("searchLocation", cookieValue.toString(), null);
	}
}

function removeCookie(cookieName) {
	var cookieValue = getCookie("searchLocation");
	cookieArray = cookieValue.split(",");
	for (x in cookieArray) {
		if(cookieArray[x] == cookieName) cookieArray.splice(x,1);
	}
	cookieValue = cookieArray.toString();
	setCookie("searchLocation", cookieValue.toString(), null);
	
	//setCookie("searchLocation", cookieName, -1);
	printPreviousLocations();
}

function printPreviousLocations() {
	var cookieValue = getCookie("searchLocation");
	var cookieArray = null;	
}
function setCookie(c_name, value, expiredays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}
function getCookie(c_name) {
	if (document.cookie.length > 0) {
		c_start = document.cookie.indexOf(c_name + "=");
		if (c_start != -1) {
			c_start = c_start + c_name.length + 1;
			c_end = document.cookie.indexOf(";", c_start);
			if (c_end == -1) {
				c_end = document.cookie.length;
			}
			var cookieVal = unescape(document.cookie.substring(c_start, c_end));
			cookieVal = cookieVal.replace('\"',"").replace('\"',"");
			return cookieVal;
		}
	}
	return "";
}


function formatDateHomePage(_date) {
	var m_names = new Array("Jan", "Feb", "Mar", 
	"Apr", "May", "Jun", "Jul", "Aug", "Sep", 
	"Oct", "Nov", "Dec");
	
	var day = _date.substring(0,2);
	var month = _date.substring(3,5);
	var year = _date.substring(6);
	month = month - 1 ;
	var d = new Date(year,month,day)
	return m_names[month] + ". " + day + ", " + year;
}
//End of Home Page related JS
/*** T R A N S P A R E N T   G I F     P A T C H ***/
var bgsleight	= function() {
	function addLoadEvent(func) {
		var oldonload = window.onload;
		if (typeof window.onload != 'function') {
			window.onload = func;
		} else {
			window.onload = function() {
				if (oldonload) {
					oldonload();
				}
				func();
			}
		}
	}
	function fnLoadPngs() {
		var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
		var itsAllGood = (rslt != null && Number(rslt[1]) >= 5.5);
		for (var i = document.all.length - 1, obj = null; (obj = document.all[i]); i--) {
			if (itsAllGood && obj.currentStyle.backgroundImage.match(/\.png/i) != null) {
				fnFixPng(obj);
				obj.attachEvent("onpropertychange", fnPropertyChanged);
			}
		}
	}

	function fnPropertyChanged() {
		if (window.event.propertyName == "style.backgroundImage") {
			var el = window.event.srcElement;
			if (!el.currentStyle.backgroundImage.match(/x\.gif/i)) {
				var bg	= el.currentStyle.backgroundImage;
				var src = bg.substring(5,bg.length-2);
				el.filters.item(0).src = src;
				el.style.backgroundImage = "url(x.gif)";
			}
		}
	}

	function fnFixPng(obj) {
		var bg	= obj.currentStyle.backgroundImage;
		var src = bg.substring(5,bg.length-2);
		obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')";
		obj.style.backgroundImage = "url(x.gif)";
	}
	return {
		
		init: function() {
			
			if (navigator.platform == "Win32" && navigator.appName == "Microsoft Internet Explorer" && window.attachEvent) {
				addLoadEvent(fnLoadPngs);
			}
			
		}
	}
	
}();


/*** T R A N S P A R E N T   G I F     P A T C H ***/

/*Method to Bookmark event/venues - START*/
function bookmark(venueId, titleId, pgId, entityName) {
	UserManager.addUserBookmark(venueId, titleId, pgId, entityName, addUserBookmarkHandler);
	
	function addUserBookmarkHandler(data) {
		if (data == "logout") {
			if (_$id('bookmarkMyWozzonId') != null) {
			 	showLoginTable('addUserBookMark', _$id('bookmarkMyWozzonId'));
				return;
			}
		} else if (data == 'Yes') {
			if (venueId != 0 && titleId == 0 && pgId == 0) { // Venues
				var popup_msg = 'Your venue has been bookmarked...';
			} else if (venueId == 0 && titleId != 0 && pgId == 0) { // Titles
				var popup_msg = 'Your title has been bookmarked...';
			} else { // Events
				var popup_msg = 'Your event has been bookmarked...';
			}
		} else if (data == 'Exist') {
			if (venueId != 0 && titleId == 0 && pgId == 0) {
				var popup_msg = 'You have already bookmarked this venue.';
			} else if (venueId == 0 && titleId != 0 && pgId == 0) {
				var popup_msg = 'You have already bookmarked this title.';
			} else {
				var popup_msg = 'You have already bookmarked this event.';
			}
		} else {
			if (venueId != 0 && titleId == 0 && pgId == 0) {
				var popup_msg = 'Error while bookmarking venue.';
			} else if (venueId == 0 && titleId != 0 && pgId == 0) {
				var popup_msg = 'Error while bookmarking tilte.';
			} else {
				var popup_msg = 'Error while bookmarking event.';
			}
		}
		SNG_alert(popup_msg, 'Success'); 
	}
}
var IMAGE_CONTAINER_W=228;
var IMAGE_CONTAINER_H=171;
 var editFlag=false;
var CJ_Image = {
	Calculate: function(options) {
		// declare some local variables
		var ratioX, ratioY, scale, newWidth, newHeight;
		// Check to make sure all the required variables were sent and pass validation
		if (typeof options.srcWidth !== "number" || typeof options.srcHeight !== "number" || typeof options.destWidth !== "number" || typeof options.destHeight !== "number" || typeof options.method !== "string") {
			return;
		}
		// Grab scale ratios
		ratioX = options.destWidth / options.srcWidth;
		ratioY = options.destHeight / options.srcHeight;
		// Determine which algorithm to use
		if (options.method === "fit") {
			scale = ratioX < ratioY ? ratioX: ratioY;
		} else if (options.method === "fill") {
			scale = ratioX > ratioY ? ratioX: ratioY;
		}
		// Set new dimensions
		newWidth = Math.round(options.srcWidth * scale, 10);
		newHeight = Math.round(options.srcHeight * scale, 10);
		// Return the new dimensions, plus the offsets, and if the destination box
		// is smaller or equal to the source image dimensions
		return {
			width: newWidth,
			height: newHeight,
			offset: {
				x: parseInt((options.destWidth - newWidth) / 2, 10),
				y: parseInt((options.destHeight - newHeight) / 2, 10)
			},
			fits: options.srcWidth >= options.destWidth && options.srcHeight >= options.destHeight ? true: false
		};
	}
};
function todayDate() {
	var days = new Array("Sunday","Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday");
	var d = new Date();
	return ("<strong>Today is "+ days[d.getDay()]+" "+ d.getDate() + "/"+ d.getMonth()+1 + "/" + d.getFullYear()+"</strong>");

}

function cutoffText(text, size) {
	var str=text;
	if(str.length > size) document.write(str.substring(0,size)+"...");
	else document.write(str);
}
//a function to limit characters in text area
function textCounter(field,cntfield,maxlimit) {
	var fieldValLength = SNG_checkLength(field.value);
	
	if (fieldValLength > maxlimit)  {
		field.value = field.value.substring(0, maxlimit);
		var msg = " can not be more than ";
		if(field.name == "eventName")
			SNG_alert(' \'Event Name\''+msg+'200 characters.');
		else if(field.name == "shortDescription")
			SNG_alert('\'Short Description\''+msg+'75 characters.');
		else if(field.name == "about")
			SNG_alert(' \'About You\''+msg+'1000 characters.');
		else if(field.name == "descp")
			SNG_alert(' \'Event Description\''+msg+'4000 characters.');	
		else if(field.name == "category")
			SNG_alert(' \'Event Category\''+msg+'200 characters.');	
		else if(field.name == "tags")
			SNG_alert(' \'Event Tags\''+msg+'200 characters.');	
		else if(field.name == "fullPrice")
			SNG_alert(' \'Full Price\''+msg+'100 digits.');	
		else if(field.name == "fullPriceNotes")
			SNG_alert(' \'Full Price Notes\''+msg+'500 digits.');	
		else if(field.name == "child")
			SNG_alert(' \'Child Price\''+msg+'100 digits.');	
		else if(field.name == "childNotes")
			SNG_alert(' \'Child Price Notes\''+msg+'500 digits.');	
		else if(field.name == "familyPrice")
			SNG_alert(' \'Family Price\''+msg+'100 digits.');	
		else if(field.name == "familyPriceNotes")
			SNG_alert(' \'Family Price Notes\''+msg+'500 digits.');	
		else if(field.name == "memFriPrice")
			SNG_alert(' \'Members/Friends Price\''+msg+'100 digits.');	
		else if(field.name == "memFriPriceNotes")
			SNG_alert(' \'Members/Friends Price Notes\''+msg+'500 digits.');		
		else if(field.name == "concession")
			SNG_alert(' \'Concession\''+msg+'100 digits.');	
		else if(field.name == "concessionNotes")
			SNG_alert(' \'Concession Notes\''+msg+'500 digits.');	
		else if(field.name == "seniorCitizen")
			SNG_alert(' \'Senior Citizen Prize\''+msg+'100 digits.');	
		else if(field.name == "seniorCitizenNotes")
			SNG_alert(' \'Senior Citizen Price Notes\''+msg+'500 digits.');	
		else if(field.name == "groupPrice")
			SNG_alert(' \'Group Price\''+msg+'100 digits.');	
		else if(field.name == "groupPriceNotes")
			SNG_alert(' \'Group Price Notes\''+msg+'500 digits.');		
		//Venue	
		else if(field.name == "name")
			SNG_alert(' \'Venue Name\''+msg+'200 characters.');	
		else if(field.name == "description")
			SNG_alert(' \'Venue Description\''+msg+'4000 characters.');	
		else if(field.name == "usefulInfo")
			SNG_alert(' \'Useful Information\''+msg+'1000 characters.');			
		else if(field.name == "venueCategory")
			SNG_alert(' \'Venue Category\''+msg+'200 characters.');	
		else if(field.name == "venueTag")
			SNG_alert(' \'Tags\''+msg+'200 characters.');		
		else if(field.name == "address1")
			SNG_alert(' \'Address\''+msg+'200 characters.');	
		else if(field.name == "townCity")
			SNG_alert(' \'Town City\''+msg+'100 characters.');		
		else if(field.name == "postcode")
			SNG_alert(' \'Post Code\''+msg+'10 characters.');	
		else if(field.name == "timeNotes" || field.name == "timingNotes")
			SNG_alert(' \'Timing Notes\''+msg+'1000 characters.');		
		else if(field.name == "webAddress")
			SNG_alert(' \'Web Address\''+msg+'500 characters.');		
		else if(field.name == "email")
			SNG_alert(' \'Email\''+msg+'300 characters.');		
		else if(field.name == "enquiresPhNum")
			SNG_alert(' \'\Enquires Phone No.\''+msg+'30 characters.');			
	}
	
}


function findPos(obj) {
	var curleft = curtop = 0;
    if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	} else {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
	}
	return [curleft,curtop];
}

function showLoginTableEarnPound(obj){
	if(_$id('isUserLogged') && _$id('isUserLogged').value == 'Yes' )  {  
		var pos = findPos(obj);
		_$id('mainDiv_earnpound').style.left = pos[0] - 200 +'px'; 
		_$id('mainDiv_earnpound').style.top =  pos[1] - 130 +'px';
		showDivs('tbl_login_er');
       return;
	}else {
		var cntx = document.getElementById('cntx');
		if(cntx == null) cntx = "";
		else cntx = cntx.value;
		window.location = cntx;
	}
	
}


function showLoginTable(whichLink,obj) {  

	  if(null != whichLink) {
        $('#whichLink').val( whichLink);
      }
	  
	  if($('#isUserLogged').length > 0 && $('#isUserLogged').val() == 'Yes' )  {
	     checkLoginHandler("UserLogged");
	     return;
	  } else {
		  if($('#signInContainerDIV').length == 0){
			  SNG_loadContainer("SNG_showLoginCallBack()", 'signIn');
		  }else{
			  $('#signinlink').click();
		  }
	  }

}

function SNG_showLoginCallBack(){
	SNG_loadContainerSIUBindings();
	$('#signinlink').click();
}

function SNG_scrollToCenter(){
	
	x = getScrollWidth();
	y = getScrollHeight();
	_$id('mainDiv').style.left = x + 350 + 'px'; 
	_$id('mainDiv').style.top =  y + 200  + 'px';
}
function getScrollWidth()
{
   var w = window.pageXOffset ||
           document.body.scrollLeft ||
           document.documentElement.scrollLeft;
           
   return w ? w : 0;
}

function getScrollHeight()
{
   var h = window.pageYOffset ||
           document.body.scrollTop ||
           document.documentElement.scrollTop;
           
   return h ? h : 0;
}

function setDefaultValue(obj) {
		var val = trim(obj.value);
		if(val.length  == 0){
			obj.value=obj.defaultValue;
		}
}
function hideDivs(divName) {
	if(_$id(divName)) {
		 _$id(divName).style.display = 'none';
	}
}

function showDivs(divName) {
  if(_$id(divName)){
		 _$id(divName).style.display = '';
	}
}
function showRegistrationTable(divName) {
	hideDivs('tbl_login'); 
	showDivs(divName);
	if(document.getElementById('registration_form') != null) {
		document.getElementById('registration_form').nickName.value = '';
		document.getElementById('registration_form').email.value = '';
		document.getElementById('registration_form').reg_password.value = '';
		document.getElementById('registration_form').password1.value = '';
	}
}

function showResetLink() {
	showDivs('resetLink');
	hideDivs('forgetPasswordError');	
}

function showNickHelp(divName) {
	showDivs(divName);
}

function hideNickHelp(divName) {
	hideDivs(divName);
}
//End by Ammar

function goAddVenue( frm_name ){
var frmObj = _$id(frm_name);
if(frmObj != null)
	{
		frmObj.action="controller.web";
		frmObj.method.value="addVenueEvent";
		frmObj.submit();
	}

}
function o_nGoingChangeDates( ){
	var stats = _$id('ongoing').checked
	
		var _startD = _$id('startDate');
		var _endD = _$id('endDate');

if(stats)
	{
		
		if(_startD != null && _endD != null){
			
			var currDateObj = new Date();
			var yr = currDateObj.getFullYear();
			var stDate = "1/1/"+yr;
			var enDate ="31/12/"+yr;
			_startD.value = stDate;
			_endD.value = enDate;
		
		_startD.style.color = '#999999';
		_endD.style.color = '#999999'
		
		}else{
			alert("Date fields not found");
		}
		
	}else{
		
		_startD.style.color = '#000000';
		_startD.value="";
		_endD.style.color = '#000000';
		_endD.value="";

	}
}

function getQueryVariable(query, variable) {

var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
   return pair[1];
}
   return "0";
}
} 

function reportUnsuitable( )
{
	var formObj = _$id('unsuitable_form');
	if(formObj != null){
	var hlink = window.location.href;
	
		var qrStr = hlink.substr(0, hlink.indexOf('?'));
		
		var titleId = getQueryVariable(qrStr, "titleId");
		var venueId = getQueryVariable(qrStr, "venueId");
		
		hlink = qrStr + "?"  + getValue('eventURL'); // + "venueId=" +venueId+"&titleId=" + titleId;
        hlink = escape(hlink);
	
	
	var subject = "Report Unsuitable Information on Wozzon";
	var email = "feedback@wozzon.com" ;
	var body = "I would like to report Unsuitable information on Wozzon.com: " ;
	var message = " %0DType here any comments:%0D";	
	var comp ="mailto:"+email+"?subject="+subject+"&body="+ body + hlink+message;
	
	
			win = window.open(comp,'emailWindow');
			if (win && win.open &&!win.closed) win.close();
	}
}
/*function checkVenue(pageNo) {
	var _form = document.event_venue_main;
	var name = getValue('name');
	var town = getValue('townCity');
	if (name) name = trim(name);
	if (town.length<=0 || (town.indexOf("e.g. Manchester")!= -1)) town  = ''; else trim(town);
	
	if (( name.length <= 0 ) || (name.indexOf("e.g. Odeon")!= -1)) {
		errorMessages('errorDiv', 'Please fill in mandatory field(s) to continue');
		_$id('name').style.border = '1px solid #ff0000';
		_$id('venueName').style.color = '#ff0000';
	} else {
		showProgress();
		UserManager.checkVenue(name, town, pageNo, checkVenueHandler);
	}
}*/

function loginAjax(id) {
	
	SNG_loginAjax(id);
	
}
function logout(pageId) {
	var ctx = _$id('cntx').value;
	if(_$id('isUserLogged'))   {
		_$id('isUserLogged').value = 'No' ;
	}
	
	var objHomePageLogout  = _$id('#homePageLogout');
	var logoutGoHome = $('#onLogoutGoHome');
	if((logoutGoHome && logoutGoHome.length > 0) || (objHomePageLogout && objHomePageLogout.value=='true') )  {
		/*If User loged out from home page do no login on refersh page.*/
		window.location = ctx+"login.web?method=logout";
		
	} else {
		UserManager.logout(pageId, logoutHandler);
	}
	/*For Feature Banner*/
	setCookie("show_feature_banner", "", 0);
}
function logoutHandler(source) {/*Always reload the page when ever logout*/
		var url = document.location.href;
		var pointer =  url.indexOf("controller");
		var hashIndex = url.indexOf("#");
		var lengthUrl = url.length;
		if(url.charAt(lengthUrl) == "#") {
			url = url.substring(pointer,(lengthUrl-1));
		} else if(hashIndex > 0 ) {
		  url = url.substring(pointer,hashIndex);
		} else {
			url = url.substring(pointer,lengthUrl);
		}
		window.location = url;
}


/*function addVenue() {
	var town = getValue('townCity');
	var name = getValue('name')
	if (town.length<=0 || (town.indexOf("e.g. Manchester")!= -1)) _$id('townCity').value  = ''; 
	if (( name.length <= 0 ) || (name.indexOf("e.g. Odeon")!= -1)) _$id('name').value  = ''; 
	
	document.forms.event_venue_main.submit();
}*/
String.prototype.replaceAll = function(pcFrom, pcTo){

      var i = this.indexOf(pcFrom);

      var c = this;

      while (i > -1){

      c = c.replace(pcFrom, pcTo);
      i = c.indexOf(pcFrom);

      }

      return c;
      }


function validateNumber(inputVal) {
	inputVal = inputVal.replaceAll(' ', "");
	
	if (isNaN(inputVal)) {
		return false;
	} else {
		return true;
	}
}

/*function checkVenueDetail(){
	form = document.add_venue_form;
	var startDate = form.startTime.value;
 	var endDate =  form.endTime.value;
	var name = form.name.value;
	var town = form.townCity.value;	 
	var pnum = form.enquiresPhNum.value;
	var vDesc = form.description.value;
	var vCategory = form.venueCategory.value;
	var address = form.address1.value;
	var usefulInfo = form.usefulInfo.value;
	var tags = form.venueTag.value;
	var timingNotes = form.timeNotes.value;
	var email = form.email.value;
	
	if(name) name = trim(name);
    if(town) town  = trim(town);
	if(pnum) pnum  = trim(pnum);
	if(vDesc) vDesc = trim(vDesc);
    if(address) address  = trim(address);
	if(email) email = trim(email)
	
	
	if(timingNotes.indexOf("E.g. Mon-Sat 9AM-8PM, Sun 12AM-5PM; closed Bank holidays")!= -1) _$id('timeNotes').value  = '';
	if(tags.indexOf("E.g. modern art, live music, great food")!= -1) _$id('venueTag').value  = '';
	if(usefulInfo.indexOf("E.g. admission fee, members only, kids welcome, etc.")!= -1) _$id('usefulInfo').value  = '';
	
	if(name.length <= 0){
		displayErrorMessage("Please fill the venue name.");
		return false;
	}
	else if(vDesc.length <= 0){
		displayErrorMessage("Please fill the venue description.");
		return false;
	}
	else if( (vCategory.indexOf("Specify other category")!= -1) || vCategory.length <=0){
   	   displayErrorMessage("Please specify venue category");
	   return false;
    }
	else if(address.length <= 0){
		displayErrorMessage("Please fill in the address.");
		return false;
	}
	else if(town.length <= 0){
		displayErrorMessage("Please fill the town name.");
		return false;
	} 
	
	if(!compareGr8erDates(startDate,endDate)) {
			displayErrorMessage("Please provide a valid date range.");
			return false;
	} 
	else if(email.length > 0 && !checkEmail(email)){
			displayErrorMessage("Please provide valid email address.");
			return false;
	}
	else if(!(validateNumber(pnum))){
		displayErrorMessage("Phone number should be numeric.");
		return false;
	}
	else {		
		document.forms.add_venue_form.submit();
	}	
	
}

function editVenueForm(){
	document.venue_detail_form.method.value="editVenueForm";
	document.venue_detail_form.submit();
	}

function submitVenue(){
	document.forms.venue_detail_form.method.value="submitVenue";
	document.forms.venue_detail_form.submit();
	}
*/	

/*function addEvent(){
	document.forms.venue_detail_form.action="e_controller.web";
	document.forms.venue_detail_form.method.value="addEventForm";
	document.forms.venue_detail_form.submit();
	}*/
	

function login(){

 var email = document.forms.gdp_main_login.email.value; 
 if(trim(email).length == 0 ) {
   errorMessages("loginErrorDiv","Email address is required.");
 } else if(checkEmail(email)) {
	 document.forms.gdp_main_login.submit();
 }else{
    errorMessages("loginErrorDiv","Please enter valid email address.");
 }
}
function resetPass(){
 if(checkEmail(document.forms.login_form.email.value)) {
 	 document.forms.login_form.method.value="resetPass";
	 document.forms.login_form.submit();
		}else{
			errorMessages("loginErrorDiv","Please enter valid email address.");
		}
}

function doResetPass(){
	
	
	if(document.forms.login_form.login_password.value.length <=4 || (document.forms.login_form.login_password.value != document.forms.login_form.re_login_password.value )){
		
		if(document.forms.login_form.login_password.value.length <=4 ){
	errorMessages('loginErrorDiv', 'The password should be a minimum of 5 characters long.')
		}else if(document.forms.login_form.login_password.value != document.forms.login_form.re_login_password.value){
	errorMessages('loginErrorDiv', 'Passwords do not match.')		
		}
	}else{
 	 document.forms.login_form.method.value="doResetPass";
	 document.forms.login_form.submit();
	}
}


function registerNow() {
	    if(!checkEmail(document.forms.registration_form.email.value)){
	 		//displayErrorMessage("Please enter valid email.");		
			errorMessages(null,"Please enter valid email address.");	
		}else
		if(document.forms.registration_form.nickName == ""){
			errorMessages(null,"Enter nick name.");
		}else 
		if(document.forms.registration_form.password.value.length <5 ){
			errorMessages(null,"The password should be a minimum of 5 characters long.");
		}else
		if(document.forms.registration_form.password.value != document.forms.registration_form.password1.value){
			errorMessages(null,"Passwords do not match.");
		}
		else{
			document.forms.registration_form.submit();
		}
}

function registerEarnPound(){
	var userAge = "";
	var firstName = "";
	var lastName = "";
	var gender = "";
	var reviewRegion = "";
	var paypalEmail = "";

	UserManager.isEarnPoundReviewer(function(data){
		if(data=='notreviewer'){
			var div = "registerationError_er" ;
			
			firstName = document.getElementById('registration_form_er').firstName.value;
			lastName = document.getElementById('registration_form_er').lastName.value;
			userAge = document.getElementById('registration_form_er').age.value;
			gender = document.getElementById('registration_form_er').gender.value;
			reviewRegion = document.getElementById('registration_form_er').reviewRegion.value;
			paypalEmail = document.getElementById('registration_form_er').paypalEmail.value;
			termsAndConditions = document.getElementById('registration_form_er').termsAndConditionsReview;
			
			if(!(termsAndConditions!=null && termsAndConditions.checked)){
				displayMsg(div, "You must agree to our Terms & Conditions before you can Sign Up.");
			}else if(trim(firstName) == ""){
				displayMsg(div,"Enter first name.");
			}else if(trim(lastName) == ""){
				displayMsg(div,"Enter last name.");
			}else if(!checkEmail(paypalEmail)){
				displayMsg(div,"Enter PayPal Email address.");
			}else{
				displayMsg(div,"");
				UserManager.registerEarnByReview(firstName, lastName, gender, userAge, reviewRegion, paypalEmail, registerationEarnPoundHandler);
			}
		}else if(data!="" && data!='error'){
			div = "registerationError_er"
			displayMsg(div, "Hey " + data +"! You are already registered with this campaign as a local reviewer.");
		}else if(data=='error'){
			div = "registerationError_er"
			displayMsg(div,"Error.");
		}
		
		
	});
}

var user_nickName ="";
function registerNowAjax(id, promotionalReg) {
	var emailId = "";
	var nickName = "";
	var regPassword = "";
	var termsAndConditions = "";
	
	var div = "";
	if(id == '1' ) {
		div = "registerationError" ;
		document.getElementById('registration_form').identity.value = '1';
		emailId = document.getElementById('registration_form').email.value;
		nickName = document.getElementById('registration_form').nickName.value;
		regPassword = document.getElementById('registration_form').password.value;
		retypePass = document.getElementById('registration_form').password1.value;
		termsAndConditions = document.getElementById('registration_form').termsAndConditions;
	}
	
	if(!checkEmail(emailId)){
			displayMsg(div,"Please enter valid email address.");	
		}else
		if(!(termsAndConditions!=null && termsAndConditions.checked)){
			displayMsg(div, "You must agree to our Terms & Conditions before you can Sign Up.");
		}else if("" == nickName || nickName.length == 0){
			displayMsg(div,"Enter nick name.");
		}else if(SNG_checkNickname(nickName)){
			displayMsg(div, NICK_NAME_INVALID_CHAR);
		}else 
		if(regPassword.length <5 ){
			displayMsg(div,"The password must be at least 5 characters long.");
		}else
		if(regPassword != retypePass){
			displayMsg(div,"The entered passwords do not match.");
		}else{
			var isRemember = "N";
			var remFlag = false;

			var reg_form_chkbox = document.getElementById('registration_form').chk_rememberMe;
			
			if(reg_form_chkbox != null && reg_form_chkbox.checked)
			isRemember = "Y";
			
			var productServicesChkBox = document.getElementById('productServices');
			
			if(promotionalReg != null && productServicesChkBox && productServicesChkBox.checked){
			remFlag = true;
			}else{remFlag = false;}
			var regPg = document.getElementById('reg_page');
			if(regPg != null){
				regPg = regPg.value;
			}else{
				regPg='wozzon/default'
			}
			
			UserManager.register(remFlag, emailId, nickName, regPassword, isRemember, regPg, registerationHandler);
			
			user_nickName = nickName;
		}
}
/*function submitEvent(){
	   validateEventFormData(document.add_event_form);
}*/	
function addAnotherEvent(){
	
	var addAnotherObj = _$id('addAnotherEvent');
		addAnotherObj.value = 'true';
		document.add_event_form.submit();
	}	
		
/*function addVenue_Event(id){
	if(id > 0 ) {
	    document.forms['add_venue_event'].venueId.value=id;
    	document.forms['add_venue_event'].submit();
	}	else {
		document.add_event_form.action="v_controller.web";
		document.add_event_form.method.value="venueDetail";
		document.add_event_form.submit();
	}
}*/

function enterData(e) {
    if (Number(e) == 13) {
		checkVenue(0);
	} else {
		removeErrorState();
		_$id('btnCheckVenue').style.display = '';
   		_$id('btnAddNewVenue').style.display = 'none';
		_$id('venueslist').style.display = 'none';
		checkDisplayLink();
	}
}

/*function onEnterKeyLogin(e,id) {
	if(Number(e) == 13) {
		SNG_loginAjax(id);
	}
}*/

function checkDisplayLink(){
	var name = getValue('name');
	var town = getValue('townCity');

	if((name!= "") && (town!="" ) ){
		document.getElementById('bottom').style.display = ''; // Shaheer
		//document.getElementById('nlinked').style.display = 'none';
		//document.getElementById('linked').style.display = '';
		document.getElementById('venueslist').style.display = 'none';
	}else if((name != " e.g. Odeon") && (town != " e.g. Manchester")){
		document.getElementById('bottom').style.display = ''; // Shaheer
		//document.getElementById('nlinked').style.display = 'none';
		//document.getElementById('linked').style.display = '';
		document.getElementById('venueslist').style.display = 'none';
	}
	else{
		document.getElementById('bottom').style.display = ''; // Shaheer
		//document.getElementById('nlinked').style.display = '';
		//document.getElementById('linked').style.display = 'none';
		document.getElementById('venueslist').style.display = 'none';
		
		}
}

/*function checkVenueHandler(source) {
try{
	var obj =  _$id("venueslist");	

		document.getElementById('bottom').style.display = 'none'; // Shaheer		    
		document.getElementById('venueslist').style.display = '';
   
  if( source == "error" ) 
      displayErrorMessage("Error processing your request.");	
   else if( source == "logout")   
      displayErrorMessage("Your login session has expired");
   else if( source == "notfound")   
      displayErrorMessage("Your login session has expired");   
   else   {          
     obj.innerHTML = source;
   }
   _$id('btnCheckVenue').style.display = 'none';
   _$id('btnAddNewVenue').style.display = '';
   
}catch(error){
	   hideProgress();
	}finally{
		hideProgress();
	}
}*/

function checkVenueHandler(source) {
try{
	var obj =  _$id("venueslist");	

		document.getElementById('bottom').style.display = 'none'; // Shaheer		    
		document.getElementById('venueslist').style.display = '';
   
  if( source == "error" ) 
      displayErrorMessage("Error processing your request.");	
   else if( source == "logout")   
      displayErrorMessage("Your login session has expired");
   else if( source == "notfound")   
      displayErrorMessage("Your login session has expired");   
   else   {          
     obj.innerHTML = source;
   }
   _$id('btnCheckVenue').style.display = 'none';
   _$id('btnAddNewVenue').style.display = '';
   
}catch(error){
	   hideProgress();
	}finally{
		hideProgress();
	}
}

function checkUserSyncAccount() {
	UserManager.checkUserSyncAccount(checkUserSyncAccountHandler);
}

function checkUserSyncAccountHandler(source) {
	var syncAccount = _$id('syncAccount');
	
	try {
		if (source == "error") {
			syncAccount.style.display = 'none';
		} else if (source == "alreadySync") {
			syncAccount.style.display = 'none';
		} else if (source == "notSync") {
			/*For reverting Feature Banner
			syncAccount.style.display = '';
			*/
			/* For Feature Banner*/
			if(_$id('hasToggled').value=='0'){
				_$id('hasToggled').value = "1";
				if(_$id('removeSyncPanel').value!="true"){
					syncAccount.style.display = '';
					toggleFeatureBanner();
				}else{
					syncAccount.style.display = 'none';
				}
			}			 
			hideShowFeatureBanner();
			/*For Feature Banner-End*/
		} else if (source == "invalid") {
			syncAccount.style.display = 'none';
		}
	} catch(err) {
	}
}
/* For Feature Banner*/
function hideShowFeatureBanner(){
	
	var syncAccount = _$id('syncAccount');
	var featureBanner = _$id('featureBanner');
	if(syncAccount.style.display == 'none'){
		featureBanner.style.display = '';
	}else{
		featureBanner.style.display = 'none';
	}
}

function toggleFeatureBanner(){
	var featureBannerVal = getCookie("show_feature_banner");
	var syncAccount = _$id('syncAccount');
	if(featureBannerVal=='0'){
		setCookie("show_feature_banner", "1", 1);
		syncAccount.style.display = 'none';
	}else{
		setCookie("show_feature_banner", "0", 1);
		syncAccount.style.display = '';
	}
}
/* For Feature Banner-End*/
function checkLoginHandler(source) {
	
	SNG_checkLoginHandler(source);

}

function registerationHandler(source) {
	var obj = _$id("registerationError");
	var div = "";
	div = "registerationError";	
	showDivs(div);	
	if( source == "1" ) displayMsg(div,"This email address has already been taken");
	else if(source == "2")   displayMsg(div,"Nickname already in use, please select another Nickname");
	else if( source == "3") displayMsg(div,"Error registering user");
	else if(source == "4")	displayMsg(div,"Please enter nick name.");
    else if(source == "5" ) displayMsg(div,"Please enter password.");
    else if(source == "6" ) displayMsg(div,"Please enter  email address.");

    else if(source == "Registered" || source == "ReRegistered")  {		
			
			//checkRemember('registration_form'); // if remmeber me checked save username
			 //var productServicesChkBox = _$id('productServices');
			// if comming from comptetion registeration page
 	 		
			   //removeUserInfo() ;
			   var submitForm = document.getElementById('compete_form');
			   if(submitForm != null){
				   checkRemember('registration_form'); // if remmeber me checked save username
				   submitForm.submit();
				   return ;
			   }
				
	  		
	  	hideDivs('tbl_registration');			
		var isreviewEvent = _$id('isReviewEvent')
		var isreview =_$id('isReview')
				
		if( !( (isreview && isreview.value == "Yes") ||  (isreviewEvent && isreviewEvent.value == "Yes") || 
					  ( _$id('whichLink').value == "showSubmitChanges" ) )  ) {		
		   SNG_messagePopup('registerationSuccess');	 		 
		}
		 checkLoginHandler(user_nickName);
	 } else  {          
	  	obj.innerHTML = source;
	}
}

function registerationEarnPoundHandler(source){
	
	var obj = _$id("registerationError_er");
	var div = "";
	div = "registerationError_er";	
	showDivs(div);	
	if(source == "7" ) displayMsg(div,"Please enter First Name.");
	else if(source == "8" ) displayMsg(div,"Please enter Last Name.");
	else if(source == "9" ) displayMsg(div,"Please enter PayPal Email.");
	else if(source == "10" ) displayMsg(div,"There is already another user associated with the Paypal email address you have specified.");
	else if(source == "Registered")  {		
	  	showDivs('tbl_regSuccess'); 
	 } else  {          
	  	obj.innerHTML = source;
	}
}

function showRegistrationPage(){
	
	isEarnPoundReviewer();
}
function isEarnPoundReviewer(){
	UserManager.isEarnPoundReviewer(isERReviewerHandler);
}

function isERReviewerHandler(data){
	var div ;	
	
	if(data=='notreviewer'){
		var cntx = document.getElementById('cntx');
		 if(cntx == null) cntx = "";
		 else cntx = cntx.value;
		 window.location = cntx +'promotions/registration_earnpound';
	}else if(data!="" && data!='error'){
		div = "alreadyReviewerDiv"
		displayMsg(div, "Hey " + data +"! You are already registered with this campaign as a local reviewer.");
	}else if(data=='error'){
		div = "registerationError_er"
		displayMsg(div,"Error.");
	}
}

function setStartFrom(cal) {
	var date = cal.date;
	var time = date.getTime()       
	var field = document.getElementById("startDate");	
	var date2 = new Date(time);
	field.value = date2.print("%d/%m/%Y");
	_$id('endDate').value = field.value;
}

function setEndDate(cal) {
    var date = cal.date;
    var time = date.getTime()       
    var field = document.getElementById("endDate");
    var date2 = new Date(time);
	field.value = date2.print("%d/%m/%Y");        
}

/*function updateAdminFee(id){
    var val ='0';
	if(id == 1){
	    _$id('priceDiv').style.display='';
		_$id('otherPriceLink').style.display='';				
	}else if(id == 2){
    	_$id('priceDiv').style.display='none';
		_$id('otherPriceLink').style.display='none';
		_$id('otherPrice').style.display='none';
		
	} else {
    	_$id('priceDiv').style.display='none';    	
    	val ='';			
	}
	setValue('fullPrice',val);
	setValue('child',val);
	setValue('familyPrice',val);
	setValue('memFriPrice',val);
	setValue('concession',val);
	setValue('seniorCitizen',val);
	setValue('groupPrice',val);
	
}

function setValue(id,val)
{
   var obj= _$id(id);
   if(obj)
   {
     obj.value=val;
   }
   else 
   {
     obj = _name(id);
     if(obj)
       obj.value=val;     
   }   
}*/


function loadSubCategory(){
	var obj   = _$id('categoryId');
    var index = obj.selectedIndex;
 	    id    =obj[index].value;

   if( id == "0" ) {   
     _$id('categoryId').selectedIndex=0;
	document.forms[0].subcategoryId.disabled=true; 
   } else {   
     UserManager.loadSubCategories(id, loadSubCatHandler);     
   }
}


function loadSubCatHandler(source){
     obj = _$id("sourceSubCatId");
     obj.innerHTML=source;
     obj.disabled=false;
     
}
function getDateObject(dateString,dateSeperator)
{
	//This function return a date object after accepting 
	//a date string ans dateseparator as arguments
	var curValue=dateString;
	var sepChar=dateSeperator;
	var curPos=0;
	var cDate,cMonth,cYear;

	//extract day portion
	curPos=dateString.indexOf(sepChar);
	cDate=dateString.substring(0,curPos);
	
	//extract month portion				
	endPos=dateString.indexOf(sepChar,curPos+1);			cMonth=dateString.substring(curPos+1,endPos);

	//extract year portion				
	curPos=endPos;
	endPos=curPos+5;			
	cYear=curValue.substring(curPos+1,endPos);
	
	//Create Date Object
	dtObject=new Date(cYear,cMonth-1,cDate);	
	return dtObject;
}
function parseTime(varTime){


}
function compareGr8erDates(val1, val2){

	if(val2 == "" ){
		return true;
	}
	var date1,date2;
	//date1 = getDateObject(val1,"/"); //As now the new date format has space, 
	//date2 = getDateObject(val2,"/"); //we can directly convert it to date obj

	date1 = new Date(val1)
	date2 = new Date(val2)
	
	if(date2 >= date1){
		return true;
	}else{
		return false;
	}
}
function validateFullPrice(valv){
	
	if(valv.indexOf("") != -1){
		valv = valv.replace("","");
		return isNumeric(valv)
	}else{
	return isNumeric(valv)
	}
	
}

	
	
function isDaySelected(){
	var is_selected=false;
		for(i = 0;i <= 6 ; i++){
			if(document.add_event_form.days[i].checked == true ){
				is_selected=true;
				}
		   }
	return is_selected;
	}

function checkDays(){
	var all_checked=true;	

	for(i = 0;i <= 6 ; i++){
		if(document.add_event_form.days[7].checked==true && document.add_event_form.days[i].checked  == false ){
			document.add_event_form.days[7].checked = false;
				}
		}

	for(i = 0;i <= 6 ; i++){
		if(document.add_event_form.days[i].checked == false ){
			all_checked=false;
				}
		   }
 	document.add_event_form.days[7].checked = all_checked;
}

function updateDays(){
	if(document.add_event_form.days[7].checked==true)
	for(i = 0;i <= 7 ; i++){
	    document.add_event_form.days[i].checked=true;
		}

}
function checkAllVenueDays(){
	//if(document.add_venue_form.days[7].checked==true)
	for(i = 0;i <= 6 ; i++){
	    document.add_venue_form.days[i].checked=true;
		}

}
function unCheckAllVenueDays(){
	//if(document.add_venue_form.days[7].checked==true)
	for(i = 0;i <= 6 ; i++){
	    document.add_venue_form.days[i].checked=false;
		}

}


function cancel(name){
   if(_$id(name)) {
	_$id(name).method.value="cancel";	
   } else {
      _$id("method").value="cancel";     
   }
   document.forms[name].submit();
}

function isNumeric(strString)
   //  check for valid numeric strings	
   {
   var strValidChars = "0123456789.";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
   }

function isValidTime(obj, skip)
   //  check for valid numeric strings	
   {
	var strString = obj.value;
   var strValidChars = "0123456789:AM PM am pm Unknown";
   var strChar;
   var blnResult = true;
	
   if(skip && (trim(strString).length <= 0 || strString == ' e.g. 9:00 AM')){
   
   obj.value = "";
   return true;
   }
   
   if (strString.length <= 0)
   return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }

   return blnResult;
   }

function validatePostCode(strString) {
   var strValidChars = "0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
	
}

function validateTimeFormat(value, skip) {
	var flag = true;
	var hasMeridian = false;
	value = value.toUpperCase();
	
   var re = /^\d{1,2}[:]\d{2}([:]\d{2})?( [AP][M]?)?$/;
   
   if(value == "UNKNOWN" || value == "OPTIONAL" || value == "Unknown" || value == "Optional"){
		flag =  true;
	}
   else {
		   if (!re.test(value)) { flag = false; }
		   if (value.indexOf("AM") > 0) { hasMeridian = true; }
		   if (value.indexOf("PM") > 0) { hasMeridian = true; }
		   var values = value.split(":");
		   if (hasMeridian)
		   {
			  if ( (parseFloat(values[0]) < 1) || (parseFloat(values[0]) > 12) )
				{
				  flag = false;
				 }
			}else{
			   flag = false;
		   }
		   
		   if ( (parseFloat(values[1]) < 0) || (parseFloat(values[1]) > 59) ) { flag =  false; }
		   if (values.length > 2) {
			  if ( (parseFloat(values[2]) < 0) || (parseFloat(values[2]) > 59) ) { flag =  false; }
		   }
   
   }
   if(skip && trim(value).length <= 0 && !flag){
		flag = true;
	}
	
   return flag;
}

function dotimedrop(time){
var cal_time;
	if(time == "startTimeSelect"){
		cal_time = document.add_event_form.startTimeSelect[document.add_event_form.startTimeSelect.selectedIndex].value;
  	 	if(cal_time == 'All Day'){
		document.add_event_form.startTime.value='12:00 AM';	
		document.add_event_form.startTime.setAttribute('readonly','readonly');
		document.add_event_form.startTime.style.color = '#999999'

		document.add_event_form.endTime.value='12:00 AM';	
		document.add_event_form.endTime.setAttribute('readonly','readonly');
		document.add_event_form.endTime.style.color = '#999999'

		}else{
		document.add_event_form.startTime.value=cal_time;
		document.add_event_form.startTime.removeAttribute('readOnly');
		
		if(document.add_event_form.startTime.value != ' e.g. 9:00 AM'){
		document.add_event_form.startTime.style.color = '#000000'
		}
		
		document.add_event_form.endTime.removeAttribute('readOnly'); 
		
		if(document.add_event_form.endTime.value != ' Optional'){
		document.add_event_form.endTime.style.color = '#000000'
			}
		}

		
			 
  	 }else
	if(time == "endTimeSelect"){
		cal_time = document.add_event_form.endTimeSelect[document.add_event_form.endTimeSelect.selectedIndex].value;
	if(cal_time=='All Day')
		{
  	 	document.add_event_form.endTime.value= '12:00 AM';
		document.add_event_form.endTime.setAttribute('readonly','readonly');
		document.add_event_form.endTime.style.color = '#999999';

  	 	document.add_event_form.startTime.value= '12:00 AM';
		document.add_event_form.startTime.setAttribute('readonly','readonly');
		document.add_event_form.startTime.style.color = '#999999'

		}else{
  	 	document.add_event_form.endTime.value= cal_time;
		document.add_event_form.endTime.removeAttribute('readOnly');
		
		if(document.add_event_form.endTime.value != ' Optional'){
		document.add_event_form.endTime.style.color = '#000000'
		}
		
		document.add_event_form.startTime.removeAttribute('readOnly');
		if(document.add_event_form.startTime.value != ' e.g. 9:00 AM'){
		document.add_event_form.startTime.style.color = '#000000'
			}
		}
  	 }


}

/*function editEventForm() {

  document.add_event_form.method.value = "editEvent";
  document.add_event_form.submit();
}*/

function submitEventForm() {
   document.add_event_form.submit();
}

function addEventPriceValidator(strString)
   //  check for valid numeric strings	
   {
   var strValidChars = "0123456789. -";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length;  i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         break;
         }
      }
   return blnResult;
   }
   
   
function writeTimePeriod(_form){  
    var today = new Date();
    var day   = today.getDate();
    var month = today.getMonth() + 1;
    var year  = today.getYear();
 	if (year < 2000) year += 1900; 	
 	_form.gdp_whenfrom.value =  today.print("%d/%m/%Y");
	
	if(month == 12) {
	   month = 1 ;
	   year = year + 1  ;
	} else month = month + 1 ;
	
	var days = getDaysInMonth(month,year);
	if( days < day )  day = days;
	else if( day < 10 ) day = "0" + day;		
	if( month < 10 ) month = "0" + month;		
    _form.gdp_whento.value =  day + "/" + month+"/" + year; 
}


function killEnter(evt) {
	if(evt.keyCode == 13 || evt.which == 13) {
		//alert("ENTER");
		return false;
	}
return true;
}



//Add user Review on Venue Page (Ajax Based Functionality) 
var userVenueRating = 0;
function addReviewForVenue(id) {
   var comment =  _$id('userComment').value 
   var rating = _$id('rating').value;
   var termsAndConditions = _$id('termsAndConditionsReview');
   if(id != 0 && (comment == ' Add your comments here' || comment.length == 0)) {
	  SNG_alert("Complete your review before submitting. Both rating and comments are compulsory.");
   } else if (comment.length > 1000) {
	   _$id('userComment').value = comment.substring(0,1000);
	   SNG_alert("Comment text can not exceed 1000 characters.");
   } else if (rating == 0) {
	   SNG_alert("Complete your review before submitting. Both rating and comments are compulsory.");
   } else if (!(termsAndConditions!=null && termsAndConditions.checked) ) {
	   SNG_alert("You must accept our review terms & conditions before you can submit a review.");
   } else {
	  UserManager.addReviewVenue(id, comment, rating, addReviewVenueHandler);
	  userVenueRating = parseInt(rating);
   }
}


function addReviewVenueHandler(source) {
   var obj= _$id('showcomments');
   var hide= _$id('hideComments');
   var rate_this_venue = document.getElementById('rate_this_venue');
	
   if( source == "error" ) 
	   SNG_alert("Error processing your request.");	
   else if( source == "logout")  {
	   if(_$id('reviewMain') != null) {  
			showLoginTable('SubmitRating',_$id('reviewMain'));
			return;
		}		
   } 
   else {
	 if(source == "AlreadyReviewed" ) {
		 SNG_alert("You have already reviewed this venue.");

	    SNG_showCommentArea(false);
	    SNG_showAllReviews();
	   return;
   	 } 
   	 
     obj.innerHTML = source;	 
     SNG_showCommentArea(false);
     _$id('userComment').value ='' ;
     obj.style.display = '';
     var allComments = _$id('showAllComments');
     if(allComments) {
        hide.style.display = '';
     }
     var  reviewArea = _$id('reviewarea');
     if(reviewArea) {
        reviewArea.style.display = '';     
     }
     var userCommentCount =_$id('userCommentCount').value;
	 var totalRating = _$id('totalRating').value  ;
	 totalRating = parseInt(userVenueRating) + parseInt(totalRating);
     userCommentCount = parseInt(userCommentCount) +  1;
	 _$id('userCommentCount').value = userCommentCount;
	 SNG_selstar(totalRating , userCommentCount, true);
     if(userCommentCount == 1 ) {
       _$id('averageReview').style.display = '';   
     }
     if(userCommentCount > 1){
			$('.SNG_edRatingText').html('ratings');
	 }else{
			 $('.SNG_edRatingText').html('rating');
	  }
	  $('#totalReview').html(userCommentCount);
	  $('#totalReview2').html('(' + userCommentCount  +  ')');
   }
}
//Scripts for Editing user reviews
var isVenueEditUser = false;
function SNG_edituserReview(userCommentId, isVenue) {
	$('#isEdit').val('Yes');
	if(userCommentId != null) {
		$('#userCommentId').val(userCommentId);
		isVenueEditUser = isVenue;
		UserManager.editUserReview(userCommentId, SNG_editUserReviewHandler);
	}
}

function SNG_editUserReviewHandler(source) {
	var cntx = document.getElementById('cntx');
	if(cntx!=null)cntx = cntx.value;
	
	if(null != source) {
		if(source == "NotFound") {
			SNG_alert("Error processing your request.");
			return false;
		} else if(source == "logout") {
			SNG_alert("Login session expired.");
			return false;
		}
		else {
		 
		 $('#userComment').show();
		 $('#userComment').val(source);		 
		 
		 $('#commentSumbit').hide();
		 $('#commentUpdate').show();
		 SNG_showCommentArea(true);
		 //$('#editUserReviewLink').hide();
		 //Star Reseting Functionality	 
			 var rateStar = _$id('rateStar');
			 var rating = parseInt(_$id('noOfStars').value);
			 var message;
			 var starHtml = '';
       var messages = ["", "Terrible", "Bad", "Just OK","Good","Excellent"];
       message = _$id('star0'+rating).title;
       //rateIt(rating);

		if(isVenueEditUser){
			rateIt(rating, true);
			for (curnum = 1; curnum <= 5; curnum++) {
				
				if (rating >= curnum)
					starHtml +='<a href="#" onclick="return SNG_rateIt('+ curnum +', true)">' +
					'<img src="'+cntx+'SNG_images/star_green.png" title="'+messages[curnum]+'" width="16" height="15" id="star0'+curnum+'" onmouseover="SNG_selstarRate('+curnum+', true);" onmouseout="SNG_selstarRate('+rating+', true);"/> </a>\r\n';
				 else
					starHtml +='<a href="#" onclick="return SNG_rateIt('+ curnum +', true)">' +
					'<img src="'+cntx+'SNG_images/star_white.png" title="'+messages[curnum]+'" width="16" height="15" id="star0'+curnum+'" onmouseover="SNG_selstarRate('+curnum+', true);" onmouseout="SNG_selstarRate('+rating+', true);"/> </a>\r\n';
			}
		
		}else{
			rateIt(rating);
			for (curnum = 1; curnum <= 5; curnum++) {
				
				if (rating >= curnum)
					starHtml +='<a href="#" onclick="return SNG_rateIt('+ curnum +')">' +
					'<img src="'+cntx+'SNG_images/star_yellow.png" title="'+messages[curnum]+'" width="16" height="15" id="star0'+curnum+'" onmouseover="SNG_selstarRate('+curnum+');" onmouseout="SNG_selstarRate('+rating+');"/> </a>\r\n';
				 else
					starHtml +='<a href="#" onclick="return SNG_rateIt('+ curnum +')">' +
					'<img src="'+cntx+'SNG_images/star_white.png" title="'+messages[curnum]+'" width="16" height="15" id="star0'+curnum+'" onmouseover="SNG_selstarRate('+curnum+');" onmouseout="SNG_selstarRate('+rating+');"/> </a>\r\n';
			}
		}

		_$id('userComment').focus();
        rateStar.innerHTML = starHtml;
			
			//_$id('rateMessage').innerHTML = 'Terrible&#0133;<img src="'+cntx+'images/spacer.gif" alt="" width="40" height="15" />&#0133;Excellent';
			//_$id('rateMessage').style.color='#999999';
		}
	} 
	
	isVenueEditUser = false;
}

//End Of Scripts for Editing user Reviews
//End of 'Add User Reviews on Venue Page.

//Script for Pagination of Venues. [By Ammar ]

function getVenueNextPage(pageNo) {
	UserManager.getVenueNextPage(pageNo, checkVenueHandler);
}

//End of Scripts for Pagination of Venues 


//For Add Venue Submission (Scripts From Shaheer, integrated by Ammar) \
// Shaheer
function openAddTimingsArea() {
	document.getElementById("openDate").style.display = '';
	document.getElementById("openDay").style.display = '';
	document.getElementById("timingNotes").style.display = '';
	document.getElementById("addOpeneingTimes").style.display = 'none';
	_$id('addTimings').value = 'Yes';
	_$id('openDates').checked = true;
	_$id('daysOpen').checked = true;
	setAllYear('startTime', 'endTime'); //Setting Date 
	checkAllVenueDays(); //Setting all days of week
}

function closeAddTimingsArea() {
	document.getElementById("openDate").style.display = 'none';
	document.getElementById("openDay").style.display = 'none';
	document.getElementById("timingNotes").style.display = 'none';
	document.getElementById("addOpeneingTimes").style.display = '';
	_$id('chooseDate').style.display = '';
	_$id('showDay').style.display = 'none';
	_$id('showDate').style.display = 'none';
	_$id('addTimings').value = 'No';
}

function getVanueCategory(value) {
	if (value == "Other")
		document.getElementById("specifyVenueCategory").style.display = '';
	else
		document.getElementById("specifyVenueCategory").style.display = 'none';
}

function popupCalendar(obj) {
	var openDateFrom = new Date();  
	 var opentDateTo = new Date();
	 //opentDateTo.setMonth(openDateFrom.getMonth()+1);
	 document.add_venue_form.startTime.value =  openDateFrom.print("%d/%m/%Y");   
	 document.add_venue_form.endTime.value =  opentDateTo.print("%d/%m/%Y");
	 document.getElementById(obj).onclick();	 
}

function setDateCriteria(inputVal) {
	if(inputVal != null){
		_$id('dateCriteria').value = inputVal;
	}
}
function setAllYear(objWhen, objTo) {
	var currDateObj = new Date();
	var yr = currDateObj.getFullYear();
	var stDate = "1/1/"+yr;
	var enDate ="31/12/"+yr;
	_$id(objWhen).value = stDate;
	_$id(objTo).value = enDate;
}
function venueEventValidation() {
	// TODO
}

/*//For Event Pagination
function showPagedEvents(pageNo) {
	var venueId = _$id('venueId').value
	UserManager.eventPager(pageNo,venueId, eventPagerHandler);
}

function eventPagerHandler(source) {
	var obj = _$id('eventPager');
	_$id('firstListOfEvents').style.display = 'none';
	obj.innerHTML = source;
	
}*/

/*function showShortEventDetail(titleId) { //For a short ajax based detail of event in an overlay.	
	if(document.add_event_form.quickAddEventId) {
		document.add_event_form.method.value="showEventDetail";
		document.add_event_form.titleId.value=titleId;
		document.add_event_form.submit();		
	}else {
		UserManager.showEventDetail(titleId, showEventDetailHandler);
	}
}


function showEventDetailHandler(source) {
	var obj = _$id('shortEventDetail');
	if(source == "error") {
		displayErrorMessage("Error processing your request.");
	} else {
		obj.style.display = '';
		obj.innerHTML = source;
	}
}*/

function closeEventDetailLayer(divId) {
	var obj = document.getElementById(divId);
	if(obj != null) 
		obj.style.display = 'none';
}						 
//End For Add Venue Submission 

//Get All counties

function getCounties(countryId) {
	UserManager.getCountiesByCountryId(countryId, getCountyHandler);
}

function getCountyHandler(source) {
	document.getElementById('u8_trf').innerHTML = source;
	/*var obj = _$id('countyDropDown');
	obj.innerHTML = source;
	obj.style.display = '';
	if(source == "Error")
		obj.style.display = 'none';*/
}

// Shaheer -- 2008 09 15

function showToolTip(obj) {
	obj = _$id(obj);
	var pos = findPos(obj);
	_$id('openLayer').style.left = pos[0]  + 20 + 'px'; 
	_$id('openLayer').style.top =  pos[1] + 'px';
	_$id('openLayer').style.display = '';
	_$id('openLayer').style.position = 'absolute';
}

function hideToolTip(obj) {
	_$id('openLayer').style.display = 'none';
}
function submitViaEnter(evt, id) {
    evt = (evt) ? evt : event;
    var target = (evt.target) ? evt.target : evt.srcElement;
    var charCode = (evt.charCode) ? evt.charCode :
        ((evt.which) ? evt.which : evt.keyCode);
    if (charCode == 13) {
		if(id =='resetPass'){
			//calling ajax submit method.
			doResetPassAjax();
			return false;
		}
		else if(id =='search'){
			//calling ajax submit method.
			lowerSearchEvents();
			//return false;
		}else if(id == 'LocationSpecified'){
			defaultLocationSpecified();
			return false;
		}
    }
	return true;
}
//End get All Counties

function saveGeoLocation(){
	var lat = _$id('latitude').value;
	var lng = _$id('longitude').value;
	UserManager.saveGeoLocation(lat, lng, saveGeoLocationHandler);
}
function saveGeoLocationHandler(source){
	if(source != "OK"){
		alert("Warning: Error in Processing GEO Location");
	}
}
function  showProgress(){
	var obj = document.getElementById('dv_progress')
	if(obj != null){
		obj.style.display='inline';
	}
}
function  hideProgress(){
	var obj = document.getElementById('dv_progress')
	if(obj != null){
		obj.style.display='none';
	}
}

function storeSearchLocation(searchLocation) {
	UserManager.storeSearchLocation(searchLocation, storeSearchLocationHandler);
}
function storeSearchLocationHandler(source) {
	if(source == "error") alert("Error strong location in session...");
}


String.prototype.capitalize = function(){ //v1.0
    return this.replace(/\w+/g, function(a){
		return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
}
function openTitleGroup(obj, linkObj){
	obj.style.display='';
	linkObj.style.display='none';
}

var SEARCH_LOC_ALL_UK = 'United Kingdom';

function populateSearchLocationFromCookie(){
	var currLoc = getCookie("currentSearchLocation");
	var locObj = _$id('searchLocation');

	if(currLoc != ""){
		locObj.value = currLoc;
	}else {
		locObj.value = SEARCH_LOC_ALL_UK;
	}
}

function fetchSearchLocationFromCookie(){
	var currLoc = getCookie("currentSearchLocation");
	var locObj = _$id('searchLocation');

	if(currLoc != ""){
		return currLoc;
	}else {
		return SEARCH_LOC_ALL_UK;
	}
}
function backToSearch(){
	_$id('gdp_form').submit();
}
function uploadFiles() {
  var image = dwr.util.getValue('imageFile');
  UploadDownload.uploadFiles(image,function(data) {
    dwr.util.setValue('image', data);
  });
}
function finishProgress(){
	var pbt = _$id('progressBarText');
	if(pbt){
		pbt.innerHTML = 'upload progress: 100%';
	}
	var pbtc = _$id('progressBarBoxContent');
	if(pbtc){
		pbtc.style.width = parseInt(100 * 3.5) + 'px';
	}
}

function getCroppedImg(){
	SNG_closeFancyBox();
	var image2 = _$id('image2');
	if(image2 == null || image2.value == ''){
		return;
	}
	image2  = image2.value;
	
	var iPath =  '/venueImages/images/'+ image2 + '?state='+new Date().getTime();
	showDivs('div_venue_img')
	hideDivs('div_upload')
	hideDivs('div_crop')
	showDivs('img_options')
	var objImg = _$id('venue_img');
	objImg.src=iPath;
	objImg.style.width='';
	objImg.style.height='';
	objImg.style.display='';
	//$('.SNG_edNoImage').hide();
	$('.SNG_edImgCont').removeClass('SNG_edImgContNoImg');
	showControls(false);
}


function resetProgressBar(){
	_$id('progressBar').style.display='none';
	_$id('progressBarBoxContent').style.width='0px';
	_$id('uploadbutton').disabled = false;
    _$id('file1').disabled = false;
    hideFileSection();
	_$id('frm_upload').reset();
	
}
function hideCropDiv() {
	
	if(qaImage) {
		qaImage = false;		
		hideDivs('div_crop');
	    divCrop = _$id('crop_div'); 
	    deleteNodes(divCrop);
	    createCropElement(divCrop);
	    if(_$id('uploadImage')) _$id('uploadImage').disabled = false;
	} else {
		if(editFlag){
			editFlag= false;
			_$id('div_crop').style.display='none';
		}else{
			resetProgressBar();
			hideDivs('div_crop');
			var divCrop = _$id('crop_div');
			deleteNodes(divCrop);
			createCropElement(divCrop);
			clearSession(_$id('image1').value, _$id('image2').value);
			hideFileSection();
			
			if(_$id('isEventSubmission').value=="true"){
				showDivs('upload_link');
			}else{
				if(imgs && imgs.length == 0){
					showDivs('upload_link');
				}	
			}
		}
	}
	
	if(!qaImagecropped) {
    	if(_$id('uploadImage'))
     	   _$id('uploadImage').disabled = false;
    }
	
}
function backToUpload(){
	if(qaImage) {
		qaImage = false;		
		hideDivs('div_crop');
	    divCrop = _$id('crop_div'); 
	    deleteNodes(divCrop);
	    createCropElement(divCrop);
		return false;
	}
	
	if(editFlag){
		editFlag= false;
		_$id('div_crop').style.display='none';
	}else{
	resetProgressBar();
	var divCrop = _$id('crop_div');
	deleteNodes(divCrop);
	createCropElement(divCrop);
	clearSession(_$id('image1').value, _$id('image2').value);
	hideFileSection();
	SNG_showUploadDlg();
	}
	
	
}

function deleteNodes(cell)
{
	if ( cell.hasChildNodes() )
	{
    	while ( cell.childNodes.length >= 1 )
    	{
        cell.removeChild( cell.firstChild );      
    	}
	}

}
function createCropElement(parent){
var newNode = document.createElement("img");
newNode.id="cropbox";
newNode.name="cropbox";
newNode.src='';
parent.appendChild(newNode);
}
function SNG_showUploadDlg(){
	
	editFlag= false;
	resetProgressBar();
	//$('#upload_link').hide();
	//if($('.beFirstToUpload').length > 0){$('.beFirstToUpload').hide();}
	
	//$('#fileUploadError').html('');
	if($('#uploadImage').length > 0) _$id('uploadImage').disabled = true;
	if($('#report').length > 0)
		$('#report').hide();
	$('#div_crop').hide();
	$('#div_upload').show();
	
	divCrop = _$id('crop_div'); 
	$('#file1').val('');
    deleteNodes(divCrop);
    createCropElement(divCrop);
    if(imgs != undefined && imgs!=null && imgs.length>0){
	    imgs[0].isOld="true";
		showImage(0);
    }
}
function clearSessionMoreImage(){
	   	clearSession(_$id('image1').value, _$id('image2').value);
	    document.getElementById('image1').value='';
	    document.getElementById('image2').value='';	
	
} 

var qaImage = false;
var qaImagecropped = false;
function getQuickAddToCrop(imageName,width,height){	 
	 _$id('image1').value = imageName
	 _$id('imageFileName').value=imageName;
	 var objCropBox = parent.document.getElementById('cropbox');
	 objCropBox.style.width=width + 'px'
	 objCropBox.style.height=height + 'px'
	 qaImage = true;
	 getImgToCrop();
	 _$id('image1').value = "";
}

function getImgToCrop(){
	finishProgress();
	var source = ""
	if(_$id('image1'))
		source = _$id('image1').value;
	
	if(source != ""){		
		var iPath = source;
		var imgName = "";
		if(iPath == null || iPath == ""){
			SNG_alert('error getting name');
			return;
		}
		imgName = iPath;
		iPath =  '/venueImages/images/'+ iPath;
		_$id('div_upload').style.display='none';
		//hideDivs('cancelUploadBtn');
		showDivs('backUploadBtn');
		_$id('div_crop').style.display='';
		
		if(_$id('cords') != null){
		_$id('cords').image.value=imgName;
		_$id('cords').x.value=0;
		_$id('cords').y.value=0;
		_$id('cords').w.value=0;
		_$id('cords').h.value=0;
		}
		var cropObj = _$id('cropbox');
		cropObj.src=iPath;
		cropObj.style.display='';
		_$id('div_img').style.display='';
		
		var rW = cropObj.width;
		var rH = cropObj.height;
		
		var cropperXOffset = (cropObj.width-IMAGE_CONTAINER_W)/2;
		var cropperYOffset = (cropObj.height-IMAGE_CONTAINER_H)/2;
		
		if(rW > IMAGE_CONTAINER_W){rW=IMAGE_CONTAINER_W;}
		if(rH > IMAGE_CONTAINER_H){rH = IMAGE_CONTAINER_H;}
			jQuery(function(){
				jQuery('#cropbox').Jcrop({
					aspectRatio: IMAGE_CONTAINER_W/IMAGE_CONTAINER_H,
					setSelect:   [ cropperXOffset, cropperYOffset, cropperXOffset+IMAGE_CONTAINER_W, cropperYOffset+IMAGE_CONTAINER_H ],
					onSelect: updateCoords
				});
			});
		SNG_resizeFancyBox();
	} 
	
	
}

function showDeleteImg(){
	if(!qaImage)
		showDivs('div_delete_pic')
	else {
		qaImage = false;
		hideDivs('div_crop');
	    divCrop = _$id('crop_div'); 
	    deleteNodes(divCrop);
	    createCropElement(divCrop);
	}
}

function deleteImg(image, page){	
	var del= confirm("Are you sure you want to delete this image?");
	if(del) {
		UserManager.delTempImages(image, page, delTempImageHandler);
	}

}

function delTempImageHandler(source) {
	var imgList = _$id('imageList');
	if(source == "error") {
		SNG_alert("error deleting image");
	}else if(source == "logout") {
		SNG_alert("Login session expired");
	}else if(source != "") {		
		if(imgList) {
			imgList.innerHTML = source;
		}
	}
}

function delOldImageHandler(source){
	if(source=="error"){
		SNG_alert("error deleting image");
	}else if(source=="logout"){
		SNG_alert("Login session expired");
	}else if(source==""){
		hideDivs('div_delete_pic');

		 var hlen = window.location.href.length;
		 if(window.location.href.substr(hlen-1,hlen)=="#"){
			 window.location.href = window.location.href.substr(0,hlen -1);
		 }else{
			 reloadWindow();
		 }
	}else{
		SNG_alert("error deleting image");
	}
	
}

function cancelShowDelete(){
	_$id('div_delete_pic').style.display='none';
}
function deleteImage(image1, image2){
	if(imgs!=null && imgs.length > 0&& imgs[imgCounter].isOld=="true"){ //If image is added prevsly.
		UserManager.deleteOldImage(imgs[imgCounter].imageId, delOldImageHandler);
	}else{//If image is just added (delete original and added image)
		UserManager.deleteImage(image1, image2, deleteImageHandler)
	}
}
function deleteImageHandler(source){
	if(source == null || source == "error"){
		SNG_alert("error deleting image");
	}

	hideDivs('div_delete_pic');
	 var hlen = window.location.href.length;
	 if(window.location.href.substr(hlen-1,hlen)=="#"){
		 window.location.href = window.location.href.substr(0,hlen -1 );
	 }else{
		 reloadWindow();
	 }
}
function reloadWindow(){
	window.location.href=window.location.href;
}
function acceptImg(entityId, image1, image2){
	UserManager.acceptImage(entityId, image1, image2, acceptImgHandler)
}
function acceptImgHandler(source){
	if(source == null || source =="error"){
		SNG_alert("error acception image");
		return;
	}
	SNG_closeFancyBox();
	//if(imgs.length == 1 && imgs[0].imageType == "lobbyImage"){
	//	imgs.pop();
	//}
	newValue = imgs.length;
	imgs.reverse();
	if(editFlag){
		newValue = newValue -1;
	}

	var infos = source.split("/");
	imgs[newValue] = new ImageInfo("/venueImages/images/"+infos[0],infos[2], infos[3], "1","false", infos[1], infos[4]);
	imgs.reverse();
	showImage(0);

}

function acceptImageOnClick(){
	acceptImg(_$id('entityID').value,_$id('image1').value, _$id('image2').value);
}

function editImg(image2){
	editFlag = true;
	UserManager.editImage(editFlag, image2, editImgHandler)
}
function editImgHandler(source){
	if(source == null || source == "error"){
		SNG_alert('error editimg image');
		return;
	}
	_$id('imageToDelete').value=_$id('image2').value;
	showDivs('div_crop');
	//showDivs('cancelUploadBtn');
	hideDivs('backUploadBtn');
	hideDivs('div_upload')
}
function reportUnsuitableImg(img, reportText, venueName, venueId, titleName, titleId){
	if(reportText.length == 0){
		SNG_alert('Please tell us why you find this picture inappropriate');
		return;
	}else if(reportText.length > 4000){
		SNG_alert('text should not bigger then 4000 characters');
		return;
	}
	UserManager.reportUnsuitableImgage(img.imageName, reportText, venueName, venueId, titleName, titleId, reportUnsuitableImgHandler)
}
function reportUnsuitableImgHandler(source){
	if(source == "error"){
		SNG_alert("Error processing your request");
	}
	hideDivs('div_report_pic');
	showDivConfirmReport(imgs[imgCounter].imageName);
}
function showDivReport(img){
	_$id('report_pic').src=img.imageName;
	_$id('img_report_txt').value='';
	_$id('div_report_pic').style.display='';
}

function showDivConfirmReport(img){
	_$id('div_confirm_report').style.display='';
	_$id('div_confirm_report_pic').src=img;
}
function hideDivConfirmReport(img){
	_$id('div_confirm_report').style.display='none';
	_$id('div_confirm_report_pic').src='';
}
function stopUpload(){
	window.clearTimeout(timeOut)
	cntx = document.getElementById('cntx');
	if(cntx != null) cntx = cntx.value;

	removeBack('target_upload', cntx + '/images/spacer.gif');
	if(navigator.appName == "Microsoft Internet Explorer")
	{
		window.document.execCommand('Stop');
	}else{
		window.stop();
		
	}
	
}
function clearSession(image1, image2){
	if((image1!=null && image1!="") || 
			(image2!=null && image2!="")){
	
		UserManager.clearSession(image1, image2, clearSessionHandler)
	}
}
function clearSessionHandler(source){
	if(source == "error"){
		//alert(source);
	}
}
function resetUpload(){
	stopUpload();
	resetProgressBar();
}
function validateImage(image_file)
{
var extensions = new Array("jpg","jpeg","gif","png","bmp");
var image_length = image_file.length;
var pos = image_file.lastIndexOf('.') + 1;
var ext = image_file.substring(pos, image_length);
var final_ext = ext.toLowerCase();
for (i = 0; i < extensions.length; i++)
{
	if(extensions[i] == final_ext)
	{
	return true;
	}
}
	return false;
}
function CreateDelegate(contextObject, delegateMethod)
{
    return function()
    {
        return delegateMethod.apply(contextObject, arguments);
    }
}

function img_onload()
{
	var srcImg = _$id(imageIdent);
	var srcW = this.width;
	var srcH = this.height;
	var d_w=srcW;//IMAGE_CONTAINER_W;
	var d_h=srcH;//IMAGE_CONTAINER_H;
	var cnt_w=0,cnt_h=0;
	
	if(imageIdent == 'report_pic' || imageIdent == 'div_confirm_report_pic'){
		cnt_w=173;
		cnt_h=130;
	}else{//venue_img case
		cnt_w=IMAGE_CONTAINER_W;
		cnt_h=IMAGE_CONTAINER_H;
	}
		if(d_w > cnt_w){d_w=cnt_w;}
		if(d_h > cnt_h){d_h=cnt_h;}
	
		var thumbNail = CJ_Image.Calculate({
		srcWidth: srcW,
		srcHeight: srcH,
		destWidth:  d_w,
		destHeight: d_h,
		method: "fit"
	});

	var rW = thumbNail.width;
	var rH = thumbNail.height;
	srcImg.width=rW;
	srcImg.height=rH;
	if($('#venue_img ').length > 0){
		$('#venue_img ').vAlign();
	}
	
	if($('#userImage').length > 0 && imageIdent == 'userImage'){
		$('#userImage').vAlign();
	}
}
var imageIdent = '';
function scaleMyImage(srcImg, id) {
imageIdent = id;
var nwImg = new Image();
nwImg.onload = CreateDelegate(nwImg, img_onload);
nwImg.src = srcImg.src+'';

}

function getImgesList(){
	var cropDiv =_$id('div_crop');
	var divCrop = _$id('crop_div');
    if(cropDiv) {    	 
		 cropDiv.style.display='none';
		 _$id('div_upload').style.display='none';
		 _$id('upload_link').style.display='';
		 resetProgressBar();
		 deleteNodes(divCrop);
	   	 createCropElement(divCrop);		
		 hideFileSection();		 
	} 
   
    if(qaImage) {
    	qaImage = false;
    	qaImagecropped = true;
    	if(_$id('uploadImage'))
    	   _$id('uploadImage').disabled = true;
    }
    
    if(!qaImagecropped) {
    	if(_$id('uploadImage'))
     	   _$id('uploadImage').disabled = false;
    }
}
function hideFileSection(flag){
	if(flag){
	_$id('div_file').style.display='none';
	_$id('p_cert').style.display='none';
	//_$id('upload_statement').style.display='none';
	
	}else{
	_$id('div_file').style.display='';
	_$id('p_cert').style.display='';
	//_$id('upload_statement').style.display='';
	}
}
function showControls(flag){
	if(flag){		
		//showDivs('report');
		showDivs('nav_control');
	}else{

		if(imgs && imgs.length == 0){
			showDivs('tbl_venue_img');
		}
	}
}

function deleteQAVenue(venueId) {  
	var del= confirm("Are you sure you want to delete this venue?");
	if(!del) return false;
	var obj =  _$id("quickAdd_" + venueId);
    UserManager.delQuickAddVenue(venueId, 
    	function(source){
		 	if(source == "error") {
		 		errorMessages('errorDiv', 'Error deleting venue');
		 	}  else if(obj) {
	        	obj.style.display='none';
	        }
		}
    );
}

function deleteQAEvent(eventId) {   
	var del= confirm("Are you sure you want to delete this event?");
	if(!del) return false;
	var obj =  _$id("quickAdd_" + eventId);
	UserManager.delQuickAddEvent(eventId, 
    	function(source){
		 	if(source == "error") {
		 		errorMessages('errorDiv', 'Error deleting event');
		 	}  else if(obj) {
	        	obj.style.display='none';	        	
	        }
	
		}
	);
}

function removeBack(frame, URL) {
	
	var IFrameObj = document.getElementById(frame);
	if (IFrameObj.contentDocument) {
		// For NS6
		IFrameDoc = IFrameObj.contentDocument;
	} else if (IFrameObj.contentWindow) {
			//	For IE5.5 and IE6
		IFrameDoc = IFrameObj.contentWindow.document;
	} else if (IFrameObj.document) {
		// For IE5
		IFrameDoc = IFrameObj.document;
	} else {
		return true;
	}

	IFrameDoc.location.replace(URL);
	return false;
}

function ImageInfo(imageName,nick,profileName, deleteable, isOld, imageId, uploadDate, imageType) {
	this.imageName=	imageName;
	this.nickName =	nick;
	this.profileName = profileName
	this.deleteable = deleteable;
	this.isOld = isOld;
	this.imageId = imageId;
	this.uploadDate = uploadDate;
	this.imageType = imageType;
}

function reportUnsuitableUserImg(imageLink, userProfilelink, reportText){
	if(reportText.length == 0){
		SNG_alert('Please tell us why you find this picture inappropriate');
		return;
	}else if(reportText.length > 4000){
		SNG_alert('text should not bigger then 4000 characters');
		return;
	}
	UserManager.reportUnsuitableUserImg(imageLink, userProfilelink, reportText,
			function(source) {
				$('#div_report_pic').hide();
				$('#div_confirm_report').show();	
			}			
	);
}

function reportUnsuitableProfile(userProfilelink, reportText){
	if(reportText.length == 0){
		SNG_alert('Please tell us why you find this profile inappropriate');
		return;
	}else if(reportText.length > 4000){
		SNG_alert('text should not bigger then 4000 characters');
		return;
	}
	UserManager.reportUnsuitableProfile(userProfilelink, reportText,
			function(source) {
				$('#report_profile').hide();
				$('#confirm_report').show();	
			}			
	);
}
function isNumeric(strString)
   //  check for valid numeric strings	
   {
		 
   var strValidChars = "0123456789.";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
			
   return blnResult;
   }
	 
 function removePound(objName) {
  var objPrice = _$id(objName);
	if(objPrice){
		if(objPrice.value.indexOf('') !=-1 ){
			objPrice.value = objPrice.value.replace("","");
		}
	}
	
}

function removeNotes(objName) {
  var objPrice = _$id(objName);
	if(objPrice && objPrice.value == '<Notes>'){	
			objPrice.value = ''
		
	}
	
}
function removeZero(objName) {
  var objPrice = _$id(objName);
	if(objPrice){
		if( trim(getValue(objName)) == "0" ){
			objPrice.value = "";
		}
	}
	
}
function Asc(Str)
{
	return Str.charCodeAt(0);
}
function priceValidator(strString)   {
	
   var strValidChars = "0123456789. -,�";
   var strChar;
   strString = strString.replace("","");
   if (strString.length == 0) return false;
    for (i = 0; i < strString.length;  i++){
      strChar = strString.charAt(i);
	  if(Asc(strChar) == 163){
		  continue;
		  }
	  //alert(strChar+' - '+Asc(strChar));
      if (strValidChars.indexOf(strChar) == -1) {         
         return false;
      }
    }
   return true;
}

function validatePriceField(objName) {
   if( objName == 'fullPrice' &&  !priceValidator(trim(getValue('fullPrice')))) {
     	displayErrorMessage("The characters in the pricing field need to be numeric");
     	highlightTextField(_$id(objName));
     	_$id(objName).focus();
     	return false;
	} else if( trim(getValue(objName)).length > 0 &&  !priceValidator(getValue(objName))) {
       	displayErrorMessage("The characters in the pricing field need to be numeric");
       	highlightTextField(_$id(objName));
       	_$id(objName).focus();
       	return false;
	}
	return true;
}

function validateEventPrice(add_event_form) {

	var priceOpt = getCheckedValue(add_event_form.addmissionFee);
	if(priceOpt == 1) {		
	    if(!validatePriceField('fullPrice')) return false;	      
		if(!validatePriceField('child')) return false;
		if(!validatePriceField('familyPrice')) return false;
		if(!validatePriceField('memFriPrice')) return false;
		if(!validatePriceField('concession'))  return false;
		if(!validatePriceField('seniorCitizen')) return false;
		if(!validatePriceField('groupPrice')) return false;				
		     	
	}
	return true;

}
function removeDefaultData() {
        removePound('fullPrice');
		removePound('child');
		removePound('familyPrice');
		removePound('memFriPrice');
		removePound('concession');
		removePound('seniorCitizen');
		removePound('groupPrice');
		
		removeZero('child');
		removeZero('familyPrice');
		removeZero('memFriPrice');
		removeZero('concession');
		removeZero('seniorCitizen');
		removeZero('groupPrice');
		
		removeNotes('fullPriceNotes');
		removeNotes('childNotes');
		removeNotes('familyPriceNotes');
		removeNotes('memFriPriceNotes');
		removeNotes('concessionNotes');
		removeNotes('seniorCitizenNotes');
		removeNotes('groupPriceNotes');
		displayRegularText(_$id('tags'),'Tags')
		displayRegularText(_$id('category'),' Specify event category')
}

function validateEventTimingRows() {
  var allDays;
  var allDates;
  var allTime;
  var timingRows=''; 
  var isError = false;
  for(var i=1; i<=addId; i++ ) {
    if( i > 1 ) timingRows = timingRows + '~'
    allDates = getCheckedValue(_name('openDates_'+ i));    
    if( allDates == 2 ){
        if(compareGr8erDates(_$id('whenfrom_'+i).value, _$id('whento_'+i).value))
	           timingRows = timingRows + getDateDMY(_$id('whenfrom_'+i).value) + '|' + getDateDMY(_$id('whento_'+i).value) ;
	     else {
     	      SNG_alert("End Date should be greater or equal to start Date");
     	      isError =true;
	     }  
    
    } else {
      timingRows = timingRows + onGoingDates(i);
    }
  
    allDays =  getCheckedValue(_name('openAllWeek_'+ i));        
    if( allDays == 2 ){	
      timingRows = timingRows + '|' +  getDaysValue(i);     
    } else {
      timingRows = timingRows + '|' + 'Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday'
    }
    
    allTime =  getCheckedValue(_name('hour_'+ i));
    if( allTime == 1 ){
      timingRows = timingRows + '|' + 'TBC' + '|' + 'TBC';
    } else {
      var timings = getTimingsValue(i);
      if(timings.length > 0 ) 
         timingRows = timingRows + '|' +  timings ;
       else isError =true;  
    }
	timingRows = timingRows + '|' + _$id('currentRowId_'+i).value;
  }
  
  if(!isError) SNG_setValue('timingRows',timingRows);  
  return !isError;
}


function getDateDMY(dateMDY){
	var thisDate = new Date(dateMDY);
	var day   = thisDate.getDate();
    var month = thisDate.getMonth() + 1;
    var year  = thisDate.getYear();
 	if (year < 2000) year += 1900;
 	
 	return day+"/"+month+"/"+year;
}



function onGoingDates(rowId) {	
	
	var currDateObj = new Date();
	var yr = currDateObj.getFullYear();
	var stDate = "01/01/"+yr;
	var enDate ="31/12/"+yr;
	return stDate + '|' + enDate;
	//_$id('whenfrom_'+rowId).value = stDate;
    //_$id('whento_'+rowId).value = enDate;
}

function getDaysValue(rowId){
   var days = _name('chkChooseDay_' + rowId);
   var daysValues= '' ;
   
	for(i = 0;i <days.length; i++){
	
		if(days[i].checked){
           if( daysValues != '' ) daysValues = daysValues + ', '
		   daysValues = daysValues + days[i].value;
		} 
    }
    if( daysValues == '' ) daysValues= ' ' ;
	return daysValues;
}
function getTimingsValue(rowId){
   var startHour = _$id('startHour_' + rowId);
   var startMins = _$id('startMin_' + rowId);
   var startFormat = _$id('startFormat_' + rowId);
   var endHour = _$id('endHour_' + rowId);
   var endMins = _$id('endMin_' + rowId);
   var endFormat = _$id('endFormat_' + rowId);
   var time='';
  
   if(startHour.value == '-' &&  startMins.value == '-' && startFormat.value == "-") {
	  var vnTop = $('#endFormat_' + rowId).offset().top;
      SNG_venueAddVMsg(vnTop, "Please select start time");      
      return '';    
      
   } else if(startHour.value == '-' ) {	    
     var vnTop = $('#endFormat_' + rowId).offset().top;
	 SNG_venueAddVMsg(vnTop, "Please select start time hour");
     return '';
     
   } else if(startMins.value == '-' ) {
	 var vnTop = $('#endFormat_' + rowId).offset().top;
 	 SNG_venueAddVMsg(vnTop, "Please select start time minutes");  
     return '';
     
   } else  if( startFormat.value == '-' ) {
		 var vnTop = $('#endFormat_' + rowId).offset().top;
	 	 SNG_venueAddVMsg(vnTop, "Please select start time meridian (AM/PM) ");  
	     return '';
	    
   } else {	   
	   time = startHour.value + ':' + startMins.value  +' ' +  startFormat.value ;   
   }
      
   if(endHour.value == "-" && endMins.value == "-" && endFormat.value == "-" ) {
	   time  = time + '|TBC';   
   } else if(endHour.value == '-') {
    	 var vnTop = $('#endFormat_' + rowId).offset().top;
    	 SNG_venueAddVMsg(vnTop, "Please select end time hour");  
	     return '';          
   } else if( endMins.value == '-' ) {
	  var vnTop = $('#endFormat_' + rowId).offset().top;
	  SNG_venueAddVMsg(vnTop, "Please select end time minutes");  
	  return '';   
	  
   } else if(endFormat.value == '-' )   {
	   var vnTop = $('#endFormat_' + rowId).offset().top;
	   SNG_venueAddVMsg(vnTop, "Please select end time meridian (AM/PM) ");  
	   return ''; 
   } else {
		 time =  time  + '|' +  endHour.value + ':' + endMins.value + ' ' + endFormat.value ;       
   }    
   return time;
}

/*function removeHighlighting(element) 
{
    if(element.style)
     	element.style.border='';
}*/

/*function clearEventField(_form) {
	 removeHighlighting(_$id('eventName'));
	 removeHighlighting(_$id('descp'));
	 removeHighlighting(_$id('categoryId'));
	 removeHighlighting(_$id('category'));
	 removeHighlighting(_$id('fullPrice'));
	 removeHighlighting(_$id('child'));
	 removeHighlighting(_$id('familyPrice'));
	 removeHighlighting(_$id('memFriPrice'));
	 removeHighlighting(_$id('concession'));
	 removeHighlighting(_$id('seniorCitizen'));
	 removeHighlighting(_$id('groupPrice'));
	 if(_form.length) {
	   for(var i=0; i<_form.length; i++)
     	 removeHighlighting(_form[i]);
	 }
 
}*/
/*function validateEventFormData(_form){	
   clearMessage();   
   clearEventField(_form);
   var catObj = _form.categoryId;
   var categoryId = catObj.options[catObj.selectedIndex].value;
   if(_$id('eventName').value <=0 ){
	   displayErrorMessage("Please enter event name");
	    highlightTextField(_$id('eventName'));
	    _$id('eventName').focus();
   }else
   if(_$id('descp').value <= 0){
	   displayErrorMessage("Please enter description");
	   highlightTextField(_$id('descp'));
	   _$id('descp').focus();
   }else 
   if(_$id('shortDescription').value.length > 75){
	   displayErrorMessage("Short description can not be more then 75 characters.");
	   highlightTextField(_$id('shortDescription'));
	   _$id('shortDescription').focus();
   }else
   if(categoryId == 0){
   	   displayErrorMessage("Please select category");
   	   highlightTextField(_$id('categoryId'));
   	   _$id('categoryId').focus();
   } else
   if( categoryId == -1 && (_form.category.value == ' Specify event category' || trim(_form.category.value) == '') ){
   	   displayErrorMessage("Please enter other category");
   	   highlightTextField(_$id('category'));
   	   _$id('category').focus();
   } else if(!validateEventPrice(_form)) {
	 return;
   } else if(!validateEventTimingRows()) {
     return;
   } else {
      removeDefaultData();
      _form.method.value="eventDetail";
      _form.submit();   
   }	  
   
}*/
function backStep(id) {   
	if(id > 0)
	   addVenue_Event(id);
	else  editVenueForm();

}

// new layout page changes
var rollImage = new Array();
// find now image
rollImage[0]= new Image(84,38);  // width,height
//rollImage[0].src = "images/find-now-home.jpg";
rollImage[1] = new Image(83,38);
//rollImage[1].src = "images/Find-now_home_rollover.jpg";
// add event venue image
rollImage[2]= new Image(211,30);  // width,height
//rollImage[2].src = "images/add-your-venue-or-events.jpg";
rollImage[3] = new Image(211,30);
//rollImage[3].src = "images/add-your-venue-or-events_rollover.jpg";

rollImage[4]= new Image(84,38);  // width,height
//rollImage[4].src = "images/Find-now.jpg";
rollImage[5] = new Image(83,38);
//rollImage[5].src = "images/Find-now_rollover.jpg";

function swapImage(obj,index){
var cntx = document.getElementById('cntx');
if(cntx!= null)cntx = cntx.value;

rollImage[0].src = cntx+"images/find-now-home.jpg";
rollImage[1].src = cntx+"images/Find-now_home_rollover.jpg";
rollImage[2].src = cntx+"images/add-your-venue-or-events.jpg";
rollImage[3].src = cntx+"images/add-your-venue-or-events_rollover.jpg";
rollImage[4].src = cntx+"images/Find-now.jpg";
rollImage[5].src = cntx+"images/Find-now_rollover.jpg";
obj.src = rollImage[index].src;
    return true;
}

// search method of result.vm

function resetOldValues(_form) {
	_form.locationProvided.value = '1';
	if( _form.sortType.value != '3' )
		_form.sortType.value = '0';
	_form.searchInDescription.value = 'false';
	_form.categoryId.value = '0';
	_form.subCategoryId.value = '0';
	_form.brandCategoryId.value = '0';
	_form.displayFutureEvents.value = 'true';
	_form.displayFutureResultLink.value = 'false';
	_form.pageId.value = '0';
}

function searchInDescription() {
     var _form = document.gdp_search_form;
     setSearchCriteria();
     _form.searchInDescription.value = "true";
     _form.submit();
}

function searchExactMatchVenues() {
   var _form = document.gdp_search_form;   
   setSearchCriteria();
  _form.pageId.value="0" ;
  _form.sortType.value = "1";
  _form.method.value="search"; 
  _form.exactMatchVenues.value = "true" ;
  _form.submit();
  submitOK = false;  
} 
function searchExactMatchVenuesMapView() {
   var _form = document.gdp_search_form;   
   setSearchCriteria();
  _form.pageId.value="0" ;
  _form.sortType.value = "1";
  _form.method.value="search"; 
  _form.exactMatchVenues.value = "true" ;
	_form.showAllCategories.value="No";
  _form.submit();
  submitOK = false;  
} 



function showEventDetail(titleId, venueId) {
  var _form = document.gdp_search_form;  
  setSearchCriteria();
  _form.titleId.value=titleId;
  _form.venueId.value=venueId;
  _form.method.value="getEventDetail";
  _form.submit();
}
function showVenue(venueId) {   
    var _form = document.gdp_search_form;
    setSearchCriteria();
   _form.venueId.value=venueId; 
   _form.method.value="getVenue";
   _form.submit();
 }  

function searchEventsWithInc(dayInc) {  

  var _form = document.gdp_search_form;
  setSearchCriteria();
  _form.pageId.value="0";
  _form.dayIncrement.value = dayInc;
  _form.submit();  

}

function searchEventsForCategory(categoryId) {

   var _form = document.gdp_search_form;
   setSearchCriteria();
   _form.pageId.value="0" ;
  _form.categoryId.value=categoryId;
  _form.subCategoryId.value = "0"
  _form.submit();   
  
}

function searchEventsForSubCategory(subCategoryId) {
     var _form = document.gdp_search_form;     
     setSearchCriteria();
     _form.pageId.value="0" ;
     _form.subCategoryId.value = subCategoryId ;     
     _form.submit();   
 } 

  function searchEventsForSubCategoryMapView(subCategoryId,categoryId) {
     var _form = document.gdp_search_form;     
     setSearchCriteria();
     _form.subCategoryId.value = subCategoryId ;   
		 _form.categoryId.value=categoryId;
		 _form.showAllCategories.value="Yes";
		 _form.pageSize.value ="10";
     _form.submit();   
 } 
 
function searchEventsForCategoryMapView(categoryId) {

   var _form = document.gdp_search_form;
   setSearchCriteria();
  _form.categoryId.value=categoryId;
	_form.showAllCategories.value="Yes";
	_form.pageSize.value ="10";
  _form.submit();   
  
}
 
function showPage(page) {            
      var  _form = document.gdp_search_form;
      setSearchCriteria();
      _form.pageId.value=page;      
      _form.submit();
      return true;
   
}
function searchSortBy(sort) {        
      var  _form = document.gdp_search_form;
       setSearchCriteria();
       _form.pageId.value="0" ;
      _form.sortType.value = sort;
      _form.submit();
      return true;
}

function searchLocations(_form) {        
      var  _form = document.gdp_search_form;
      setSearchCriteria();
     _form.method.value="loctions";
     _form.submit();
      return true;
}

function changPageSize(pageSize) {        
	var _form = document.gdp_search_form;
	setSearchCriteria();   
	_form.pageId.value="0" ; 
	_form.pageSize.value = pageSize;
	rememberPref(pageSize);
	_form.submit();
	//return true;
}

function removeSpecialChars(searchString) {
	    var sb = '';
	    var i, c, code;
	    var length = searchString.length;	    
	    for (i = 0; i <length;  i++) {
	        c = searchString.charAt(i);	       
					
	       if (c == '\\' || c == '+' || c == '!' || c == '('  || c == ')' || c == ':' || c == '#' 
	        || c == '^' || c == '[' || c == ']'  || c == '\"' || c == '{' || c == '}' || c == '<' 
	       	|| c == '~' || c == '*' || c == '?'  || c == '|'  || c == '&' || c == '%' || c == '>'
	       	|| c == '.' || c == '@' || c == '\'' || c == '`' || c == '$' || c == '!' || c == ';' 
			|| c == '=' || c == '/' || c == ',' ) {	       	
             // 45 for '-' and 95 for '_'  =*|\-_)(*&^%$#@!~`<>,.?/"':;
	      } else {
	         sb = sb + c;
	         
	      }
	   }
	   return sb;	    
	    
}

function setWeekendDates(_form) {
     var dateFrom = new Date();  
     var dateTo = new Date();
	 var FRIDAY = 5;
	 var SATURDAY = 6 ;
	 var SUNDAY = 0;	 	 		   
	 
	  var day = dateFrom.getDay();
	  if( day > SUNDAY && day  <= FRIDAY)  {
	     day = FRIDAY - day;
		 dateFrom.setDate(dateFrom.getDate()+day);
		 dateTo.setDate(dateFrom.getDate() + 2);		 
	  } else if(day == SATURDAY) {
    	 dateTo.setDate(dateFrom.getDate() + 1);		 
	  }
	 _form.gdp_whenfrom.value =  dateFrom.print("%d/%m/%Y");   
	 _form.gdp_whento.value =  dateTo.print("%d/%m/%Y");
	 _form.dateCriteria.value = 4;	
	 
}
function setTomorrowDate(_form) {
	var date = new Date();
	var time = date.getTime();
	var when = "";
	var till = "";
	time += Date.DAY; date = new Date(time); 
	when =  date.print("%d/%m/%Y");
	till= when;
	_form.gdp_whenfrom.value = trim(when);
	_form.gdp_whento.value = trim(till);	
	_form.when.value = trim(when);
	_form.till.value = trim(till);
	_form.dateCriteria.value = 3;
}
function setAllDates(gdp_main){
	var val = gdp_main.gdp_when.value;
	val = parseInt(val);
	var date = new Date();
	var time = date.getTime();
	var when = "";
	var till = "";
	when =  date.print("%d/%m/%Y");
	gdp_main.gdp_whenfrom.value = trim(when);
	gdp_main.gdp_whento.value = trim(till);	
	gdp_main.dateCriteria.value = val;	
}
function loadCategoriesCounts(){   
   UserManager.getRefineCategories(false, false, loadCategoriesCountsHandler);
}


function loadCategoriesCountsHandler(source) {
   var obj= _$id('categoriesCounts');
   if( source == "error" ) {
      //displayErrorMessage("Error processing your request.");	   
   } else   {          
     obj.innerHTML = source;
     var obj= _$id('paginationBar');
     if(obj) {
        loadResultPaging();  
     } else {     
        setTimeout('loadResultPaging()', 1100);
     }
   }
	
}

function loadCategoriesCountsMap(){
   UserManager.getRefineCategories(false,false, loadCategoriesCountsHandlerMap);
}
function loadCategoriesCountsHandlerMap(source) {
   var obj= _$id('categoriesCounts');
   if( source == "error" ) {
      //displayErrorMessage("Error processing your request.");	   
   } else   {          
     obj.innerHTML = source;
     var obj= _$id('paginationBar');
     if(obj) {
        loadResultPaging();  
     } else {     
        setTimeout('loadResultPaging()', 2000);
     }
   }
	adjustView();
}
function loadResultPaging(){
   var obj;
   UserManager.getPagination(function(source) {
       if( source == "error" ) {
 		//     displayErrorMessage("Error processing your request.");	   
		} else   {          
     	  obj = _$id('paginationBar');
	      if(obj) obj.innerHTML = source;  
	   }
   });

}

function detailCounter(field,maxlimit) {
	if (field.value.length > maxlimit)  {
		field.value = field.value.substring(0, maxlimit);
	}
}
function addUserDetail(){
	   var userDetail = $("#userDetail").val();	   
	   if(jQuery.trim(userDetail) == '') {
	    	SNG_alert('Please add something about yourself');
	   } else {
			UserManager.updateUserDetail(userDetail, function(source){
				if(source == "logout") {
					SNG_alert('Login session expired');
				} else if(source == "error" ) {
					SNG_alert('Error during update your detail');
				}else if(source == "success") {
				  var area = $("#detailArea");				  
				  area.find("p").html(textToHtml(userDetail));
				  $('#detailBox').hide();
				  area.show();
				}
				
			});
	   }	   
}
function SNG_userLocation(postcode,town){	
	if(town != '') {
		$('#myTown').val(town);
	}	
	if(postcode != '') {
		$('#myPostcode').val(postcode);  	
	}
	
}
function  hideLocationBox() {
	$('#myTown').val($('#myTown').defaultValue);
	$('#myPostcode').val($('#myPostcode').defaultValue);
	$('#locationBox').hide();	 
	$('#locationArea').show();
}

function addUserLocation() {
	var town = $('#myTown').val();
	var postcode = $('#myPostcode').val();
	town = jQuery.trim(town);
	postcode = jQuery.trim(postcode);	
	if(town == $('#myTown').attr("defaultValue"))		
		town = '';
	if( postcode == $('#myPostcode').attr("defaultValue"))
		postcode = '';
	
	
	if(town == '' || postcode == '' ) {
		SNG_alert('Please Enter you location');
	} else {
		UserManager.updateUserLocation(postcode, town, function(source){
			if(source == "logout") {
				SNG_alert('Login session expired');
			} else if(source == "error" ) {
				SNG_alert('Error during update your location');
			} else {						 
				 $('#locationBox').hide();
				 $('#postcodeArea').text(postcode);
				 $('#townArea').text(town);
				 $('#locationArea').show();
				 SNG_UserProfileCompletion();
				 if( source != "success") {
					 var pc = source.split(",");					 
					 load(pc[0], pc[1]);
					 var link = '<a href="javascript:void(0)" onclick="window.open(\''+ $("#cntx").val() +'controller.web?method=getLargeMap&';
					 link += 'latitude='+ pc[0] +'&longitude='+ pc[1] + '&townCity='+ town +  '&postCode='+  postcode;
					 link += '\',\'Large Map\',\'scrollbars=no,resizable=no,width=700,height=500\')">View large map</a>' ;
					 $('#largeMap').html(link);
					 $('#largeMap').show();					 
					 $('#postcode').val(postcode);
					 if($('#alertPostcode').length > 0)
						 $('#alertPostcode').val(postcode);
					 
				 }
				 $('#townCity').val(town);
				 
			} 
			
		});
	}
	
	

}

function textToHtml(string) {
	string = string.replace(/\r\n/g,"<BR/>");
	string = string.replace(/\r/g,"<BR/>");
	string = string.replace(/\n/g,"<BR/>");
	return string;
}
function removeUserBookmark(bookmarkId){		
	UserManager.removeUserBookmark(bookmarkId, function(source){
		if(source == "logout") {
			SNG_alert('Login session expired');
		} else if(source == "error") {
			SNG_alert('Error deleting bookmark.')			 	
		} else {
			$('#myWozzonBookmarks').html(source);
			$(".SNG_srArrow").hover(function () {
			      $(this).addClass("SNG_background");
				  $(this).removeClass("SNG_srArrow");				  
			    },function () {
			      $(this).addClass("SNG_srArrow");
				  $(this).removeClass("SNG_background");				  
			 });
		}
	});
}

function deleteSearchAlert(alertId){
	if(alertId != 0){
		UserManager.deleteSearchAlert(alertId, deleteSearchAlertHandler);
	}else{
		SNG_alert('Error deleting alert.');
	}
}
function deleteSearchAlertHandler(source){
	if(source == "logout") {
		SNG_alert('Login session expired');
	} else if(source == "error") {
		SNG_alert('Error deleting alert.');		
	}else{
		$('#tab3').html(source);
		alertListHover();
	}
}
function addSearchAlert() {
    var pc = $("#alertPostcode");
    if(pc.val() == '')  {
      SNG_alert('Please Enter postcode');
    } else {
    	UserManager.addMyWozzonSearchAlert(pc.val(), $("#alertSearchLink").val() , function(source){
    		if(source == "logout") {
				SNG_alert('Login session expired');
			} else if(source == "error") {
    			SNG_alert('Error adding alert.')			 	
    		} else {
    			$('#tab3').html(source);
				alertListHover();
				SNG_UserProfileCompletion();
    		}
		});
    }
}

function alertListHover() {
		$(".SNG_mwAlert ul li").mouseover(function() {
			$(this).find("a").css('color', '#FFFFFF');
			$(this).css('background', '#C3001F');			 			 
			var src = $(this).find("img").attr("src").replace(".png", "_hover.png");			
			$(this).find("img").attr("src", src);

		});
		
		$(".SNG_mwAlert ul li").mouseout(function() {
			$(this).css('background', '#FFFFFF');
			$(this).find("a").css('color', '#C3001F');		
			var src = $(this).find("img").attr("src").replace("_hover", "");			
			$(this).find("img").attr("src", src);
			
		});	 
		
}

function setSaveSearchAlert(str){
	var obj = _$id('search_alert');
	obj.innerHTML=str;
	obj.style.display='';
}
function setSearchAlert(email){
	
	
	
	if("" != email && checkEmail(email)){
		var searchUrl = alertSearchLink;/*document.location.href;*/
		var sLabel = _$id('lb_search').innerHTML;
		if( _$id('wozzon_header_logStatus').innerHTML.indexOf('logout(1)') == -1){
			if(!_$id('chk_terms').checked){
				//alert('Please accept woZZon Terms & Conditions');
				SNG_displayLoginError($('#termsEmailAlert'), "Please accept woZZon Terms & Conditions");
				return;
			}
		}
		UserManager.setSearchAlert(email, sLabel, searchUrl, setSearchAlertHandler);
		
	}else{
		if("" == email){
			SNG_displayLoginError($('#alert_email'), "Please enter an email address");
		}else if(!checkEmail(email)){
			SNG_displayLoginError($('#alert_email'), "Please enter a valid email address");
		}
	}
}
function searchAlertNewUser(alertEmail, receiveEmail){
	if(alertEmail && alertEmail != ""){
	UserManager.searchAlertNewUser(alertEmail, receiveEmail, searchAlertNewUserHandler);
	}else{
		SNG_alert('Alert email is empty');
	}
}
function searchAlertNewUserHandler(source){
	if(source == 'error'){
		SNG_alert('error creating new account');
	}else{
		//hideDivs('saveSearchAlertPopup');
		SNG_closeFancyBox();
		_$id('response_msg').innerHTML = 'New account created, Welcome email has been sent.'
		//showDivs('search_saved')
		SNG_messagePopup('search_saved');
	}
}
function setAlertMsg(msg){
var alrt_msg = _$id('alrt_msg');
alrt_msg.innerHTML=msg;
showDivs('div_alert');

}

function setSearchAlertHandler(source){
	
	var obj_save =_$id('saveSearchAlertPopup');
	//var search_saved =_$id('search_saved');
	var alrt_eml = _$id('alert_email');
	var login_form =_$id('login_form');
	
	if(source == '1'){//success
	//obj_save.style.display='none';
		SNG_closeFancyBox();
		//search_saved.style.display='';
		SNG_messagePopup('search_saved');
		
		if(login_form.login_email.value != alrt_eml.value) {
			login_form.login_email.value = alrt_eml.value;
			login_form.login_password.value='';
		}
	
	}else if(source == '2'){//Exception occurs
		
		setAlertMsg('Error processing request');
	}else if(source == '0'){
		//wozzon user not found
		searchAlertNewUser(alrt_eml.value, _$id('recv_eml').checked);
		//setAlertMsg('Please enter a valid email address');
	}
	alrt_eml.value='';
	_$id('chk_terms').checked='';
	_$id('recv_eml').checked='checked';
	
}

function trimToDisplay(txt, limit){
	if( txt == null) return "";
	if(txt.length > limit){
		return txt.substring(0,limit) + '..';
	}else{
		return txt;
	}
}
function checkSearchSection(searchObj, locObj){

	if(searchObj.value == searchNameText){
		searchObj.style.color='#999999';
	}
	
	if(searchObj.value== '')
	{
		searchObj.style.color='#999999';
		searchObj.value=searchNameText;
	}

	if(locObj.value == '')
	{	
		locObj.style.color='#000000';
	}else{
		locObj.style.color='#000000';
	}

}
if (typeof(WebToolKit) == "undefined") {
	var WebToolKit = {};
};

WebToolKit.utf8 = {

	encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
		}

		return utftext;
	},

	decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
		while ( i < utftext.length ) {
			c = utftext.charCodeAt(i);
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	}

};

if (typeof(String.prototype.utf8encode) == "undefined") {
	String.prototype.utf8encode = function () {
		return WebToolKit.utf8.encode(this);
	};
};

if (typeof(String.prototype.utf8decode) == "undefined") {
	String.prototype.utf8decode = function () {
		return WebToolKit.utf8.decode(this);
	};
};

// JavaScript Document( Created By Ammar )
var MW_NAME = 'Name' 
var MW_NICKNAME = 'Nickname'
var MW_STREET = 'Street'
var MW_TOWNCITY = 'Town City'
var MW_POSTCODE = 'Postcode'
var MW_COUNTY = 'County'
var MW_COUNTRY = 'Country'		
var MW_MOBILENUM = 'Mobile Number'	
var MW_NEWEMAIL = 'New email'
var MW_CUR_PASS = 'Current password'
var MW_NEW_PASS = 'New password'
var MW_CONF_PASS = 'Confirm new password'
var MW_CONF_NEWEMAIL = 'Confirm new email'	
var VEP_EMAIL = 'Email'
var VEP_PASSWORD = 'Password'
var VEP_CONF_PASS = 'Confirm password'	
var VEP_FIRST_NAME = 'First Name' 	
var VEP_LAST_NAME = 'Last Name' 	
var VEP_PAYPAL_EMAIL = 'Your PayPal Email Address'	
var VEP_TOWNCITY = 'Town / City'
	
// **************************** Validation Scripts **************************************************//

function myWozzonEditDetails() {
	
	var frmName = _$id('editUserDetail');
	var nickName = frmName.nickName.value;	
	var postCode = frmName.postcode.value;
	var phone = frmName.phone.value;
	var password = frmName.newPassword.value;
	var oldPassword = frmName.oldPassword.value;
	var rePassword = frmName.reNewPassword.value;
	var newEmail = frmName.newEmail.value;		
	var reNewEmail = frmName.reNewEmail.value;
	var country = frmName.countryName.value;
	var county = frmName.countyName.value;
	var townCity = frmName.townCity.value;
	var street = frmName.street.value;
	var username = frmName.userName.value;
	
	postCode = trim(postCode);
	if(postCode == MW_POSTCODE) postCode = '';
	
	phone = trim(phone);
	if(phone == MW_MOBILENUM)  phone= '';
	
	nickName = trim(nickName);
	if( nickName == MW_NICKNAME) nickName = '';
	
	newEmail = trim(newEmail);
	if(newEmail == MW_NEWEMAIL) newEmail = '';	
	
	reNewEmail = trim(reNewEmail);
	if(reNewEmail == MW_CONF_NEWEMAIL) reNewEmail = '';
	
	country = trim(country);
	if(country == MW_COUNTRY ) country = '';
	
	county= trim(county);
	if(county == MW_COUNTY) county = '';
	
	townCity= trim(townCity);
	if(townCity == MW_TOWNCITY) townCity = '';
	
	street = trim(street);
	if( street == MW_STREET ) street = '';
	
	username = trim(username);
	if( username == MW_NAME ) username = '';
	
	
	
	if(nickName.length == 0) {
		SNG_displayNickNameError($("#text_nickName"),"Please provide nick name.");		
		return false;
	}else if(SNG_checkNickname(nickName)){
		SNG_displayNickNameError($("#text_nickName"), NICK_NAME_INVALID_CHAR);		
		return false;
	}
	else if($('#nickNameAlreadyExist').val() == "1") {
		SNG_displayNickNameError($("#text_nickName"),"There is already an account associated with this nickname");
		return false;
	}
	else if(phone.length > 0 && !validateNumber(phone)){
		SNG_displayLoginError($("#phone"),"Characters in the phone number field need to be numeric.");		
		return false;
	}
	else if($('#emailAlreadyExist').val() == "1") {
		SNG_displayLoginError($("#newEmail"), "There is already an account associated with this email");
		return false;
	}
	else if(newEmail.length > 0 ) {
		if(checkEmail(newEmail)) {
			if( reNewEmail == newEmail) {
				frmName.email.value = newEmail;
			} else if( reNewEmail.length > 0)  {
				SNG_displayLoginError($("#reNewEmail"), "New email address doesn't matches with the confirm new email address");
				return false;
			} else {
				SNG_displayLoginError($("#reNewEmail"), "Please provide confirm new email address");
				return false;
			}
		} else {
			SNG_displayLoginError($("#newEmail"), "Please provide a valid new email address");
			return false;
		}
	}	
	
	 if(password.length > 0) {
		if(password.length  < 5) {
			SNG_displayLoginError($("#newPassword"), "Hang on, you need a minimum of 5 characters");
			return false;
		}
		else if(oldPassword.length > 0) {
		   if(rePassword.length > 0) {
			   if(password == rePassword) {
				   frmName.password.value = password;
			   } else {
				   SNG_displayLoginError($("#reNewPassword"),"New password doesn't matches with the confirm new password");
			   		return false;
			   }
		   } else {
			   SNG_displayLoginError($("#reNewPassword"),"Please provide confirm new password");
			   return false;
		   }
		} else {
			 SNG_displayLoginError($("#oldPassword"),"Please provide value for current password.");
			 return false;
		}
	}
	
	if($('input[name=receiveEmailCheckBox]').is(':checked')){		
		$('#receiveEmail').val("Y");
	}else {
		$('#receiveEmail').val("N");				
	}
	
	
	frmName.postcode.value = postCode;
	frmName.phone.value = phone;			
	frmName.countryName.value = country ;
	frmName.countyName.value = county;
	frmName.townCity.value = townCity;
	frmName.street.value = street;
	frmName.userName.value = username;
	
	frmName.submit();
}

function clearErrorMsg() {
	displayEntityErrorMessage(div, "");	
}
// **************************** End Validation Scripts **************************************************//




//**************************************** Ajax Scripts *************************************************//

function checkNickName(str, oldNickName) {
	var nickName = trim(str);
	if(MW_NICKNAME != nickName && nickName.length > 0 && nickName != oldNickName )
		if(SNG_checkNickname(nickName)){
			SNG_displayNickNameError($('#text_nickName'), NICK_NAME_INVALID_CHAR);
		}else{
			UserManager.checkNickName(nickName, checkNickNameHandler);
		}
	else if ( nickName == oldNickName ) {
		$('#nickNameAlreadyExist').val("0");
		SNG_hideClearAllErrors();
	}
}

function checkNickNameHandler(source) {

	if(source == "error")
		SNG_displayNickNameError($("#text_nickName"),"Error processing request for checking availability of nick name.");
	else if(source == "Exists") {
		$('#nickNameAlreadyExist').val("1");
		SNG_displayNickNameError($("#text_nickName"),"There is already an account associated with this nickname");					
	} else {
		$('#nickNameAlreadyExist').val("0");
		SNG_hideClearAllErrors();
	}
	
}

function checkEmailAvailability(str, oldEmail) {
	var reNewEmail = trim(str)
	var newEmail = trim($("#newEmail").val());	
	
	if(newEmail == MW_NEWEMAIL) newEmail = '';
	
	if(reNewEmail == MW_CONF_NEWEMAIL) reNewEmail = '';
		
	if( newEmail == oldEmail ||  newEmail == '') {
		$('#emailAlreadyExist').val("0");
		SNG_hideClearAllErrors();
	} else if(newEmail.length > 0 && checkEmail(newEmail) &&  newEmail != oldEmail && reNewEmail == newEmail) {		
		UserManager.checkEmailAvailability(newEmail, checkEmailAvailabilityHandler);		
	} else if( !checkEmail(newEmail) ) {
		SNG_displayLoginError($("#newEmail"), "Please provide a valid new email address");
	} else if( reNewEmail.length > 0)  {
		SNG_displayLoginError($("#reNewEmail"), "New email address doesn't matches with the confirm new email address");		
	} else {
		SNG_displayLoginError($("#reNewEmail"), "Please provide confirm new email address");		
	}
}

function checkEmailAvailabilityHandler(source) {

	if(source == "error")
		SNG_displayLoginError($("#newEmail"), "Error processing request for checking availability of email.");
	else if(source == "Exists") {
		$('#emailAlreadyExist').val("1");
		SNG_displayLoginError($("#newEmail"), "There is already an account associated with this email");	
	} else {
		$('#emailAlreadyExist').val("0");
		SNG_hideClearAllErrors();
		
	}
	
}

function updateUserInfo(email) {
    var token= 6;
	var a= readCookie("wozzonuser");
	if(a && email) {
	    UserManager.getUserToken(email, function(source) {
        if(source != "error" && source != "invalid" )
            if(source.length > token) {
                remember(email,source.substr(token));
            }
        });	   
	}  
}

//**************************************** End Ajax Scripts *********************************************//
	
$(document).ready(function() {
	$('#editUserDetail input').blur(function(){
		
		var name = $(this).attr('name');
	    var val = trim($(this).val()); 
	    if(name == 'userName' && val == '') {
	    	$(this).val(MW_NAME);
	    	$(this).removeClass('popupTextField').addClass('popupTextFieldBefore');
	    } else if(name == 'nickName' && val == '' ) {
	    	$(this).val(MW_NICKNAME);
	    	$(this).removeClass('popupTextField').addClass('popupTextFieldBefore');
	    } else if(name == 'street' && val == '' ) {
	    	$(this).val(MW_STREET);
	    	$(this).removeClass('popupTextField').addClass('popupTextFieldBefore');
	    } else if(name == 'postcode' && val == '' ) {
	    	$(this).val(MW_POSTCODE);
	    	$(this).removeClass('popupTextField').addClass('popupTextFieldBefore');
	    } else if(name == 'countyName' && val == '' ) {
	    	$(this).val(MW_COUNTY);
	    	$(this).removeClass('popupTextField').addClass('popupTextFieldBefore');
	    }else if(name == 'countryName' && val == '' ) {
	    	$(this).val(MW_COUNTRY);
	    	$(this).removeClass('popupTextField').addClass('popupTextFieldBefore');
	    }else if(name == 'phone' && val == '' ) {
	    	$(this).val(MW_MOBILENUM);
	    	$(this).removeClass('popupTextField').addClass('popupTextFieldBefore');
	    }else if(name == 'newEmail' && val == '' ) {
	    	$(this).val(MW_NEWEMAIL);
	    	$(this).removeClass('popupTextField').addClass('popupTextFieldBefore');
	    }else if(name == 'reNewEmail' && val == '') {
	    	$(this).val(MW_CONF_NEWEMAIL);	
	    	$(this).removeClass('popupTextField').addClass('popupTextFieldBefore');
	    }else if(name == 'oldPassword' && val == '' ) {
	    	$('input[name="password_text"]').removeClass().addClass('popupTextFieldBefore');
	    	$('input[name="password_text"]').parent().show();	    	
	    	$(this).parent().hide();
	    }else if(name == 'newPassword' && val == '' ) {
	    	$('input[name="new_password_text"]').removeClass().addClass('popupTextFieldBefore');
	    	$('input[name="new_password_text"]').parent().show();	    	
	    	$(this).parent().hide();
	    }else if(name == 'reNewPassword' && val == '' ) {
	    	$('input[name="renew_password_text"]').removeClass().addClass('popupTextFieldBefore');
	    	$('input[name="renew_password_text"]').parent().show();
	    	$(this).parent().hide();
	    }else if(name == 'townCity' && val == '' ) {
	    	$(this).val(MW_TOWNCITY);
	    	$(this).removeClass('popupTextField').addClass('popupTextFieldBefore');
	    }
	    
		
	});
	
	$('#editUserDetail input').focus(function(){
		
		var name = $(this).attr('name');
	    var val = trim($(this).val()); 
	    if(name == 'userName' && val == MW_NAME ) {
	    	$(this).val('');
	    	$(this).removeClass('popupTextFieldBefore').addClass('popupTextField');
	    } else if(name == 'nickName') {
	    	$(this).removeClass('SNG_SPTextFieldActive');
	    	if( val == MW_NICKNAME ) {
		    	$(this).val('');		    	
		    	$(this).removeClass('popupTextFieldBefore').addClass('popupTextField');    	
	    	}
	    } else if(name == 'street' && val == MW_STREET ) {
	    	$(this).val('');
	    	$(this).removeClass('popupTextFieldBefore').addClass('popupTextField');
	    } else if(name == 'postcode' && val == MW_POSTCODE ) {
	    	$(this).val('');
	    	$(this).removeClass('popupTextFieldBefore').addClass('popupTextField');
	    } else if(name == 'countyName' && val == MW_COUNTY ) {
	    	$(this).val('');
	    	$(this).removeClass('popupTextFieldBefore').addClass('popupTextField');
	    }else if(name == 'countryName' && val == MW_COUNTRY ) {
	    	$(this).val('');
	    	$(this).removeClass('popupTextFieldBefore').addClass('popupTextField');
	    }else if(name == 'phone' && val == MW_MOBILENUM ) {
	    	$(this).val('');
	    	$(this).removeClass('popupTextFieldBefore').addClass('popupTextField');
	    }else if(name == 'newEmail' && val == MW_NEWEMAIL ) {
	    	$(this).val('');
	    	$(this).removeClass('popupTextFieldBefore').addClass('popupTextField');
	    }else if(name == 'reNewEmail' && val == MW_CONF_NEWEMAIL ) {
	    	$(this).val('');	
	    	$(this).removeClass('popupTextFieldBefore').addClass('popupTextField');
	    }else if(name == 'password_text' && val == MW_CUR_PASS ) {
	    	$("#oldPassword").parent().show();
	    	$("#oldPassword").focus();
	    	$(this).parent().hide();
	    	$(this).removeClass().addClass('popupTextField');
	    }else if(name == 'new_password_text' && val == MW_NEW_PASS ) {
	    	$("#newPassword").parent().show();
	    	$("#newPassword").focus();
	    	$(this).parent().hide();
	    	$(this).removeClass().addClass('popupTextField');
	    }else if(name == 'renew_password_text' && val == MW_CONF_PASS ) {
	    	$("#reNewPassword").parent().show();
	    	$("#reNewPassword").focus();
	    	$(this).parent().hide();
	    	$(this).removeClass().addClass('popupTextField');
	    }else if(name == 'townCity' && val == MW_TOWNCITY ) {
	    	$(this).val('');
	    	$(this).removeClass('popupTextFieldBefore').addClass('popupTextField');
	    }
		
	});
	
});	
/*CALENDAR.JS START*/
// $Id: calendar.js,v 1.2 2007/04/12 05:43:23 mahmed Exp $

/** The Calendar object constructor. */
Calendar = function (firstDayOfWeek, dateStr, onSelected, onClose) {
	// member variables
	this.activeDiv = null;
	this.currentDateEl = null;
	this.getDateStatus = null;
	this.getDateToolTip = null;
	this.getDateText = null;
	this.timeout = null;
	this.onSelected = onSelected || null;
	this.onClose = onClose || null;
	this.dragging = false;
	this.hidden = false;
	this.minYear = 1970;
	this.maxYear = 2050;
	this.dateFormat = Calendar._TT["DEF_DATE_FORMAT"];
	this.ttDateFormat = Calendar._TT["TT_DATE_FORMAT"];
	this.isPopup = true;
	this.weekNumbers = true;
	this.firstDayOfWeek = typeof firstDayOfWeek == "number" ? firstDayOfWeek : Calendar._FD; // 0 for Sunday, 1 for Monday, etc.
	this.showsOtherMonths = false;
	this.dateStr = dateStr;
	this.ar_days = null;
	this.showsTime = false;
	this.time24 = true;
	this.yearStep = 2;
	this.hiliteToday = true;
	this.multiple = null;
	// HTML elements
	this.table = null;
	this.element = null;
	this.tbody = null;
	this.firstdayname = null;
	// Combo boxes
	this.monthsCombo = null;
	this.yearsCombo = null;
	this.hilitedMonth = null;
	this.activeMonth = null;
	this.hilitedYear = null;
	this.activeYear = null;
	// Information
	this.dateClicked = false;

	// one-time initializations
	if (typeof Calendar._SDN == "undefined") {
		// table of short day names
		if (typeof Calendar._SDN_len == "undefined")
			Calendar._SDN_len = 3;
		var ar = new Array();
		for (var i = 8; i > 0;) {
			ar[--i] = Calendar._DN[i].substr(0, Calendar._SDN_len);
		}
		Calendar._SDN = ar;
		// table of short month names
		if (typeof Calendar._SMN_len == "undefined")
			Calendar._SMN_len = 3;
		ar = new Array();
		for (var i = 12; i > 0;) {
			ar[--i] = Calendar._MN[i].substr(0, Calendar._SMN_len);
		}
		Calendar._SMN = ar;
	}
};

// ** constants

/// "static", needed for event handlers.
Calendar._C = null;

/// detect a special case of "web browser"
Calendar.is_ie = ( /msie/i.test(navigator.userAgent) &&
		   !/opera/i.test(navigator.userAgent) );

Calendar.is_ie5 = ( Calendar.is_ie && /msie 5\.0/i.test(navigator.userAgent) );

Calendar.is_ie7 = ( Calendar.is_ie && /msie 7\.0/i.test(navigator.userAgent) );

/// detect Opera browser
Calendar.is_opera = /opera/i.test(navigator.userAgent);

/// detect KHTML-based browsers
Calendar.is_khtml = /Konqueror|Safari|KHTML/i.test(navigator.userAgent);

// BEGIN: UTILITY FUNCTIONS; beware that these might be moved into a separate
//        library, at some point.

Calendar.getAbsolutePos = function(el) {
	var SL = 0, ST = 0;
	var is_div = /^div$/i.test(el.tagName);
	if (is_div && el.scrollLeft)
		SL = el.scrollLeft;
	if (is_div && el.scrollTop)
		ST = el.scrollTop;
	var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
	if (el.offsetParent) {
		var tmp = this.getAbsolutePos(el.offsetParent);
		r.x += tmp.x;
		r.y += tmp.y;
	}
	return r;
};
Calendar.eventTimingRow = function(el) {	
	if(Calendar.is_ie7  && el.name){	
     	var W_FROM = el.name.indexOf("whenfrom_");
   	    var W_TO =  el.name.indexOf("whento_");	
	    return (W_FROM != -1 || W_TO != -1);				  
	} else return false;
	
};
Calendar.lowerSearchForm = function(el) {	
	if(Calendar.is_ie7  && el.name){	     	
		var L_FROM = el.name.indexOf("l_gdp_whenfrom");
   	    var L_TO =  el.name.indexOf("l_gdp_whento");	
		 return (L_FROM != -1 || L_TO != -1);
	 } else return false;
	
};

Calendar.newSearchForm = function(el) {	
	if(Calendar.is_ie7  && el.name){	     			
		if (Calendar.lowerSearchForm(el))
		      return true;
			  
		var U_FROM = el.name.indexOf("gdp_whenfrom");
   	    var U_TO =  el.name.indexOf("gdp_whento");		  
	    return ( ( ! _$id("l_gdp_whenfrom") ) && U_FROM != -1 || U_TO != -1 );				  
	} else return false;
	
};



Calendar.isRelated = function (el, evt) {
	var related = evt.relatedTarget;
	if (!related) {
		var type = evt.type;
		if (type == "mouseover") {
			related = evt.fromElement;
		} else if (type == "mouseout") {
			related = evt.toElement;
		}
	}
	while (related) {
		if (related == el) {
			return true;
		}
		related = related.parentNode;
	}
	return false;
};

Calendar.removeClass = function(el, className) {
	if (!(el && el.className)) {
		return;
	}
	var cls = el.className.split(" ");
	var ar = new Array();
	for (var i = cls.length; i > 0;) {
		if (cls[--i] != className) {
			ar[ar.length] = cls[i];
		}
	}
	el.className = ar.join(" ");
};

Calendar.addClass = function(el, className) {
	Calendar.removeClass(el, className);
	el.className += " " + className;
};

// FIXME: the following 2 functions totally suck, are useless and should be replaced immediately.
Calendar.getElement = function(ev) {
	var f = Calendar.is_ie ? window.event.srcElement : ev.currentTarget;
	while (f.nodeType != 1 || /^div$/i.test(f.tagName))
		f = f.parentNode;
	return f;
};

Calendar.getTargetElement = function(ev) {
	var f = Calendar.is_ie ? window.event.srcElement : ev.target;
	while (f.nodeType != 1)
		f = f.parentNode;
	return f;
};

Calendar.stopEvent = function(ev) {
	ev || (ev = window.event);
	if (Calendar.is_ie) {
		ev.cancelBubble = true;
		ev.returnValue = false;
	} else {
		ev.preventDefault();
		ev.stopPropagation();
	}
	return false;
};

Calendar.addEvent = function(el, evname, func) {
	if (el.attachEvent) { // IE
		el.attachEvent("on" + evname, func);
	} else if (el.addEventListener) { // Gecko / W3C
		el.addEventListener(evname, func, true);
	} else {
		el["on" + evname] = func;
	}
};

Calendar.removeEvent = function(el, evname, func) {
	if (el.detachEvent) { // IE
		el.detachEvent("on" + evname, func);
	} else if (el.removeEventListener) { // Gecko / W3C
		el.removeEventListener(evname, func, true);
	} else {
		el["on" + evname] = null;
	}
};

Calendar.createElement = function(type, parent) {
	var el = null;
	if (document.createElementNS) {
		// use the XHTML namespace; IE won't normally get here unless
		// _they_ "fix" the DOM2 implementation.
		el = document.createElementNS("http://www.w3.org/1999/xhtml", type);
	} else {
		el = document.createElement(type);
	}
	if (typeof parent != "undefined") {
		parent.appendChild(el);
	}
	return el;
};

// END: UTILITY FUNCTIONS

// BEGIN: CALENDAR STATIC FUNCTIONS

/** Internal -- adds a set of events to make some element behave like a button. */
Calendar._add_evs = function(el) {
	with (Calendar) {
		addEvent(el, "mouseover", dayMouseOver);
		addEvent(el, "mousedown", dayMouseDown);
		addEvent(el, "mouseout", dayMouseOut);
		if (is_ie) {
			addEvent(el, "dblclick", dayMouseDblClick);
			el.setAttribute("unselectable", true);
		}
	}
};

Calendar.findMonth = function(el) {
	if (typeof el.month != "undefined") {
		return el;
	} else if (typeof el.parentNode.month != "undefined") {
		return el.parentNode;
	}
	return null;
};

Calendar.findYear = function(el) {
	if (typeof el.year != "undefined") {
		return el;
	} else if (typeof el.parentNode.year != "undefined") {
		return el.parentNode;
	}
	return null;
};

Calendar.showMonthsCombo = function () {
	var cal = Calendar._C;
	if (!cal) {
		return false;
	}
	var cal = cal;
	var cd = cal.activeDiv;
	var mc = cal.monthsCombo;
	if (cal.hilitedMonth) {
		Calendar.removeClass(cal.hilitedMonth, "hilite");
	}
	if (cal.activeMonth) {
		Calendar.removeClass(cal.activeMonth, "active");
	}
	var mon = cal.monthsCombo.getElementsByTagName("div")[cal.date.getMonth()];
	Calendar.addClass(mon, "active");
	cal.activeMonth = mon;
	var s = mc.style;
	s.display = "block";
	if (cd.navtype < 0)
		s.left = cd.offsetLeft + "px";
	else {
		var mcw = mc.offsetWidth;
		if (typeof mcw == "undefined")
			// Konqueror brain-dead techniques
			mcw = 50;
		s.left = (cd.offsetLeft + cd.offsetWidth - mcw) + "px";
	}
	s.top = (cd.offsetTop + cd.offsetHeight) + "px";
};

Calendar.showYearsCombo = function (fwd) {

	var cal = Calendar._C;
	if (!cal) {
		return false;
	}
	var cal = cal;
	var cd = cal.activeDiv;
	var yc = cal.yearsCombo;
	if (cal.hilitedYear) {
		Calendar.removeClass(cal.hilitedYear, "hilite");
	}
	if (cal.activeYear) {
		Calendar.removeClass(cal.activeYear, "active");
	}
	cal.activeYear = null;
	var Y = cal.date.getFullYear() + (fwd ? 1 : -1);
	var yr = yc.firstChild;
	var show = false;
	for (var i = 12; i > 0; --i) {
		if (Y >= cal.minYear && Y <= cal.maxYear) {
			yr.innerHTML = Y;
			yr.year = Y;
			yr.style.display = "block";
			show = true;
		} else {
			yr.style.display = "none";
		}
		yr = yr.nextSibling;
		Y += fwd ? cal.yearStep : -cal.yearStep;
	}
	if (show) {
		var s = yc.style;
		s.display = "block";
		if (cd.navtype < 0)
			s.left = cd.offsetLeft + "px";
		else {
			var ycw = yc.offsetWidth;
			if (typeof ycw == "undefined")
				// Konqueror brain-dead techniques
				ycw = 50;
			s.left = (cd.offsetLeft + cd.offsetWidth - ycw) + "px";
		}
		s.top = (cd.offsetTop + cd.offsetHeight) + "px";
	}
};

// event handlers

Calendar.tableMouseUp = function(ev) {
	var cal = Calendar._C;
	if (!cal) {
		return false;
	}
	if (cal.timeout) {
		clearTimeout(cal.timeout);
	}
	var el = cal.activeDiv;
	if (!el) {
		return false;
	}
	var target = Calendar.getTargetElement(ev);
	ev || (ev = window.event);
	Calendar.removeClass(el, "active");
	if (target == el || target.parentNode == el) {
		Calendar.cellClick(el, ev);
	}
	var mon = Calendar.findMonth(target);
	var date = null;
	if (mon) {
		date = new Date(cal.date);
		if (mon.month != date.getMonth()) {
			date.setMonth(mon.month);
			cal.setDate(date);
			cal.dateClicked = false;
			cal.callHandler();
		}
	} else {
		var year = Calendar.findYear(target);
		if (year) {
			date = new Date(cal.date);
			if (year.year != date.getFullYear()) {
				date.setFullYear(year.year);
				cal.setDate(date);
				cal.dateClicked = false;
				cal.callHandler();
			}
		}
	}
	with (Calendar) {
		removeEvent(document, "mouseup", tableMouseUp);
		removeEvent(document, "mouseover", tableMouseOver);
		removeEvent(document, "mousemove", tableMouseOver);
		cal._hideCombos();
		_C = null;
		return stopEvent(ev);
	}
};

Calendar.tableMouseOver = function (ev) {
	var cal = Calendar._C;
	if (!cal) {
		return;
	}
	var el = cal.activeDiv;
	var target = Calendar.getTargetElement(ev);
	if (target == el || target.parentNode == el) {
		Calendar.addClass(el, "hilite active");
		Calendar.addClass(el.parentNode, "rowhilite");
	} else {
		if (typeof el.navtype == "undefined" || (el.navtype != 50 && (el.navtype == 0 || Math.abs(el.navtype) > 2)))
			Calendar.removeClass(el, "active");
		Calendar.removeClass(el, "hilite");
		Calendar.removeClass(el.parentNode, "rowhilite");
	}
	ev || (ev = window.event);
	if (el.navtype == 50 && target != el) {
		var pos = Calendar.getAbsolutePos(el);
		var w = el.offsetWidth;
		var x = ev.clientX;
		var dx;
		var decrease = true;
		if (x > pos.x + w) {
			dx = x - pos.x - w;
			decrease = false;
		} else
			dx = pos.x - x;

		if (dx < 0) dx = 0;
		var range = el._range;
		var current = el._current;
		var count = Math.floor(dx / 10) % range.length;
		for (var i = range.length; --i >= 0;)
			if (range[i] == current)
				break;
		while (count-- > 0)
			if (decrease) {
				if (--i < 0)
					i = range.length - 1;
			} else if ( ++i >= range.length )
				i = 0;
		var newval = range[i];
		el.innerHTML = newval;

		cal.onUpdateTime();
	}
	var mon = Calendar.findMonth(target);
	if (mon) {
		if (mon.month != cal.date.getMonth()) {
			if (cal.hilitedMonth) {
				Calendar.removeClass(cal.hilitedMonth, "hilite");
			}
			Calendar.addClass(mon, "hilite");
			cal.hilitedMonth = mon;
		} else if (cal.hilitedMonth) {
			Calendar.removeClass(cal.hilitedMonth, "hilite");
		}
	} else {
		if (cal.hilitedMonth) {
			Calendar.removeClass(cal.hilitedMonth, "hilite");
		}
		var year = Calendar.findYear(target);
		if (year) {
			if (year.year != cal.date.getFullYear()) {
				if (cal.hilitedYear) {
					Calendar.removeClass(cal.hilitedYear, "hilite");
				}
				Calendar.addClass(year, "hilite");
				cal.hilitedYear = year;
			} else if (cal.hilitedYear) {
				Calendar.removeClass(cal.hilitedYear, "hilite");
			}
		} else if (cal.hilitedYear) {
			Calendar.removeClass(cal.hilitedYear, "hilite");
		}
	}
	return Calendar.stopEvent(ev);
};

Calendar.tableMouseDown = function (ev) {
	if (Calendar.getTargetElement(ev) == Calendar.getElement(ev)) {
		return Calendar.stopEvent(ev);
	}
};

Calendar.calDragIt = function (ev) {
	var cal = Calendar._C;
	if (!(cal && cal.dragging)) {
		return false;
	}
	var posX;
	var posY;
	if (Calendar.is_ie) {
		posY = window.event.clientY + document.body.scrollTop;
		posX = window.event.clientX + document.body.scrollLeft;
	} else {
		posX = ev.pageX;
		posY = ev.pageY;
	}
	cal.hideShowCovered();
	var st = cal.element.style;
	st.left = (posX - cal.xOffs) + "px";
	st.top = (posY - cal.yOffs) + "px";
	return Calendar.stopEvent(ev);
};

Calendar.calDragEnd = function (ev) {
	var cal = Calendar._C;
	if (!cal) {
		return false;
	}
	cal.dragging = false;
	with (Calendar) {
		removeEvent(document, "mousemove", calDragIt);
		removeEvent(document, "mouseup", calDragEnd);
		tableMouseUp(ev);
	}
	cal.hideShowCovered();
};

Calendar.dayMouseDown = function(ev) {
	var el = Calendar.getElement(ev);
	if (el.disabled) {
		return false;
	}
	var cal = el.calendar;
	cal.activeDiv = el;
	Calendar._C = cal;
	if (el.navtype != 300) with (Calendar) {
		if (el.navtype == 50) {
			el._current = el.innerHTML;
			addEvent(document, "mousemove", tableMouseOver);
		} else
			addEvent(document, Calendar.is_ie5 ? "mousemove" : "mouseover", tableMouseOver);
		addClass(el, "hilite active");
		addEvent(document, "mouseup", tableMouseUp);
	} else if (cal.isPopup) {
		cal._dragStart(ev);
	}
	if (el.navtype == -1 || el.navtype == 1) {
		if (cal.timeout) clearTimeout(cal.timeout);
		cal.timeout = setTimeout("Calendar.showMonthsCombo()", 250);
	} else if (el.navtype == -2 || el.navtype == 2) {
		if (cal.timeout) clearTimeout(cal.timeout);
		cal.timeout = setTimeout((el.navtype > 0) ? "Calendar.showYearsCombo(true)" : "Calendar.showYearsCombo(false)", 250);
	} else {
		cal.timeout = null;
	}
	return Calendar.stopEvent(ev);
};

Calendar.dayMouseDblClick = function(ev) {
	Calendar.cellClick(Calendar.getElement(ev), ev || window.event);
	if (Calendar.is_ie) {
		document.selection.empty();
	}
};

Calendar.dayMouseOver = function(ev) {
	var el = Calendar.getElement(ev);
	if (Calendar.isRelated(el, ev) || Calendar._C || el.disabled) {
		return false;
	}
	if (el.ttip) {
		if (el.ttip.substr(0, 1) == "_") {
			el.ttip = el.caldate.print(el.calendar.ttDateFormat) + el.ttip.substr(1);
		}
		el.calendar.tooltips.innerHTML = el.ttip;
	}
	if (el.navtype != 300) {
		Calendar.addClass(el, "hilite");
		if (el.caldate) {
			//Calendar.addClass(el.parentNode, "rowhilite");
		}
	}
	return Calendar.stopEvent(ev);
};

Calendar.dayMouseOut = function(ev) {
	with (Calendar) {
		var el = getElement(ev);
		if (isRelated(el, ev) || _C || el.disabled)
			return false;
		removeClass(el, "hilite");
		if (el.caldate)
			removeClass(el.parentNode, "rowhilite");
		if (el.calendar)
			el.calendar.tooltips.innerHTML = _TT["SEL_DATE"];
		return stopEvent(ev);
	}
};

/**
 *  A generic "click" handler :) handles all types of buttons defined in this
 *  calendar.
 */
Calendar.cellClick = function(el, ev) {
	var cal = el.calendar;
	var closing = false;
	var newdate = false;
	var date = null;
	if (typeof el.navtype == "undefined") {
		////edition of canceling if written below/////
//		if (cal.currentDateEl ) {
			if (cal.currentDateEl )  // this line is inserted by 
				Calendar.removeClass(cal.currentDateEl, "selected");
			Calendar.addClass(el, "selected");
			closing = (cal.currentDateEl == el);
			if (!closing) {
				cal.currentDateEl = el;
			}
//		}
		//////////end edition/////////

		cal.date.setDateOnly(el.caldate);
		date = cal.date;
		var other_month = !(cal.dateClicked = !el.otherMonth);
		if (!other_month && !cal.currentDateEl)
			cal._toggleMultipleDate(new Date(date));
		else
			newdate = !el.disabled;
		// a date was clicked
		if (other_month)
			cal._init(cal.firstDayOfWeek, date);
	} else {
		if (el.navtype == 200) {
			Calendar.removeClass(el, "hilite");
			cal.callCloseHandler();
			return;
		}
		date = new Date(cal.date);
		if (el.navtype == 0)
			date.setDateOnly(new Date()); // TODAY
		// unless "today" was clicked, we assume no date was clicked so
		// the selected handler will know not to close the calenar when
		// in single-click mode.
		// cal.dateClicked = (el.navtype == 0);
		cal.dateClicked = false;
		var year = date.getFullYear();
		var mon = date.getMonth();
		function setMonth(m) {
			var day = date.getDate();
			var max = date.getMonthDays(m);
			if (day > max) {
				date.setDate(max);
			}
			date.setMonth(m);
		};
		switch (el.navtype) {
		    case 400:
			Calendar.removeClass(el, "hilite");
			var text = Calendar._TT["ABOUT"];
			if (typeof text != "undefined") {
				text += cal.showsTime ? Calendar._TT["ABOUT_TIME"] : "";
			} else {
				// FIXME: this should be removed as soon as lang files get updated!
				text = "Help and about box text is not translated into this language.\n" +
					"If you know this language and you feel generous please update\n" +
					"the corresponding file in \"lang\" subdir to match calendar-en.js\n" +
					"and send it back to <mihai_bazon@yahoo.com> to get it into the distribution  ;-)\n\n" +
					"Thank you!\n" +
					"http://dynarch.com/mishoo/calendar.epl\n";
			}
			alert(text);
			return;
		    case -2:
			if (year > cal.minYear) {
				date.setFullYear(year - 1);
			}
			break;
		    case -1:
			if (mon > 0) {
				setMonth(mon - 1);
			} else if (year-- > cal.minYear) {
				date.setFullYear(year);
				setMonth(11);
			}
			break;
		    case 1:
			if (mon < 11) {
				setMonth(mon + 1);
			} else if (year < cal.maxYear) {
				date.setFullYear(year + 1);
				setMonth(0);
			}
			break;
		    case 2:
			if (year < cal.maxYear) {
				date.setFullYear(year + 1);
			}
			break;
		    case 100:
			cal.setFirstDayOfWeek(el.fdow);
			return;
		    case 50:
			var range = el._range;
			var current = el.innerHTML;
			for (var i = range.length; --i >= 0;)
				if (range[i] == current)
					break;
			if (ev && ev.shiftKey) {
				if (--i < 0)
					i = range.length - 1;
			} else if ( ++i >= range.length )
				i = 0;
			var newval = range[i];
			el.innerHTML = newval;
			cal.onUpdateTime();
			return;
		    case 0:
			// TODAY will bring us here
			cal.dateClicked = true;		////Pixsense's Change
						
			if ((typeof cal.getDateStatus == "function") &&
			    cal.getDateStatus(date, date.getFullYear(), date.getMonth(), date.getDate())) {
				return false;
			}
			break;
		}
		if (!date.equalsTo(cal.date)) {
			cal.setDate(date);
			newdate = true;
		} else if (el.navtype == 0)
			newdate = closing = true;
	}
	if (newdate) {
		ev && cal.callHandler();
	}
	if (closing) {
		Calendar.removeClass(el, "hilite");
		ev && cal.callCloseHandler();
	}
};

// END: CALENDAR STATIC FUNCTIONS

// BEGIN: CALENDAR OBJECT FUNCTIONS

/**
 *  This function creates the calendar inside the given parent.  If _par is
 *  null than it creates a popup calendar inside the BODY element.  If _par is
 *  an element, be it BODY, then it creates a non-popup calendar (still
 *  hidden).  Some properties need to be set before calling this function.
 */
Calendar.prototype.create = function (_par) {
	var parent = null;
	if (! _par) {
		// default parent is the document body, in which case we create
		// a popup calendar.
		parent = document.getElementsByTagName("body")[0];
		this.isPopup = true;
	} else {
		parent = _par;
		this.isPopup = false;
	}
	this.date = this.dateStr ? new Date(this.dateStr) : new Date();

	var table = Calendar.createElement("table");
	this.table = table;
	table.cellSpacing = 0;
	table.cellPadding = 0;
	table.calendar = this;
	Calendar.addEvent(table, "mousedown", Calendar.tableMouseDown);

	var div = Calendar.createElement("div");
	this.element = div;
	div.className = "calendar";
	if (this.isPopup) {
		div.style.position = "absolute";
		div.style.display = "none";
		//div.style.zIndex = "20";
	}
	div.appendChild(table);

	var thead = Calendar.createElement("thead", table);
	///Change////
	this.thead = thead;
        /////change end/////
	var cell = null;
	var row = null;

	var cal = this;
	var hh = function (text, cs, navtype) {
		cell = Calendar.createElement("td", row);
		cell.colSpan = cs;
		cell.className = "calbutton";
		if (navtype != 0 && Math.abs(navtype) <= 2)
			cell.className += " nav";
		Calendar._add_evs(cell);
		cell.calendar = cal;
		cell.navtype = navtype;
		cell.innerHTML = "<div unselectable='on'>" + text + "</div>";
		return cell;
	};

	row = Calendar.createElement("tr", thead);
	// Change/////
	var title_length = 6;
	///chg end/////
	(this.isPopup) && --title_length;
	//(this.weekNumbers) && ++title_length;
	this.weekNumbers = false;
	
	///  Change////
//	hh("?", 1, 400).ttip = Calendar._TT["INFO"];
	///Change End////////
	this.title = hh("", 7, 300);
	this.title.className = "ctitle";
	if (this.isPopup) {
		this.title.ttip = Calendar._TT["DRAG_TO_MOVE"];
		this.title.style.cursor = "move";
		hh("&#x00d7;", 1, 200).ttip = Calendar._TT["CLOSE"];
	}

	row = Calendar.createElement("tr", thead);
	row.className = "headrow";
	////  Change///////////
//	this._nav_py = hh("&#x00ab;", 1, -2);
//	this._nav_py.ttip = Calendar._TT["PREV_YEAR"];
	/////Change end///////////////
	this._nav_pm = hh("&#x2039;", 1, -1);
	this._nav_pm.ttip = Calendar._TT["PREV_MONTH"];

	////  Change///////////
	this._nav_now = hh(Calendar._TT["TODAY"], this.weekNumbers ? 6 : 5, 0);  ///originally 6 is 4 and 5 is 3
	/////Change end///////////////
	this._nav_now.ttip = Calendar._TT["GO_TODAY"];

	this._nav_nm = hh("&#x203a;", 1, 1);
	this._nav_nm.ttip = Calendar._TT["NEXT_MONTH"];
	////  Change///////////
//	this._nav_ny = hh("&#x00bb;", 1, 2);
//	this._nav_ny.ttip = Calendar._TT["NEXT_YEAR"];
	/////Change end///////////////
	// day names
	row = Calendar.createElement("tr", thead);
	row.className = "daynames";
	
	if (this.weekNumbers) {
		cell = Calendar.createElement("td", row);
		cell.className = "name wn";
		cell.innerHTML = Calendar._TT["WK"];
	}
	
	for (var i = 7; i > 0; --i) {
		cell = Calendar.createElement("td", row);
		if (!i) {
			cell.navtype = 100;
			cell.calendar = this;
			Calendar._add_evs(cell);
		}
	}
	this.firstdayname = (this.weekNumbers) ? row.firstChild.nextSibling : row.firstChild;
	this._displayWeekdays();

	var tbody = Calendar.createElement("tbody", table);
	this.tbody = tbody;

	for (i  = 6; i > 0; --i) {
		row = Calendar.createElement("tr", tbody);
		if (this.weekNumbers) {
			cell = Calendar.createElement("td", row);
		}
		for (var j = 7; j > 0; --j) {
			cell = Calendar.createElement("td", row);
			cell.calendar = this;
			Calendar._add_evs(cell);
		}
	}

	if (this.showsTime) {
		row = Calendar.createElement("tr", tbody);
		row.className = "time";

		cell = Calendar.createElement("td", row);
		cell.className = "time";
		cell.colSpan = 2;
		cell.innerHTML = Calendar._TT["TIME"] || "&nbsp;";

		cell = Calendar.createElement("td", row);
		cell.className = "time";
		cell.colSpan = this.weekNumbers ? 4 : 3;

		(function(){
			function makeTimePart(className, init, range_start, range_end) {
				var part = Calendar.createElement("span", cell);
				part.className = className;
				part.innerHTML = init;
				part.calendar = cal;
				part.ttip = Calendar._TT["TIME_PART"];
				part.navtype = 50;
				part._range = [];
				if (typeof range_start != "number")
					part._range = range_start;
				else {
					for (var i = range_start; i <= range_end; ++i) {
						var txt;
						if (i < 10 && range_end >= 10) txt = '0' + i;
						else txt = '' + i;
						part._range[part._range.length] = txt;
					}
				}
				Calendar._add_evs(part);
				return part;
			};
			var hrs = cal.date.getHours();
			var mins = cal.date.getMinutes();
			var t12 = !cal.time24;
			var pm = (hrs > 12);
			if (t12 && pm) hrs -= 12;
			var H = makeTimePart("hour", hrs, t12 ? 1 : 0, t12 ? 12 : 23);
			var span = Calendar.createElement("span", cell);
			span.innerHTML = ":";
			span.className = "colon";
			var M = makeTimePart("minute", mins, 0, 59);
			var AP = null;
			cell = Calendar.createElement("td", row);
			cell.className = "time";
			cell.colSpan = 2;
			if (t12)
				AP = makeTimePart("ampm", pm ? "pm" : "am", ["am", "pm"]);
			else
				cell.innerHTML = "&nbsp;";

			cal.onSetTime = function() {
				var pm, hrs = this.date.getHours(),
					mins = this.date.getMinutes();
				if (t12) {
					pm = (hrs >= 12);
					if (pm) hrs -= 12;
					if (hrs == 0) hrs = 12;
					AP.innerHTML = pm ? "pm" : "am";
				}
				H.innerHTML = (hrs < 10) ? ("0" + hrs) : hrs;
				M.innerHTML = (mins < 10) ? ("0" + mins) : mins;
			};

			cal.onUpdateTime = function() {
				var date = this.date;
				var h = parseInt(H.innerHTML, 10);
				if (t12) {
					if (/pm/i.test(AP.innerHTML) && h < 12)
						h += 12;
					else if (/am/i.test(AP.innerHTML) && h == 12)
						h = 0;
				}
				var d = date.getDate();
				var m = date.getMonth();
				var y = date.getFullYear();
				date.setHours(h);
				date.setMinutes(parseInt(M.innerHTML, 10));
				date.setFullYear(y);
				date.setMonth(m);
				date.setDate(d);
				this.dateClicked = false;
				this.callHandler();
			};
		})();
	} else {
		this.onSetTime = this.onUpdateTime = function() {};
	}

	var tfoot = Calendar.createElement("tfoot", table);

	row = Calendar.createElement("tr", tfoot);
	row.className = "footrow";

	cell = hh(Calendar._TT["SEL_DATE"], this.weekNumbers ? 8 : 7, 300);
	cell.className = "ttip";
	if (this.isPopup) {
		cell.ttip = Calendar._TT["DRAG_TO_MOVE"];
		cell.style.cursor = "move";
	}
	this.tooltips = cell;

	div = Calendar.createElement("div", this.element);
	this.monthsCombo = div;
	div.className = "combo";
	for (i = 0; i < Calendar._MN.length; ++i) {
		var mn = Calendar.createElement("div");
		mn.className = Calendar.is_ie ? "label-IEfix" : "label";
		mn.month = i;
		mn.innerHTML = Calendar._SMN[i];
		div.appendChild(mn);
	}

	div = Calendar.createElement("div", this.element);
	this.yearsCombo = div;
	div.className = "combo";
	for (i = 12; i > 0; --i) {
		var yr = Calendar.createElement("div");
		yr.className = Calendar.is_ie ? "label-IEfix" : "label";
		div.appendChild(yr);
	}

	this._init(this.firstDayOfWeek, this.date);
	parent.appendChild(this.element);
};

/** keyboard navigation, only for popup calendars */
Calendar._keyEvent = function(ev) {
	var cal = window._dynarch_popupCalendar;
	if (!cal || cal.multiple)
		return false;
	(Calendar.is_ie) && (ev = window.event);
	var act = (Calendar.is_ie || ev.type == "keypress"),
		K = ev.keyCode;
	if (ev.ctrlKey) {
		switch (K) {
		    case 37: // KEY left
			act && Calendar.cellClick(cal._nav_pm);
			break;
		    case 38: // KEY up
			act && Calendar.cellClick(cal._nav_py);
			break;
		    case 39: // KEY right
			act && Calendar.cellClick(cal._nav_nm);
			break;
		    case 40: // KEY down
			act && Calendar.cellClick(cal._nav_ny);
			break;
		    default:
			return false;
		}
	} else switch (K) {
	    case 32: // KEY space (now)
		Calendar.cellClick(cal._nav_now);
		break;
	    case 27: // KEY esc
		act && cal.callCloseHandler();
		break;
	    case 37: // KEY left
	    case 38: // KEY up
	    case 39: // KEY right
	    case 40: // KEY down
		if (act) {
			var prev, x, y, ne, el, step;
			prev = K == 37 || K == 38;
			step = (K == 37 || K == 39) ? 1 : 7;
			function setVars() {
				el = cal.currentDateEl;
				var p = el.pos;
				x = p & 15;
				y = p >> 4;
				ne = cal.ar_days[y][x];
			};setVars();
			function prevMonth() {
				var date = new Date(cal.date);
				date.setDate(date.getDate() - step);
				cal.setDate(date);
			};
			function nextMonth() {
				var date = new Date(cal.date);
				date.setDate(date.getDate() + step);
				cal.setDate(date);
			};
			while (1) {
				switch (K) {
				    case 37: // KEY left
					if (--x >= 0)
						ne = cal.ar_days[y][x];
					else {
						x = 6;
						K = 38;
						continue;
					}
					break;
				    case 38: // KEY up
					if (--y >= 0)
						ne = cal.ar_days[y][x];
					else {
						prevMonth();
						setVars();
					}
					break;
				    case 39: // KEY right
					if (++x < 7)
						ne = cal.ar_days[y][x];
					else {
						x = 0;
						K = 40;
						continue;
					}
					break;
				    case 40: // KEY down
					if (++y < cal.ar_days.length)
						ne = cal.ar_days[y][x];
					else {
						nextMonth();
						setVars();
					}
					break;
				}
				break;
			}
			if (ne) {
				if (!ne.disabled)
					Calendar.cellClick(ne);
				else if (prev)
					prevMonth();
				else
					nextMonth();
			}
		}
		break;
	    case 13: // KEY enter
		if (act)
			Calendar.cellClick(cal.currentDateEl, ev);
		break;
	    default:
		return false;
	}
	return Calendar.stopEvent(ev);
};

/**
 *  (RE)Initializes the calendar to the given date and firstDayOfWeek
 */
Calendar.prototype._init = function (firstDayOfWeek, date) {
	var today = new Date(),
		TY = today.getFullYear(),
		TM = today.getMonth(),
		TD = today.getDate();
	this.table.style.visibility = "hidden";
	var year = date.getFullYear();
	if (year < this.minYear) {
		year = this.minYear;
		date.setFullYear(year);
	} else if (year > this.maxYear) {
		year = this.maxYear;
		date.setFullYear(year);
	}
	this.firstDayOfWeek = firstDayOfWeek;
	this.date = new Date(date);
	var month = date.getMonth();
	var mday = date.getDate();
	var no_days = date.getMonthDays();

	// calendar voodoo for computing the first day that would actually be
	// displayed in the calendar, even if it's from the previous month.
	// WARNING: this is magic. ;-)
	date.setDate(1);
	var day1 = (date.getDay() - this.firstDayOfWeek) % 7;
	if (day1 < 0)
		day1 += 7;
	date.setDate(-day1);
	date.setDate(date.getDate() + 1);

	var row = this.tbody.firstChild;
	var MN = Calendar._SMN[month];
	var ar_days = this.ar_days = new Array();
	var weekend = Calendar._TT["WEEKEND"];
	var dates = this.multiple ? (this.datesCells = {}) : null;
	for (var i = 0; i < 6; ++i, row = row.nextSibling) {
		var cell = row.firstChild;
		if (this.weekNumbers) {
			cell.className = "day wn";
			cell.innerHTML = date.getWeekNumber();
			cell = cell.nextSibling;
		}
		row.className = "daysrow";
		var hasdays = false, iday, dpos = ar_days[i] = [];
		for (var j = 0; j < 7; ++j, cell = cell.nextSibling, date.setDate(iday + 1)) {
			iday = date.getDate();
			var wday = date.getDay();
			cell.className = "day";
			cell.pos = i << 4 | j;
			dpos[j] = cell;
			var current_month = (date.getMonth() == month);
			if (!current_month) {
				if (this.showsOtherMonths) {
					cell.className += " othermonth";
					cell.otherMonth = true;
				} else {
					cell.className = "emptycell";
					cell.innerHTML = "&nbsp;";
					cell.disabled = true;
					continue;
				}
			} else {
				cell.otherMonth = false;
				hasdays = true;
			}
			cell.disabled = false;
			cell.innerHTML = this.getDateText ? this.getDateText(date, iday) : iday;
			if (dates)
				dates[date.print("%Y%m%d")] = cell;
			if (this.getDateStatus) {
				var status = this.getDateStatus(date, year, month, iday);
				if (this.getDateToolTip) {
					var toolTip = this.getDateToolTip(date, year, month, iday);
					if (toolTip)
						cell.title = toolTip;
				}
				if (status === true) {
					cell.className += " disabled";
					cell.disabled = true;
				} else {
					if (/disabled/i.test(status))
						cell.disabled = true;
					cell.className += " " + status;
				}
			}
			if (!cell.disabled) {
				cell.caldate = new Date(date);
				cell.ttip = "_";
				if (!this.multiple && current_month
				    && iday == mday && this.hiliteToday) {
					cell.className += " selected";
					this.currentDateEl = cell;
				}
				if (date.getFullYear() == TY &&
				    date.getMonth() == TM &&
				    iday == TD) {
					cell.className += " today";
					cell.ttip += Calendar._TT["PART_TODAY"];
				}
				if (weekend.indexOf(wday.toString()) != -1)
					cell.className += cell.otherMonth ? " oweekend" : " weekend";
			}
		}
		if (!(hasdays || this.showsOtherMonths))
			row.className = "emptyrow";
	}
	this.title.innerHTML = Calendar._MN[month] + ", " + year;
	this.onSetTime();
	this.table.style.visibility = "visible";
	this._initMultipleDates();
	// PROFILE
	// this.tooltips.innerHTML = "Generated in " + ((new Date()) - today) + " ms";
};

Calendar.prototype._initMultipleDates = function() {
	if (this.multiple) {
		for (var i in this.multiple) {
			var cell = this.datesCells[i];
			var d = this.multiple[i];
			if (!d)
				continue;
			if (cell)
				cell.className += " selected";
		}
	}
};

Calendar.prototype._toggleMultipleDate = function(date) {
	if (this.multiple) {
		var ds = date.print("%Y%m%d");
		var cell = this.datesCells[ds];
		if (cell) {
			var d = this.multiple[ds];
			if (!d) {
				Calendar.addClass(cell, "selected");
				this.multiple[ds] = date;
			} else {
				Calendar.removeClass(cell, "selected");
				delete this.multiple[ds];
			}
		}
	}
};

Calendar.prototype.setDateToolTipHandler = function (unaryFunction) {
	this.getDateToolTip = unaryFunction;
};

/**
 *  Calls _init function above for going to a certain date (but only if the
 *  date is different than the currently selected one).
 */
Calendar.prototype.setDate = function (date) {
	if (!date.equalsTo(this.date)) {
		this._init(this.firstDayOfWeek, date);
	}
};

/**
 *  Refreshes the calendar.  Useful if the "disabledHandler" function is
 *  dynamic, meaning that the list of disabled date can change at runtime.
 *  Just * call this function if you think that the list of disabled dates
 *  should * change.
 */
Calendar.prototype.refresh = function () {
	this._init(this.firstDayOfWeek, this.date);
};

/** Modifies the "firstDayOfWeek" parameter (pass 0 for Synday, 1 for Monday, etc.). */
Calendar.prototype.setFirstDayOfWeek = function (firstDayOfWeek) {
	this._init(firstDayOfWeek, this.date);
	this._displayWeekdays();
};

/**
 *  Allows customization of what dates are enabled.  The "unaryFunction"
 *  parameter must be a function object that receives the date (as a JS Date
 *  object) and returns a boolean value.  If the returned value is true then
 *  the passed date will be marked as disabled.
 */
Calendar.prototype.setDateStatusHandler = Calendar.prototype.setDisabledHandler = function (unaryFunction) {
	this.getDateStatus = unaryFunction;
};

/** Customization of allowed year range for the calendar. */
Calendar.prototype.setRange = function (a, z) {
	this.minYear = a;
	this.maxYear = z;
};

/** Calls the first user handler (selectedHandler). */
Calendar.prototype.callHandler = function () {
	if (this.onSelected) {
		this.onSelected(this, this.date.print(this.dateFormat));
	}
};

/** Calls the second user handler (closeHandler). */
Calendar.prototype.callCloseHandler = function () {
	if (this.onClose) {
		this.onClose(this);
	}
	this.hideShowCovered();
};

/** Removes the calendar object from the DOM tree and destroys it. */
Calendar.prototype.destroy = function () {
	var el = this.element.parentNode;
	el.removeChild(this.element);
	Calendar._C = null;
	window._dynarch_popupCalendar = null;
};

/**
 *  Moves the calendar element to a different section in the DOM tree (changes
 *  its parent).
 */
Calendar.prototype.reparent = function (new_parent) {
	var el = this.element;
	el.parentNode.removeChild(el);
	new_parent.appendChild(el);
};

// This gets called when the user presses a mouse button anywhere in the
// document, if the calendar is shown.  If the click was outside the open
// calendar this function closes it.
Calendar._checkCalendar = function(ev) {
	var calendar = window._dynarch_popupCalendar;
	if (!calendar) {
		return false;
	}
	var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev);
	for (; el != null && el != calendar.element; el = el.parentNode);
	if (el == null) {
		// calls closeHandler which should hide the calendar.
		window._dynarch_popupCalendar.callCloseHandler();
		return Calendar.stopEvent(ev);
	}
};

/** Shows the calendar. */
Calendar.prototype.show = function () {
	var rows = this.table.getElementsByTagName("tr");
	for (var i = rows.length; i > 0;) {
		var row = rows[--i];
		Calendar.removeClass(row, "rowhilite");
		var cells = row.getElementsByTagName("td");
		for (var j = cells.length; j > 0;) {
			var cell = cells[--j];
			Calendar.removeClass(cell, "hilite");
			Calendar.removeClass(cell, "active");
		}
	}
	this.element.style.display = "block";
	this.hidden = false;
	if (this.isPopup) {
		window._dynarch_popupCalendar = this;
		Calendar.addEvent(document, "keydown", Calendar._keyEvent);
		Calendar.addEvent(document, "keypress", Calendar._keyEvent);
		Calendar.addEvent(document, "mousedown", Calendar._checkCalendar);
	}
	this.hideShowCovered();
};

/**
 *  Hides the calendar.  Also removes any "hilite" from the class of any TD
 *  element.
 */
Calendar.prototype.hide = function () {
	if (this.isPopup) {
		Calendar.removeEvent(document, "keydown", Calendar._keyEvent);
		Calendar.removeEvent(document, "keypress", Calendar._keyEvent);
		Calendar.removeEvent(document, "mousedown", Calendar._checkCalendar);
	}
	this.element.style.display = "none";
	this.hidden = true;
	this.hideShowCovered();
};

/**
 *  Shows the calendar at a given absolute position (beware that, depending on
 *  the calendar element style -- position property -- this might be relative
 *  to the parent's containing rectangle).
 */
Calendar.prototype.showAt = function (x, y) {
	var s = this.element.style;
	s.left = x + "px";
	s.top = y + "px";
	this.show();
};
  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }
  function getCurrentPos(el, p){
	  var YY = findPosY(el);
	  YY = YY-80;
	  var r = { x: p.x, y: YY};
	  return r;
  }
/** Shows the calendar near a given element. */
Calendar.prototype.showAtElement = function (el, opts) {
	var self = this;
	//var timingRow = Calendar.eventTimingRow(el);
	//var serachForm = Calendar.newSearchForm(el);
	var p = Calendar.getAbsolutePos(el);
	//getCurrentPos(el, p);
	//if(timingRow)  	p = Calendar.getAbsolutePosIE7(el);
	//if(serachForm)  p = Calendar.getSearchAbsolutePosIE7(el);
	if (!opts || typeof opts != "string") {
		this.showAt(p.x, p.y + el.offsetHeight);
		return true;
	}
	function fixPosition(box) {
		if (box.x < 0)
			box.x = 0;
		if (box.y < 0)
			box.y = 0;
		var cp = document.createElement("div");
		var s = cp.style;
		s.position = "absolute";
		s.right = s.bottom = s.width = s.height = "0px";
		document.body.appendChild(cp);
		var br = Calendar.getAbsolutePos(cp);
		//if(timingRow) br = Calendar.getAbsolutePosIE7(cp);
		//if(serachForm) br =  Calendar.getSearchAbsolutePosIE7(cp);
		document.body.removeChild(cp);
		if (Calendar.is_ie) {
			br.y += document.body.scrollTop;
			br.x += document.body.scrollLeft;
		} else {
			br.y += window.scrollY;
			br.x += window.scrollX;
		}
		var tmp = box.x + box.width - br.x;
		if (tmp > 0) box.x -= tmp;
		tmp = box.y + box.height - br.y;
		if (tmp > 0) box.y -= tmp;
	};
	this.element.style.display = "block";
	Calendar.continuation_for_the_fucking_khtml_browser = function() {
		var w = self.element.offsetWidth;
		var h = self.element.offsetHeight;
		self.element.style.display = "none";
		var valign = opts.substr(0, 1);
		var halign = "l";
		if (opts.length > 1) {
			halign = opts.substr(1, 1);
		}
		// vertical alignment
		switch (valign) {
		    case "T": p.y -= h; break;
		    case "B": p.y += el.offsetHeight; break;
		    case "C": p.y += (el.offsetHeight - h) / 2; break;
		    case "t": p.y += el.offsetHeight - h; break;
		    case "b": break; // already there
		}
		// horizontal alignment
		switch (halign) {
		    case "L": p.x -= w; break;
		    case "R": p.x += el.offsetWidth; break;
		    case "C": p.x += (el.offsetWidth - w) / 2; break;
		    case "l": p.x += el.offsetWidth - w; break;
		    case "r": break; // already there
		}
		p.width = w;
		p.height = h + 40;
		self.monthsCombo.style.display = "none";
		fixPosition(p);
		if(Calendar.is_ie){
		p = getCurrentPos(window.event.srcElement, p);
		}
		self.showAt(p.x, p.y);
	};
	if (Calendar.is_khtml)
		setTimeout("Calendar.continuation_for_the_fucking_khtml_browser()", 10);
	else
		Calendar.continuation_for_the_fucking_khtml_browser();
};

/** Customizes the date format. */
Calendar.prototype.setDateFormat = function (str) {
	this.dateFormat = str;
};

/** Customizes the tooltip date format. */
Calendar.prototype.setTtDateFormat = function (str) {
	this.ttDateFormat = str;
};

/**
 *  Tries to identify the date represented in a string.  If successful it also
 *  calls this.setDate which moves the calendar to the given date.
 */
Calendar.prototype.parseDate = function(str, fmt) {
	if (!fmt)
		fmt = this.dateFormat;
	this.setDate(Date.parseDate(str, fmt));
};

Calendar.prototype.hideShowCovered = function () {
	if (!Calendar.is_ie && !Calendar.is_opera)
		return;
	function getVisib(obj){
		var value = obj.style.visibility;
		if (!value) {
			if (document.defaultView && typeof (document.defaultView.getComputedStyle) == "function") { // Gecko, W3C
				if (!Calendar.is_khtml)
					value = document.defaultView.
						getComputedStyle(obj, "").getPropertyValue("visibility");
				else
					value = '';
			} else if (obj.currentStyle) { // IE
				value = obj.currentStyle.visibility;
			} else
				value = '';
		}
		return value;
	};

	var tags = new Array("applet", "iframe", "select");
	var el = this.element;

	var p = Calendar.getAbsolutePos(el);
	var EX1 = p.x;
	var EX2 = el.offsetWidth + EX1;
	var EY1 = p.y;
	var EY2 = el.offsetHeight + EY1;

	for (var k = tags.length; k > 0; ) {
		var ar = document.getElementsByTagName(tags[--k]);
		var cc = null;

		for (var i = ar.length; i > 0;) {
			cc = ar[--i];

			p = Calendar.getAbsolutePos(cc);
			var CX1 = p.x;
			var CX2 = cc.offsetWidth + CX1;
			var CY1 = p.y;
			var CY2 = cc.offsetHeight + CY1;

			if (this.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) {
				if (!cc.__msh_save_visibility) {
					cc.__msh_save_visibility = getVisib(cc);
				}
				cc.style.visibility = cc.__msh_save_visibility;
			} else {
				if (!cc.__msh_save_visibility) {
					cc.__msh_save_visibility = getVisib(cc);
				}
				cc.style.visibility = "hidden";
			}
		}
	}
};

/** Internal function; it displays the bar with the names of the weekday. */
Calendar.prototype._displayWeekdays = function () {
	var fdow = this.firstDayOfWeek;
	var cell = this.firstdayname;
	var weekend = Calendar._TT["WEEKEND"];
	for (var i = 0; i < 7; ++i) {
		cell.className = "day name";
		var realday = (i + fdow) % 7;
		if (i) {
			cell.ttip = Calendar._TT["DAY_FIRST"].replace("%s", Calendar._DN[realday]);
			cell.navtype = 100;
			cell.calendar = this;
			cell.fdow = realday;
			Calendar._add_evs(cell);
		}
		if (weekend.indexOf(realday.toString()) != -1) {
			Calendar.addClass(cell, "weekend");
		}
		cell.innerHTML = Calendar._SDN[(i + fdow) % 7];
		cell = cell.nextSibling;
	}
};

/** Internal function.  Hides all combo boxes that might be displayed. */
Calendar.prototype._hideCombos = function () {
	this.monthsCombo.style.display = "none";
	this.yearsCombo.style.display = "none";
};

/** Internal function.  Starts dragging the element. */
Calendar.prototype._dragStart = function (ev) {
	if (this.dragging) {
		return;
	}
	this.dragging = true;
	var posX;
	var posY;
	if (Calendar.is_ie) {
		posY = window.event.clientY + document.body.scrollTop;
		posX = window.event.clientX + document.body.scrollLeft;
	} else {
		posY = ev.clientY + window.scrollY;
		posX = ev.clientX + window.scrollX;
	}
	var st = this.element.style;
	this.xOffs = posX - parseInt(st.left);
	this.yOffs = posY - parseInt(st.top);
	with (Calendar) {
		addEvent(document, "mousemove", calDragIt);
		addEvent(document, "mouseup", calDragEnd);
	}
};

// BEGIN: DATE OBJECT PATCHES

/** Adds the number of days array to the Date object. */
Date._MD = new Array(31,28,31,30,31,30,31,31,30,31,30,31);

/** Constants used for time computations */
Date.SECOND = 1000 /* milliseconds */;
Date.MINUTE = 60 * Date.SECOND;
Date.HOUR   = 60 * Date.MINUTE;
Date.DAY    = 24 * Date.HOUR;
Date.WEEK   =  7 * Date.DAY;

Date.parseDate = function(str, fmt) {
	var today = new Date();
	var y = 0;
	var m = -1;
	var d = 0;
	var a = str.split(/\W+/);
	var b = fmt.match(/%./g);
	var i = 0, j = 0;
	var hr = 0;
	var min = 0;
	for (i = 0; i < a.length; ++i) {
		if (!a[i])
			continue;
		switch (b[i]) {
		    case "%d":
		    case "%e":
			d = parseInt(a[i], 10);
			break;

		    case "%m":
			m = parseInt(a[i], 10) - 1;
			break;

		    case "%Y":
		    case "%y":
			y = parseInt(a[i], 10);
			(y < 100) && (y += (y > 29) ? 1900 : 2000);
			break;

		    case "%b":
		    case "%B":
			for (j = 0; j < 12; ++j) {
				if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { m = j; break; }
			}
			break;

		    case "%H":
		    case "%I":
		    case "%k":
		    case "%l":
			hr = parseInt(a[i], 10);
			break;

		    case "%P":
		    case "%p":
			if (/pm/i.test(a[i]) && hr < 12)
				hr += 12;
			else if (/am/i.test(a[i]) && hr >= 12)
				hr -= 12;
			break;

		    case "%M":
			min = parseInt(a[i], 10);
			break;
		}
	}
	if (isNaN(y)) y = today.getFullYear();
	if (isNaN(m)) m = today.getMonth();
	if (isNaN(d)) d = today.getDate();
	if (isNaN(hr)) hr = today.getHours();
	if (isNaN(min)) min = today.getMinutes();
	if (y != 0 && m != -1 && d != 0)
		return new Date(y, m, d, hr, min, 0);
	y = 0; m = -1; d = 0;
	for (i = 0; i < a.length; ++i) {
		if (a[i].search(/[a-zA-Z]+/) != -1) {
			var t = -1;
			for (j = 0; j < 12; ++j) {
				if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { t = j; break; }
			}
			if (t != -1) {
				if (m != -1) {
					d = m+1;
				}
				m = t;
			}
		} else if (parseInt(a[i], 10) <= 12 && m == -1) {
			m = a[i]-1;
		} else if (parseInt(a[i], 10) > 31 && y == 0) {
			y = parseInt(a[i], 10);
			(y < 100) && (y += (y > 29) ? 1900 : 2000);
		} else if (d == 0) {
			d = a[i];
		}
	}
	if (y == 0)
		y = today.getFullYear();
	if (m != -1 && d != 0)
		return new Date(y, m, d, hr, min, 0);
	return today;
};

/** Returns the number of days in the current month */
Date.prototype.getMonthDays = function(month) {
	var year = this.getFullYear();
	if (typeof month == "undefined") {
		month = this.getMonth();
	}
	if (((0 == (year%4)) && ( (0 != (year%100)) || (0 == (year%400)))) && month == 1) {
		return 29;
	} else {
		return Date._MD[month];
	}
};

/** Returns the number of day in the year. */
Date.prototype.getDayOfYear = function() {
	var now = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
	var then = new Date(this.getFullYear(), 0, 0, 0, 0, 0);
	var time = now - then;
	return Math.floor(time / Date.DAY);
};

/** Returns the number of the week in year, as defined in ISO 8601. */
Date.prototype.getWeekNumber = function() {
	var d = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
	var DoW = d.getDay();
	d.setDate(d.getDate() - (DoW + 6) % 7 + 3); // Nearest Thu
	var ms = d.valueOf(); // GMT
	d.setMonth(0);
	d.setDate(4); // Thu in Week 1
	return Math.round((ms - d.valueOf()) / (7 * 864e5)) + 1;
};

/** Checks date and time equality */
Date.prototype.equalsTo = function(date) {
	return ((this.getFullYear() == date.getFullYear()) &&
		(this.getMonth() == date.getMonth()) &&
		(this.getDate() == date.getDate()) &&
		(this.getHours() == date.getHours()) &&
		(this.getMinutes() == date.getMinutes()));
};

/** Set only the year, month, date parts (keep existing time) */
Date.prototype.setDateOnly = function(date) {
	var tmp = new Date(date);
	this.setDate(1);
	this.setFullYear(tmp.getFullYear());
	this.setMonth(tmp.getMonth());
	this.setDate(tmp.getDate());
};

/** Prints the date in a string according to the given format. */
Date.prototype.print = function (str) {
	var m = this.getMonth();
	var d = this.getDate();
	var y = this.getFullYear();
	var wn = this.getWeekNumber();
	var w = this.getDay();
	var s = {};
	var hr = this.getHours();
	var pm = (hr >= 12);
	var ir = (pm) ? (hr - 12) : hr;
	var dy = this.getDayOfYear();
	if (ir == 0)
		ir = 12;
	var min = this.getMinutes();
	var sec = this.getSeconds();
	s["%a"] = Calendar._SDN[w]; // abbreviated weekday name [FIXME: I18N]
	s["%A"] = Calendar._DN[w]; // full weekday name
	s["%b"] = Calendar._SMN[m]; // abbreviated month name [FIXME: I18N]
	s["%B"] = Calendar._MN[m]; // full month name
	// FIXME: %c : preferred date and time representation for the current locale
	s["%C"] = 1 + Math.floor(y / 100); // the century number
	s["%d"] = (d < 10) ? ("0" + d) : d; // the day of the month (range 01 to 31)
	s["%e"] = d; // the day of the month (range 1 to 31)
	// FIXME: %D : american date style: %m/%d/%y
	// FIXME: %E, %F, %G, %g, %h (man strftime)
	s["%H"] = (hr < 10) ? ("0" + hr) : hr; // hour, range 00 to 23 (24h format)
	s["%I"] = (ir < 10) ? ("0" + ir) : ir; // hour, range 01 to 12 (12h format)
	s["%j"] = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy; // day of the year (range 001 to 366)
	s["%k"] = hr;		// hour, range 0 to 23 (24h format)
	s["%l"] = ir;		// hour, range 1 to 12 (12h format)
	s["%m"] = (m < 9) ? ("0" + (1+m)) : (1+m); // month, range 01 to 12
	s["%M"] = (min < 10) ? ("0" + min) : min; // minute, range 00 to 59
	s["%n"] = "\n";		// a newline character
	s["%p"] = pm ? "PM" : "AM";
	s["%P"] = pm ? "pm" : "am";
	// FIXME: %r : the time in am/pm notation %I:%M:%S %p
	// FIXME: %R : the time in 24-hour notation %H:%M
	s["%s"] = Math.floor(this.getTime() / 1000);
	s["%S"] = (sec < 10) ? ("0" + sec) : sec; // seconds, range 00 to 59
	s["%t"] = "\t";		// a tab character
	// FIXME: %T : the time in 24-hour notation (%H:%M:%S)
	s["%U"] = s["%W"] = s["%V"] = (wn < 10) ? ("0" + wn) : wn;
	s["%u"] = w + 1;	// the day of the week (range 1 to 7, 1 = MON)
	s["%w"] = w;		// the day of the week (range 0 to 6, 0 = SUN)
	// FIXME: %x : preferred date representation for the current locale without the time
	// FIXME: %X : preferred time representation for the current locale without the date
	s["%y"] = ('' + y).substr(2, 2); // year without the century (range 00 to 99)
	s["%Y"] = y;		// year with the century
	s["%%"] = "%";		// a literal '%' character

	var re = /%./g;
	if (!Calendar.is_ie5 && !Calendar.is_khtml)
		return str.replace(re, function (par) { return s[par] || par; });

	var a = str.match(re);
	for (var i = 0; i < a.length; i++) {
		var tmp = s[a[i]];
		if (tmp) {
			re = new RegExp(a[i], 'g');
			str = str.replace(re, tmp);
		}
	}

	return str;
};

Date.prototype.__msh_oldSetFullYear = Date.prototype.setFullYear;
Date.prototype.setFullYear = function(y) {
	var d = new Date(this);
	d.__msh_oldSetFullYear(y);
	if (d.getMonth() != this.getMonth())
		this.setDate(28);
	this.__msh_oldSetFullYear(y);
};

// END: DATE OBJECT PATCHES


// global object that remembers the calendar
window._dynarch_popupCalendar = null;
/*CALENDAR.JS END*/


/*CALENDAR-EN.JS START*/

// full day names
Calendar._DN = new Array
("Sunday",
 "Monday",
 "Tuesday",
 "Wednesday",
 "Thursday",
 "Friday",
 "Saturday",
 "Sunday");

// short day names
Calendar._SDN = new Array
("Su ",
 "Mo ",
 "Tu ",
 "We ",
 "Th ",
 "Fr ",
 "Sa",
 "Su");

// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 0;

// full month names
Calendar._MN = new Array
("January",
 "February",
 "March",
 "April",
 "May",
 "June",
 "July",
 "August",
 "September",
 "October",
 "November",
 "December");

// short month names
Calendar._SMN = new Array
("Jan",
 "Feb",
 "Mar",
 "Apr",
 "May",
 "Jun",
 "Jul",
 "Aug",
 "Sep",
 "Oct",
 "Nov",
 "Dec");

// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "About the calendar";

Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"For latest version visit: http://www.dynarch.com/projects/calendar/\n" +
"Distributed under GNU LGPL.  See http://gnu.org/licenses/lgpl.html for details." +
"\n\n" +
"Date selection:\n" +
"- Use the \xab, \xbb buttons to select year\n" +
"- Use the " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " buttons to select month\n" +
"- Hold mouse button on any of the above buttons for faster selection.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Time selection:\n" +
"- Click on any of the time parts to increase it\n" +
"- or Shift-click to decrease it\n" +
"- or click and drag for faster selection.";

Calendar._TT["PREV_YEAR"] = "Prev. year (hold for menu)";
Calendar._TT["PREV_MONTH"] = "Prev. month (hold for menu)";
Calendar._TT["GO_TODAY"] = "Go Today";
Calendar._TT["NEXT_MONTH"] = "Next month (hold for menu)";
Calendar._TT["NEXT_YEAR"] = "Next year (hold for menu)";
Calendar._TT["SEL_DATE"] = "Select date";
Calendar._TT["DRAG_TO_MOVE"] = "Drag to move";
Calendar._TT["PART_TODAY"] = " (today)";

// the following is to inform that "%s" is to be the first day of week
// %s will be replaced with the day name.
Calendar._TT["DAY_FIRST"] = "Display %s first";

// This may be locale-dependent.  It specifies the week-end days, as an array
// of comma-separated numbers.  The numbers are from 0 to 6: 0 means Sunday, 1
// means Monday, etc.
Calendar._TT["WEEKEND"] = "0,6";

Calendar._TT["CLOSE"] = "Close";
Calendar._TT["TODAY"] = "Today";
Calendar._TT["TIME_PART"] = "(Shift-)Click or drag to change value";

// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e";

Calendar._TT["WK"] = "wk";
Calendar._TT["TIME"] = "Time:";

/*CALENDAR-EN.JS END*/


/*CALENDAR-SETUP.JS START*/
Calendar.setup = function (params) {
	function param_default(pname, def) { if (typeof params[pname] == "undefined") { params[pname] = def; } };

	param_default("inputField",     null);
	param_default("displayArea",    null);
	param_default("button",         null);
	param_default("eventName",      "click");
	param_default("ifFormat",       "%Y/%m/%d");
	param_default("daFormat",       "%Y/%m/%d");
	param_default("singleClick",    true);
	param_default("disableFunc",    null);
	param_default("dateStatusFunc", params["disableFunc"]);	// takes precedence if both are defined
	param_default("dateText",       null);
	param_default("firstDay",       null);
	param_default("align",          "Br");
	param_default("range",          [1900, 2999]);
	param_default("weekNumbers",    true);
	param_default("flat",           null);
	param_default("flatCallback",   null);
	param_default("onSelect",       null);
	param_default("onClose",        null);
	param_default("onUpdate",       null);
	param_default("date",           null);
	param_default("showsTime",      false);
	param_default("timeFormat",     "24");
	param_default("electric",       true);
	param_default("step",           2);
	param_default("position",       null);
	param_default("cache",          false);
	param_default("showOthers",     false);
	param_default("multiple",       null);

	var tmp = ["inputField", "displayArea", "button"];
	for (var i in tmp) {
		if (typeof params[tmp[i]] == "string") {
			params[tmp[i]] = document.getElementById(params[tmp[i]]);
		}
	}
	if (!(params.flat || params.multiple || params.inputField || params.displayArea || params.button)) {
		alert("Calendar.setup:\n  Nothing to setup (no fields found).  Please check your code");
		return false;
	}
	

	function onSelect(cal) {
		var p = cal.params;
		var update = (cal.dateClicked || p.electric);
		if (update && p.inputField) {
			p.inputField.value = cal.date.print(p.ifFormat);
			if (typeof p.inputField.onchange == "function")
				p.inputField.onchange();
		}
		if (update && p.displayArea)
		 /*	 p.displayArea.innerHTML = cal.date.print(p.daFormat) */ ;
		if (update && typeof p.onUpdate == "function")
			p.onUpdate(cal);
		if (update && p.flat) {
			if (typeof p.flatCallback == "function")
				p.flatCallback(cal);
		}
		if (update && p.singleClick && cal.dateClicked)
			cal.callCloseHandler();
	};

	if (params.flat != null) {
		if (typeof params.flat == "string")
			params.flat = document.getElementById(params.flat);
		if (!params.flat) {
			alert("Calendar.setup:\n  Flat specified but can't find parent.");
			return false;
		}
		var cal = new Calendar(params.firstDay, params.date, params.onSelect || onSelect);
		cal.showsOtherMonths = params.showOthers;
		cal.showsTime = params.showsTime;
		cal.time24 = (params.timeFormat == "24");
		cal.params = params;
		cal.weekNumbers = params.weekNumbers;
		cal.setRange(params.range[0], params.range[1]);
		cal.setDateStatusHandler(params.dateStatusFunc);
		cal.getDateText = params.dateText;
		if (params.ifFormat) {
			cal.setDateFormat(params.ifFormat);
		}
		if (params.inputField && typeof params.inputField.value == "string") {
			cal.parseDate(params.inputField.value);
		}
		cal.create(params.flat);
		cal.show();
		return false;
	}

	var triggerEl = params.button || params.displayArea || params.inputField;
	triggerEl["on" + params.eventName] = function() {
		var dateEl = params.inputField || params.displayArea;
		var dateFmt = params.inputField ? params.ifFormat : params.daFormat;
		var mustCreate = false;
		var cal = window.calendar;
		if (dateEl)
			params.date = Date.parseDate(dateEl.value || dateEl.innerHTML, dateFmt);
		if (!(cal && params.cache)) {
			window.calendar = cal = new Calendar(params.firstDay,
							     params.date,
							     params.onSelect || onSelect,
							     params.onClose || function(cal) { cal.hide(); });
			cal.showsTime = params.showsTime;
			cal.time24 = (params.timeFormat == "24");
			cal.weekNumbers = params.weekNumbers;
			mustCreate = true;
		} else {
			if (params.date)
				cal.setDate(params.date);
			cal.hide();
		}
		if (params.multiple) {
			cal.multiple = {};
			for (var i = params.multiple.length; --i >= 0;) {
				var d = params.multiple[i];
				var ds = d.print("%Y%m%d");
				cal.multiple[ds] = d;
			}
		}
		cal.showsOtherMonths = params.showOthers;
		cal.yearStep = params.step;
		cal.setRange(params.range[0], params.range[1]);
		cal.params = params;
		cal.setDateStatusHandler(params.dateStatusFunc);
		cal.getDateText = params.dateText;
		cal.setDateFormat(dateFmt);
		if (mustCreate)
			cal.create();
		//cal.refresh();
		
		if (!params.position) {
			if(params.button != null) {
				if(params.button.name == "gdp_when4") {
					changeDateCriteria2(5);	
					getDiv('showDate2', 'chooseDate2');
					cal.showAtElement(params.inputField);
					document.getElementById('gdp_when4').checked = true;
					document.getElementById('gdp_when3').checked = false;
					return true;
				} else if(params.button.name == "gdp_when2") {
					changeDateCriteria(5);	
					getDiv('showDate', 'chooseDate');
					cal.showAtElement(params.inputField);
					document.getElementById('gdp_when2').checked = true;
					document.getElementById('gdp_when1').checked = false;
					return true;
				}
			} else {
			cal.showAtElement(params.button || params.displayArea || params.inputField, params.align);
			}
		} else {
			cal.showAt(params.position[0], params.position[1]);
		}
		return false;
	};

	return cal;
};
/*CALENDAR-SETUP.JS START*/



    var userFromLink = '';
      function loginFBUser(){
      			//hideDivs("fbSignIn");
				var session = FB.Facebook.apiClient.get_session();
				var uid = session.uid;
				var sessionid = session.session_key;
		       	setCookie("login_source", "facebook", 1);
	  			UserManager.loginFBUser(uid, sessionid, checkLoginHandlerFB);
      }

	function loginFB(fromLink){
		userFromLink = fromLink;
		//SNG_closeFancyBox();
	      FB.Bootstrap.ensureInit(function () {
	      	FB.Connect.requireSession();	      	
	      	FB.Facebook.get_sessionState().waitUntilReady(function() { 
				loginFBUser();
			});
	  	  });
	}
	
	function checkSessionState(){
		var sessionWaitable = FB.Facebook.get_sessionWaitable();
		if (sessionWaitable.get_isReady() && sessionWaitable.result) {
			loginFBUser();
		}	
	}

	function closeWindow(win_name){
		hideDivs(win_name);
		closeFBPopMainDiv();
	}
	
	function closeFBPopMainDiv(){
			_$id('fbPopupMainDiv').style.display='none';
	}
	
	function showFBPopMainDiv(){

		if(userFromLink=='signIn'){ // User comming from signin page
			hideAllSignInUPPops();
			$('#fbSignUpPopup').show();
			SNG_resizeFancyBox();
		}else{//user clicked sign in using facebook
			$('#whichLink').val('Facebook');
			$('a#signinlink').click();
		}
	}
	
	//function showFBRegistrationForm(){
	//			_$id('mainDiv_fb').style.zIndex = "55";
	//			showDivs('tbl_registration_fb');
	//}

	function registerFBUser(){
				var session = FB.Facebook.apiClient.get_session();
				var uid= session.uid;
				var sessionid= session.session_key;
		        setCookie("login_source", "facebook", 1);
		        var remFlag = false;
		        
		        var nickName = $('#nickName_fb').val();
		        var emailId = $('#email_fb').val();
		        var postCode = $('#postcode_fb').val();
		        var termsChecked =  $('#signupfb_termsAndConditions').is(':checked');
				
				
		        if(trim(emailId) == "" || emailId == SIN_EMAIL){
		        	SNG_displayLoginError($('#email_fb'), 'Please enter your email address to sign up');
		        }else if(!(checkEmail(emailId))){
		        	SNG_displayLoginError($('#email_fb'), 'Please enter a valid email address');
		        }else if(trim(postCode) == '' || postCode == SUP_POSTCODE){
		        	SNG_displayLoginError($('#postcode_fb'), 'Please enter your postcode');
		        }else if(!validatePostCode(postCode) || postCode == SUP_POSTCODE){
		        	SNG_displayLoginError($('#postcode_fb'), 'Please enter a valid postcode');
		        }else if(trim(nickName) == '' || nickName == SUP_NICKNAME){
		        	SNG_displayLoginError($('#nickName_fb'), 'Please enter a Nickname');
		        }else if(!termsChecked){
		        	SNG_displayLoginError($('#termsAndConditionsFB'), 'Please read and agree to the woZZon Terms & Conditions');
		        }else{
					var productServicesChkBox = $('#signupfb_productServices');
					
					if(productServicesChkBox.length> 0 && productServicesChkBox.is(':checked')){
					remFlag = true;
					}else{remFlag = false;}
					
		        	UserManager.registerFBUser(remFlag, postCode, emailId, nickName, uid, sessionid, registerationHandlerFB);
		        }
		        
		        /*
		        if(trim((_$id('nickName_fb').value))!=""){
		        	
		       		if(checkEmail(_$id('email_fb').value)){
				        _$id('registerationError_fb').innerHTML="";
						UserManager.registerFBUser(_$id('postcode_fb').value, _$id('email_fb').value, _$id('nickName_fb').value, uid, sessionid, registerationHandlerFB);
						
					}else{
						_$id('registerationError_fb').innerHTML="Please enter valid email address.";
					}
				}else{
						_$id('registerationError_fb').innerHTML="Please enter nick name.";
				}
				*/

	}
	
	function hideLoginTableFB() {
		hideDivs('tbl_registration_fb');
		hideDivs('tbl_showNickHelp_fb');
	}

	function checkLoginHandlerFB(source) {
		//var obj = _$id("loginError");
		//var div = "";
		//div = "loginError";
		//document.getElementById('loginError').style.display = '';
		var cntx = document.getElementById('cntx');
		if(cntx == null) cntx = "";
		else cntx = cntx.value;
				
	     if( source == "error" ) 
			displayMsg(div,"Error processing your request.");	
		  else if( source == "Inactive")   
			displayMsg(div,"Please activate your account");   
		  else if( source == "Invalid") {
			displayMsg(div,"The email address or password you provided does not match our records");			
		  }
		  else if (source == "errorLoginFBUser"){
			  displayMsg(div,"Error while sign in using Facebook");			
		  }else if (source == "deleteduser"){
			  //showFBPopMainDiv();
			  //showDivs('deletedUserPopup');
			  if(userFromLink=='signIn'){
				  SNG_closeFancyBox();
			  }
			  SNG_messagePopup('reactivateFBAccount');
			  
		  }else if (source == "errorRegisterFBUser"){
			  displayMsg(div,"Error while registering user");			
	      }else if(source == "fbUserNotUpdated"){
		     var fbSession = FB.Facebook.apiClient.get_session();
  			 var uid= fbSession.uid;	
		     //clearRegistrationWindow('true');
		     showFBProfile();
		     UserManager.getFacebookUserName(uid, fillFBUserNameHandler);
		     showFBPopMainDiv();
	      	 //showFBRegistrationForm();
			 
	      }else {  
			//hideDivs('tbl_login');
	    	 if(!(userFromLink && userFromLink == 'FBSignUp')){
	    		 SNG_closeFancyBox(); 
	    	 }
	    	  
			if(_$id('welcomenote')&& source != 'UserLogged') {	
			var fbSession = FB.Facebook.apiClient.get_session();
				var uid= fbSession.uid;	
				source =  " <span><fb:name useyou='false' uid='"+ uid + "'></fb:name></span>"
				_$id("welcomenote").innerHTML = _$id("welcomenote").innerHTML = "Welcome:  "+ source; 

				_$id('welcomenote').style.display = "";
				reRenderXFBMLTags();
				askExtendedPermission();
				if(_$id('isUserLogged')) _$id('isUserLogged').value ='Yes';
				
			} else if(_$id('welcomenote_mapView')&& source != 'UserLogged') {
				_$id("welcomenote_mapView").innerHTML = _$id("welcomenote_mapView").innerHTML = "Welcome "+ source;
				_$id('welcomenote_mapView').style.display = "";
				if(_$id('isUserLogged')) _$id('isUserLogged').value ='Yes';
			}
		
			_$id("wozzon_header_logStatus").style.display = '';
			if(_$id("wozzon_header_logStatus") != null)  {
				$('.SNG_topSection ul').css('width','300px');
				//$('#welcomenote').css('width','480px');
				hideDivs('wozzon_header_signup');
				hideDivs('wozzon_header_facebook');
				_$id('wozzon_header_myWozzonStatus').innerHTML = "<a id='id_myWozzon' href='"+cntx+"controller.web?method=myWozzon' >My woZZon</a>" ;
				_$id("wozzon_header_logStatus").innerHTML ="<a href='javascript:logout(1)'>Sign out</a>";
			}
		
			window.setTimeout("SNG_checkLoginHandler('UserLogged')", 1500);
		 }	
	}
	
	function activateFBUser(){
		UserManager.activateFBUser(activationHandlerFB);
	}
	
	function activationHandlerFB(source){
		
		var cntx = document.getElementById('cntx');
		if(cntx == null) cntx = "";
		else cntx = cntx.value;
			
		SNG_closeMessage();
		
	     if( source == "error" ){ 
		    SNG_alert("Error processing your request.");
	      }else if( source == "Inactive")  {
		 	SNG_alert("Please activate your account");
		  }else if( source == "Invalid") {
			  SNG_alert("Facebook id or session key is invalid, please relogin.");
		  }else if (source == "errorActivatingFBUser"){
			  SNG_alert("Error while activating using Facebook account");
		  }else {  
				//closeFBPopMainDiv();
				var isreviewEvent = _$id('isReviewEvent')
				var isreview =_$id('isReview')
				
				if( !( (isreview && isreview.value == "Yes") ||  (isreviewEvent && isreviewEvent.value == "Yes") || 
							  ( _$id('whichLink').value == "showSubmitChanges" ) )  ) {		
				   
				}
				SNG_messagePopup('registerationSuccess');
				checkLoginHandlerFB(_$id('nickName_fb').value);
		 }	
	}
	
	function askExtendedPermission(){
		FB.Bootstrap.ensureInit(function () {
	          // Check if user has permission, if not invoke dialog.
	         var permission = 'publish_stream';
	       	 FB.Connect.requireSession(function(){
	            //check is user already granted for this permission or not
	            var hasPermission = 'false';
	            FB.Facebook.apiClient.users_hasAppPermission(permission,
	            function(hasPerm) {
	                // prompt offline permission
	                if (hasPerm == 0) {
	                    // render the permission dialog
	                    FB.Connect.showPermissionDialog(permission,
	                    function(result){
	                        if (null == result || result == ''){
	                            hasPermission = 'false';
	                        }else{
   	                            hasPermission = 'true';
	                        }
	                        UserManager.saveExtendedPermission('publish_stream', hasPermission, function(data){});
	                    }, false, null);
	                } else {
	                    hasPermission = 'true';
	                    UserManager.saveExtendedPermission('publish_stream', hasPermission, function(data){});
	                }
	            });
	            
	        });
	    });
	}

	function fillFBUserNameHandler(data){
		 var userName = replaceAll(data.toLowerCase(),' ','');
		 _$id('nickName_fb').value = userName;

	}
	
	function showFBProfile(){
		var fbSession = FB.Facebook.apiClient.get_session();
  		var uid= fbSession.uid;	
		$('.fbImage').html("<fb:profile-pic uid='" + uid + "' facebook-logo='true' width='52' height='52' ></fb:profile-pic>");
		$('.fbUserNickname').html("<fb:name useyou='false' linked='false' uid='"+ uid + "'></fb:name>");
		reRenderXFBMLTags();
	}
	
	 function registerationHandlerFB(source) {	
		var obj = _$id("registerationError_fb");
		var div = "";
		div = "registerationError_fb";	
		showDivs(div);	
		if( source == "1" ){ 
			//var msg = "<b>This email address has already been taken.</b> Do you have woZZon account with this email? <br/>" +
			//	"Yes! Then login with <b>I ALREADY HAVE WOZZON ACCOUNT</b> to sync your woZZon and Facebook Account <b>OR</b> " +
			//	 "Login with woZZon Account"; 
			//displayMsg(div,msg);
			//alert(msg);
			SNG_displayLoginError($('#email_fb'), 'This email address has already been taken.');
		}else if(source == "2")  SNG_displayLoginError($('#nickName_fb'), "Nickname already in use, please enter another Nickname"); //displayMsg(div,"Nickname already in use, please select another Nickname");
		else if( source == "3") SNG_alert("Error registering user"); //displayMsg(div,"Error registering user");
		else if(source == "4")	SNG_displayLoginError($('#nickName_fb'), 'Please enter a Nickname'); //displayMsg(div,"Please enter nick name.");
	    else if(source == "5" ) SNG_alert("Please enter password."); //displayMsg(div,"Please enter password.");
	    else if(source == "6" ) SNG_displayLoginError($('#email_fb'), 'Please enter your email address to sign up'); //displayMsg(div,"Please enter  email address.");
		else if(source == "ReRegistered")  {	
				//hideLoginTable();
				_$id('tbl_reRegister').style.display = '';
			}
	    else if(source == "Registered")  {		
		  	//closeFBPopMainDiv();
		  	//hideDivs('tbl_registration_fb');			
			var isreviewEvent = _$id('isReviewEvent')
			var isreview =_$id('isReview')
			
			if( !( (isreview && isreview.value == "Yes") ||  (isreviewEvent && isreviewEvent.value == "Yes") || 
						  ( _$id('whichLink').value == "showSubmitChanges" ) )  ) {		
			  
			}
			userFromLink = "FBSignUp";
			hideAllSignInUPPops();
			$('.successUserNickname').html($('#nickName_fb').val());
			$('#signUpSuccess').show();
			SNG_resizeFancyBox();
			checkLoginHandlerFB(_$id('nickName_fb').value);
		 } else  {          
		  	obj.innerHTML = source;
		}
	}
	
	function loginWithWozzon(){
		//hideDivs("tbl_registration_fb");
		//showDivs("tbl_existing_account");
		showFBProfile();
	}
	
	//function hideExistingAccTbl(){
	//	hideDivs("tbl_existing_account");
	//}
	
	
	function loginExistingAccount(){
		var emailValue;
		var passwordValue;
		
		emailValue = $('#email_exst_woz').val();
		passwordValue = $('#password_exst_woz').val();
		
		if(trim(emailValue) == "" || emailValue == SIN_EMAIL){
        	SNG_displayLoginError($('#email_exst_woz'), 'Please enter your existing woZZon account details');
        }else if(!(checkEmail(emailValue))){
        	SNG_displayLoginError($('#email_exst_woz'), 'Please enter a valid email address');
        }else if(trim(passwordValue) == '' || passwordValue == SIN_PASSWORD){
        	SNG_displayLoginError($('#password_exst_woz'), 'Please enter your existing woZZon password');
        	$('#password_exst_woz_text').focus();
        }else{
		   	 var fbSession = FB.Facebook.apiClient.get_session();
			 var uid= fbSession.uid;
			 var sessionid = fbSession.session_key;
			 UserManager.alreadyHaveWozzonLogin(emailValue, passwordValue, uid, sessionid, existingAccountHandler);
        }
		
	    /*    
		if(emailValue!='' && checkEmail(emailValue) && passwordValue!=''){
			//$('#login_email').val(emailValue);
			//$('#login_password').val(passwordValue);
			 var fbSession = FB.Facebook.apiClient.get_session();
			 var uid= fbSession.uid;
			 var sessionid = fbSession.session_key;
			 UserManager.alreadyHaveWozzonLogin(emailValue, passwordValue, uid, sessionid, existingAccountHandler);
			
		}else{
			_$id('exisitingAccountError_fb').innerHTML= 'Please provide a correct email and password.';
		}
		*/
	}
	
	function existingAccountHandler(source){
		if(source=='alreadySync'){
			//_$id('exisitingAccountError_fb').innerHTML="OOPS! This account is already sync. If you have any question or comment, please send us your feedback.";
			$('#password_exst_woz').val('');
			$('#email_exst_woz').val(SIN_EMAIL);
			SNG_displayLoginError($('#email_exst_woz'), 'This woZZon account is already associated with another Facebook account');
		}else if(source=='userNotExists'){
			//_$id('exisitingAccountError_fb').innerHTML="Please provide correct email/password.";
			$('#password_exst_woz').val('');
			SNG_passwordOnBlur(_$id('password_exst_woz'));
			$('#email_fb').val($('#email_exst_woz').val())
			SNG_displayLoginError($('#email_exst_woz'), "Email address not recognised, would you like to create a new account?");
		}else if(source=='Invalid'){
			//_$id('exisitingAccountError_fb').innerHTML= "The email address or password you provided does not match our records";
			$('#password_exst_woz').val('');
			SNG_displayLoginError($('#password_exst_woz'), "The password you have entered is incorrect");
		}else if(source=='error'){
			//_$id('exisitingAccountError_fb').innerHTML= "Error.";
			SNG_alert("Error.");
		}else if(source!='error'){
			//hideDivs("tbl_existing_account");
			//showDivs('tbl_sync_success');
			//TODO:show success new popup;
			userFromLink="Linked";
			SNG_loginAjax(1);
			$('#login_email').val(emailValue = $('#email_exst_woz').val());
			$('#login_password').val(passwordValue = $('#password_exst_woz').val());
			
      	}
	}

	//function backWindow(hideWindow,showWindow){
	//	hideDivs(hideWindow);
	//	showDivs(showWindow);
	//}
	
	function reRenderXFBMLTags(){
		FB.XFBML.Host.parseDomTree(); 
	}

	function showSuccessMessage(messageBody){
		showDivs("tbl_confirmation_message");
		_$id("tbl_confirmation_message_content").innerHTML(messageBody);
		
	}

	//Incomplete
	function removeSyncPanel(){
		//setCookie("remove_sync_panel", "true", 1);
		hideDivs('syncAccount');
		UserManager.removeSyncPanel();		
	}
	
	
	//function clearAlreadyWozzonWindow(){
	//	_$id('exisitingAccountError_fb').innerHTML = "";
	//	document.getElementById('existing_account_form_fb').email_exst_woz.value = "";
	//	document.getElementById('existing_account_form_fb').password_exst_woz.value = "";
	//}
	
	//function clearRegistrationWindow(clearAll){
	//	_$id('registerationError_fb').innerHTML = "";
	//	if(clearAll=='true'){
	//		_$id('nickName_fb').value="";
	//		_$id('email_fb').value="";
	//		_$id('postcode_fb').value="";
	//	}
	//}

	/* Shaheer */
	
	function loginForWozzon() {
		var loginEmail = _$id('loginEmail').value;
		var loginPassword = _$id('loginPassword').value;
		var loginRemember = _$id('loginRemember').value;
		UserManager.login(loginEmail, loginPassword, loginRemember, checkLoginForWozzonHandler);
	}
	
	function checkLoginForWozzonHandler(source) {
		if (source == "Invalid") {
			displayErrorMessage("Invalid username or password");
		} else {		
			setCookie("login_source", "whitelabel", 1);
			//_$id('welcomenote').innerHTML = source;		
			_$id('fbSignIn').style.display = 'none';
			checkLoginHandler(source);
			//hideDivs('fbSignIn');
		}
	}
	
	function fbSignIn() {
		_$id('fbSignIn').style.display = '';
		hideDivs('tbl_registration_fb');
	}
	
	
	/* Related to Synchronizing from Web, from Wozzon*/
		function getFacebookID(){
	      FB.Bootstrap.ensureInit(function () {
	      	FB.Connect.requireSession();	      	
	      	FB.Facebook.get_sessionState().waitUntilReady(function() {
	      		syncWithFacebook();
			});
	  	  });
	}
	
	    
      function syncWithFacebook(){
      		var session = FB.Facebook.apiClient.get_session();
			var uid = session.uid;
			var sessionid = session.session_key;
			document.getElementById('fb_user_info_div_permission_window').innerHTML = "<fb:profile-pic uid='" + uid + "' facebook-logo='true' size='thumb' ></fb:profile-pic>" +
									  "<b><fb:name useyou='false' linked='false' uid='"+ uid + "'></fb:name></b>";
									  
			showDivs('tbl_permission_fb');
			_$id('permissionError_fb').innerHTML='';
			showDivs('continueWithSyncDiv');
			showFBPopMainDiv();
			reRenderXFBMLTags();
      }
      
      function continueWithSync(){
		    var session = FB.Facebook.apiClient.get_session();
			var uid = session.uid;
        	UserManager.syncWozzonWithFB(uid, checkWozzonSyncHandler);
      }
      
      function checkWozzonSyncHandler(source){
      	if(source=='Success'){
      		showDivs('tbl_sync_success');
      		hideDivs('tbl_permission_fb');
      		removeSyncPanel();
      	}else if(source=='fbAlreadySync') {
      		_$id('permissionError_fb').innerHTML= 'Facebook account is already sync with some woZZon ID. Please try different Facebook Account';
      		hideDivs('continueWithSyncDiv');
      	}else if(source=='alreadySync') {
      		_$id('permissionError_fb').innerHTML= 'Your woZZon account is already sync with some Facebook Account.';
      		hideDivs('continueWithSyncDiv');
      		removeSyncPanel();
      	}
      }
	/* end */

/**
 *
 * Zoomimage
 * Author: Stefan Petre www.eyecon.ro
 * 
 */
(function($){
	var EYE = window.EYE = function() {
		var _registered = {
			init: []
		};
		return {
			init: function() {
				$.each(_registered.init, function(nr, fn){
					fn.call();
				});
			},
			extend: function(prop) {
				for (var i in prop) {
					if (prop[i] != undefined) {
						this[i] = prop[i];
					}
				}
			},
			register: function(fn, type) {
				if (!_registered[type]) {
					_registered[type] = [];
				}
				_registered[type].push(fn);
			}
		};
	}();
	$(EYE.init);
})(jQuery);
/**
 *
 * Utilities
 * Author: Stefan Petre www.eyecon.ro
 * 
 */
(function($) {
EYE.extend({
	getPosition : function(e, forceIt)
	{
		var x = 0;
		var y = 0;
		var es = e.style;
		var restoreStyles = false;
		if (forceIt && jQuery.curCSS(e,'display') == 'none') {
			var oldVisibility = es.visibility;
			var oldPosition = es.position;
			restoreStyles = true;
			es.visibility = 'hidden';
			es.display = 'block';
			es.position = 'absolute';
		}
		var el = e;
		if (el.getBoundingClientRect) { // IE
			var box = el.getBoundingClientRect();
			x = box.left + Math.max(document.documentElement.scrollLeft, document.body.scrollLeft) - 2;
			y = box.top + Math.max(document.documentElement.scrollTop, document.body.scrollTop) - 2;
		} else {
			x = el.offsetLeft;
			y = el.offsetTop;
			el = el.offsetParent;
			if (e != el) {
				while (el) {
					x += el.offsetLeft;
					y += el.offsetTop;
					el = el.offsetParent;
				}
			}
			if (jQuery.browser.safari && jQuery.curCSS(e, 'position') == 'absolute' ) {
				x -= document.body.offsetLeft;
				y -= document.body.offsetTop;
			}
			el = e.parentNode;
			while (el && el.tagName.toUpperCase() != 'BODY' && el.tagName.toUpperCase() != 'HTML') 
			{
				if (jQuery.curCSS(el, 'display') != 'inline') {
					x -= el.scrollLeft;
					y -= el.scrollTop;
				}
				el = el.parentNode;
			}
		}
		if (restoreStyles == true) {
			es.display = 'none';
			es.position = oldPosition;
			es.visibility = oldVisibility;
		}
		return {x:x, y:y};
	},
	getSize : function(e)
	{
		var w = parseInt(jQuery.curCSS(e,'width'), 10);
		var h = parseInt(jQuery.curCSS(e,'height'), 10);
		var wb = 0;
		var hb = 0;
		if (jQuery.curCSS(e, 'display') != 'none') {
			wb = e.offsetWidth;
			hb = e.offsetHeight;
		} else {
			var es = e.style;
			var oldVisibility = es.visibility;
			var oldPosition = es.position;
			es.visibility = 'hidden';
			es.display = 'block';
			es.position = 'absolute';
			wb = e.offsetWidth;
			hb = e.offsetHeight;
			es.display = 'none';
			es.position = oldPosition;
			es.visibility = oldVisibility;
		}
		return {w:w, h:h, wb:wb, hb:hb};
	},
	getClient : function(e)
	{
		var h, w;
		if (e) {
			w = e.clientWidth;
			h = e.clientHeight;
		} else {
			var de = document.documentElement;
			w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
			h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
		}
		return {w:w,h:h};
	},
	getScroll : function (e)
	{
		var t=0, l=0, w=0, h=0, iw=0, ih=0;
		if (e && e.nodeName.toLowerCase() != 'body') {
			t = e.scrollTop;
			l = e.scrollLeft;
			w = e.scrollWidth;
			h = e.scrollHeight;
		} else  {
			if (document.documentElement) {
				t = document.documentElement.scrollTop;
				l = document.documentElement.scrollLeft;
				w = document.documentElement.scrollWidth;
				h = document.documentElement.scrollHeight;
			} else if (document.body) {
				t = document.body.scrollTop;
				l = document.body.scrollLeft;
				w = document.body.scrollWidth;
				h = document.body.scrollHeight;
			}
			if (typeof pageYOffset != 'undefined') {
				t = pageYOffset;
				l = pageXOffset;
			}
			iw = self.innerWidth||document.documentElement.clientWidth||document.body.clientWidth||0;
			ih = self.innerHeight||document.documentElement.clientHeight||document.body.clientHeight||0;
		}
		return { t: t, l: l, w: w, h: h, iw: iw, ih: ih };
	},
	getMargins : function(e, toInteger)
	{
		var t = jQuery.curCSS(e,'marginTop') || '';
		var r = jQuery.curCSS(e,'marginRight') || '';
		var b = jQuery.curCSS(e,'marginBottom') || '';
		var l = jQuery.curCSS(e,'marginLeft') || '';
		if (toInteger)
			return {
				t: parseInt(t, 10)||0,
				r: parseInt(r, 10)||0,
				b: parseInt(b, 10)||0,
				l: parseInt(l, 10)
			};
		else
			return {t: t, r: r,	b: b, l: l};
	},
	getPadding : function(e, toInteger)
	{
		var t = jQuery.curCSS(e,'paddingTop') || '';
		var r = jQuery.curCSS(e,'paddingRight') || '';
		var b = jQuery.curCSS(e,'paddingBottom') || '';
		var l = jQuery.curCSS(e,'paddingLeft') || '';
		if (toInteger)
			return {
				t: parseInt(t, 10)||0,
				r: parseInt(r, 10)||0,
				b: parseInt(b, 10)||0,
				l: parseInt(l, 10)
			};
		else
			return {t: t, r: r,	b: b, l: l};
	},
	getBorder : function(e, toInteger)
	{
		var t = jQuery.curCSS(e,'borderTopWidth') || '';
		var r = jQuery.curCSS(e,'borderRightWidth') || '';
		var b = jQuery.curCSS(e,'borderBottomWidth') || '';
		var l = jQuery.curCSS(e,'borderLeftWidth') || '';
		if (toInteger)
			return {
				t: parseInt(t, 10)||0,
				r: parseInt(r, 10)||0,
				b: parseInt(b, 10)||0,
				l: parseInt(l, 10)||0
			};
		else
			return {t: t, r: r,	b: b, l: l};
	},
	traverseDOM : function(nodeEl, func)
	{
		func(nodeEl);
		nodeEl = nodeEl.firstChild;
		while(nodeEl){
			EYE.traverseDOM(nodeEl, func);
			nodeEl = nodeEl.nextSibling;
		}
	},
	getInnerWidth :  function(el, scroll) {
		var offsetW = el.offsetWidth;
		return scroll ? Math.max(el.scrollWidth,offsetW) - offsetW + el.clientWidth:el.clientWidth;
	},
	getInnerHeight : function(el, scroll) {
		var offsetH = el.offsetHeight;
		return scroll ? Math.max(el.scrollHeight,offsetH) - offsetH + el.clientHeight:el.clientHeight;
	},
	getExtraWidth : function(el) {
		if($.boxModel)
			return (parseInt($.curCSS(el, 'paddingLeft'))||0)
				+ (parseInt($.curCSS(el, 'paddingRight'))||0)
				+ (parseInt($.curCSS(el, 'borderLeftWidth'))||0)
				+ (parseInt($.curCSS(el, 'borderRightWidth'))||0);
		return 0;
	},
	getExtraHeight : function(el) {
		if($.boxModel)
			return (parseInt($.curCSS(el, 'paddingTop'))||0)
				+ (parseInt($.curCSS(el, 'paddingBottom'))||0)
				+ (parseInt($.curCSS(el, 'borderTopWidth'))||0)
				+ (parseInt($.curCSS(el, 'borderBottomWidth'))||0);
		return 0;
	},
	isChildOf: function(parentEl, el, container) {
		if (parentEl == el) {
			return true;
		}
		if (!el || !el.nodeType || el.nodeType != 1) {
			return false;
		}
		if (parentEl.contains && !$.browser.safari) {
			return parentEl.contains(el);
		}
		if ( parentEl.compareDocumentPosition ) {
			return !!(parentEl.compareDocumentPosition(el) & 16);
		}
		var prEl = el.parentNode;
		while(prEl && prEl != container) {
			if (prEl == parentEl)
				return true;
			prEl = prEl.parentNode;
		}
		return false;
	},
	centerEl : function(el, axis)
	{
		var clientScroll = EYE.getScroll();
		var size = EYE.getSize(el);
		if (!axis || axis == 'vertically')
			$(el).css(
				{
					top: clientScroll.t + ((Math.min(clientScroll.h,clientScroll.ih) - size.hb)/2) + 'px'
				}
			);
		if (!axis || axis == 'horizontally')
			$(el).css(
				{
					left: clientScroll.l + ((Math.min(clientScroll.w,clientScroll.iw) - size.wb)/2) + 'px'
				}
			);
	}
});
if (!$.easing.easeout) {
	$.easing.easeout = function(p, n, firstNum, delta, duration) {
		return -delta * ((n=n/duration-1)*n*n*n - 1) + firstNum;
	};
}
	
})(jQuery);
/**
 *
 * Date picker
 * Author: Stefan Petre www.eyecon.ro
 * 
 * Dual licensed under the MIT and GPL licenses
 * 
 */
(function ($) {
	var DatePicker = function () {
		var	ids = {},
			views = {
				years: 'datepickerViewYears',
				moths: 'datepickerViewMonths',
				days: 'datepickerViewDays'
			},
			tpl = {
				wrapper: '<div class="datepicker"><div class="datepickerBorderT" /><div class="datepickerBorderB" /><div class="datepickerBorderL" /><div class="datepickerBorderR" /><div class="datepickerBorderTL" /><div class="datepickerBorderTR" /><div class="datepickerBorderBL" /><div class="datepickerBorderBR" /><div class="datepickerContainer"><table cellspacing="0" cellpadding="0"><tbody><tr></tr></tbody></table></div><div class="calanderHelp"><p><strong>*</strong> Select the first and last date of the date range<br /></p><div class="SNG_calendarOKBtn"><p><a href="#">OK</a></p></div></div></div>',
				head: [
					'<td>',
					'<table cellspacing="0" cellpadding="0">',
						'<thead>',
							'<tr>',
								'<th class="datepickerGoPrev"><a href="#" style="color:#B0B5B9;"><span><%=prev%></span></a></th>',
								'<th colspan="5" class="datepickerMonth"><span></span></th>',
								'<th class="datepickerGoNext"><a href="#" style="color:#B0B5B9;"><span><%=next%></span></a></th>',
							'</tr>',
							'<tr class="datepickerDoW">',							
								'<th><span><%=day1%></span></th>',
								'<th><span><%=day2%></span></th>',
								'<th><span><%=day3%></span></th>',
								'<th><span><%=day4%></span></th>',
								'<th><span><%=day5%></span></th>',
								'<th><span><%=day6%></span></th>',
								'<th><span><%=day7%></span></th>',
							'</tr>',
						'</thead>',
					'</table></td>'
				],
				space : '<td class="datepickerSpace"><div></div></td>',
				days: [
					'<tbody class="datepickerDays" style="background:#FFFFFF; border:5px solid #FFFFFF;">',
						'<tr>',							
							'<td class="<%=weeks[0].days[0].classname%>"><a href="#"><span><%=weeks[0].days[0].text%></span></a></td>',
							'<td class="<%=weeks[0].days[1].classname%>"><a href="#"><span><%=weeks[0].days[1].text%></span></a></td>',
							'<td class="<%=weeks[0].days[2].classname%>"><a href="#"><span><%=weeks[0].days[2].text%></span></a></td>',
							'<td class="<%=weeks[0].days[3].classname%>"><a href="#"><span><%=weeks[0].days[3].text%></span></a></td>',
							'<td class="<%=weeks[0].days[4].classname%>"><a href="#"><span><%=weeks[0].days[4].text%></span></a></td>',
							'<td class="<%=weeks[0].days[5].classname%>"><a href="#"><span><%=weeks[0].days[5].text%></span></a></td>',
							'<td class="<%=weeks[0].days[6].classname%>"><a href="#"><span><%=weeks[0].days[6].text%></span></a></td>',
						'</tr>',
						'<tr>',
							
							'<td class="<%=weeks[1].days[0].classname%>"><a href="#"><span><%=weeks[1].days[0].text%></span></a></td>',
							'<td class="<%=weeks[1].days[1].classname%>"><a href="#"><span><%=weeks[1].days[1].text%></span></a></td>',
							'<td class="<%=weeks[1].days[2].classname%>"><a href="#"><span><%=weeks[1].days[2].text%></span></a></td>',
							'<td class="<%=weeks[1].days[3].classname%>"><a href="#"><span><%=weeks[1].days[3].text%></span></a></td>',
							'<td class="<%=weeks[1].days[4].classname%>"><a href="#"><span><%=weeks[1].days[4].text%></span></a></td>',
							'<td class="<%=weeks[1].days[5].classname%>"><a href="#"><span><%=weeks[1].days[5].text%></span></a></td>',
							'<td class="<%=weeks[1].days[6].classname%>"><a href="#"><span><%=weeks[1].days[6].text%></span></a></td>',
						'</tr>',
						'<tr>',
							
							'<td class="<%=weeks[2].days[0].classname%>"><a href="#"><span><%=weeks[2].days[0].text%></span></a></td>',
							'<td class="<%=weeks[2].days[1].classname%>"><a href="#"><span><%=weeks[2].days[1].text%></span></a></td>',
							'<td class="<%=weeks[2].days[2].classname%>"><a href="#"><span><%=weeks[2].days[2].text%></span></a></td>',
							'<td class="<%=weeks[2].days[3].classname%>"><a href="#"><span><%=weeks[2].days[3].text%></span></a></td>',
							'<td class="<%=weeks[2].days[4].classname%>"><a href="#"><span><%=weeks[2].days[4].text%></span></a></td>',
							'<td class="<%=weeks[2].days[5].classname%>"><a href="#"><span><%=weeks[2].days[5].text%></span></a></td>',
							'<td class="<%=weeks[2].days[6].classname%>"><a href="#"><span><%=weeks[2].days[6].text%></span></a></td>',
						'</tr>',
						'<tr>',
							
							'<td class="<%=weeks[3].days[0].classname%>"><a href="#"><span><%=weeks[3].days[0].text%></span></a></td>',
							'<td class="<%=weeks[3].days[1].classname%>"><a href="#"><span><%=weeks[3].days[1].text%></span></a></td>',
							'<td class="<%=weeks[3].days[2].classname%>"><a href="#"><span><%=weeks[3].days[2].text%></span></a></td>',
							'<td class="<%=weeks[3].days[3].classname%>"><a href="#"><span><%=weeks[3].days[3].text%></span></a></td>',
							'<td class="<%=weeks[3].days[4].classname%>"><a href="#"><span><%=weeks[3].days[4].text%></span></a></td>',
							'<td class="<%=weeks[3].days[5].classname%>"><a href="#"><span><%=weeks[3].days[5].text%></span></a></td>',
							'<td class="<%=weeks[3].days[6].classname%>"><a href="#"><span><%=weeks[3].days[6].text%></span></a></td>',
						'</tr>',
						'<tr>',
							
							'<td class="<%=weeks[4].days[0].classname%>"><a href="#"><span><%=weeks[4].days[0].text%></span></a></td>',
							'<td class="<%=weeks[4].days[1].classname%>"><a href="#"><span><%=weeks[4].days[1].text%></span></a></td>',
							'<td class="<%=weeks[4].days[2].classname%>"><a href="#"><span><%=weeks[4].days[2].text%></span></a></td>',
							'<td class="<%=weeks[4].days[3].classname%>"><a href="#"><span><%=weeks[4].days[3].text%></span></a></td>',
							'<td class="<%=weeks[4].days[4].classname%>"><a href="#"><span><%=weeks[4].days[4].text%></span></a></td>',
							'<td class="<%=weeks[4].days[5].classname%>"><a href="#"><span><%=weeks[4].days[5].text%></span></a></td>',
							'<td class="<%=weeks[4].days[6].classname%>"><a href="#"><span><%=weeks[4].days[6].text%></span></a></td>',
						'</tr>',
						'<tr>',
							
							'<td class="<%=weeks[5].days[0].classname%>"><a href="#"><span><%=weeks[5].days[0].text%></span></a></td>',
							'<td class="<%=weeks[5].days[1].classname%>"><a href="#"><span><%=weeks[5].days[1].text%></span></a></td>',
							'<td class="<%=weeks[5].days[2].classname%>"><a href="#"><span><%=weeks[5].days[2].text%></span></a></td>',
							'<td class="<%=weeks[5].days[3].classname%>"><a href="#"><span><%=weeks[5].days[3].text%></span></a></td>',
							'<td class="<%=weeks[5].days[4].classname%>"><a href="#"><span><%=weeks[5].days[4].text%></span></a></td>',
							'<td class="<%=weeks[5].days[5].classname%>"><a href="#"><span><%=weeks[5].days[5].text%></span></a></td>',
							'<td class="<%=weeks[5].days[6].classname%>"><a href="#"><span><%=weeks[5].days[6].text%></span></a></td>',
						'</tr>',
					'</tbody>'
				],
				months: [
					'<tbody class="<%=className%>">',
						'<tr>',
							'<td colspan="2"><a href="#"><span><%=data[0]%></span></a></td>',
							'<td colspan="2"><a href="#"><span><%=data[1]%></span></a></td>',
							'<td colspan="2"><a href="#"><span><%=data[2]%></span></a></td>',
							'<td colspan="2"><a href="#"><span><%=data[3]%></span></a></td>',
						'</tr>',
						'<tr>',
							'<td colspan="2"><a href="#"><span><%=data[4]%></span></a></td>',
							'<td colspan="2"><a href="#"><span><%=data[5]%></span></a></td>',
							'<td colspan="2"><a href="#"><span><%=data[6]%></span></a></td>',
							'<td colspan="2"><a href="#"><span><%=data[7]%></span></a></td>',
						'</tr>',
						'<tr>',
							'<td colspan="2"><a href="#"><span><%=data[8]%></span></a></td>',
							'<td colspan="2"><a href="#"><span><%=data[9]%></span></a></td>',
							'<td colspan="2"><a href="#"><span><%=data[10]%></span></a></td>',
							'<td colspan="2"><a href="#"><span><%=data[11]%></span></a></td>',
						'</tr>',
					'</tbody>'
				]
			},
			defaults = {
				flat: true,
				starts: 0,
				prev: '&#9664;',
				next: '&#9654;',
				lastSel: false,
				mode: 'range',
				view: 'days',
				calendars: 2,
				format: 'd/m/Y',
				position: 'bottom',
				eventName: 'click',
				onRender: function(){return {};},
				onChange: function(){return true;},
				onShow: function(){return true;},
				onBeforeShow: function(){return true;},
				onHide: function(){return true;},
				locale: {
					days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
					daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
					daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
					months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
					monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]					
				}
			},
			fill = function(el) {
				var options = $(el).data('datepicker');
				var cal = $(el);
				var currentCal = Math.floor(options.calendars/2), date, data, dow, month, cnt = 0, week, days, indic, indic2, html, tblCal;
				cal.find('td>table tbody').remove();
				for (var i = 0; i < options.calendars; i++) {
					date = new Date(options.current);
					date.addMonths(-currentCal + i);
					tblCal = cal.find('table').eq(i+1);
					switch (tblCal[0].className) {
						case 'datepickerViewDays':
							dow = formatDate(date, 'B, Y');
							break;
						case 'datepickerViewMonths':
							dow = date.getFullYear();
							break;
						case 'datepickerViewYears':
							dow = (date.getFullYear()-6) + ' - ' + (date.getFullYear()+5);
							break;
					} 
					tblCal.find('thead tr:first th:eq(1) span').text(dow);
					dow = date.getFullYear()-6;
					data = {
						data: [],
						className: 'datepickerYears'
					}
					for ( var j = 0; j < 12; j++) {
						data.data.push(dow + j);
					}
					html = tmpl(tpl.months.join(''), data);
					date.setDate(1);
					data = {weeks:[], test: 10};
					month = date.getMonth();
					var dow = (date.getDay() - options.starts) % 7;
					date.addDays(-(dow + (dow < 0 ? 7 : 0)));
					week = -1;
					cnt = 0;
					while (cnt < 42) {
						indic = parseInt(cnt/7,10);
						indic2 = cnt%7;
						if (!data.weeks[indic]) {
							week = date.getWeekNumber();
							data.weeks[indic] = {
								week: week,
								days: []
							};
						}
						data.weeks[indic].days[indic2] = {
							text: date.getDate(),
							classname: []
						};
						if (month != date.getMonth()) {							
							data.weeks[indic].days[indic2].classname.push('datepickerDisabled2');
							
						}						
						var fromUser = options.onRender(date);
						var val = date.valueOf();
						if (fromUser.selected || options.date == val || $.inArray(val, options.date) > -1 || (options.mode == 'range' && val >= options.date[0] && val <= options.date[1])) {
							if (month  == date.getMonth()) {		
								data.weeks[indic].days[indic2].classname.push('datepickerSelected');
							}
						}
						if (fromUser.disabled) {
							data.weeks[indic].days[indic2].classname.push('datepickerDisabled');
						}
						if (fromUser.className) {
							data.weeks[indic].days[indic2].classname.push(fromUser.className);
						}
						data.weeks[indic].days[indic2].classname = data.weeks[indic].days[indic2].classname.join(' ');
						cnt++;
						date.addDays(1);
					}
					html = tmpl(tpl.days.join(''), data) + html;
					data = {
						data: options.locale.monthsShort,
						className: 'datepickerMonths'
					};
					html = tmpl(tpl.months.join(''), data) + html;
					tblCal.append(html);
				}
			},
			parseDate = function (date, format) {
				if (date.constructor == Date) {
					return new Date(date);
				}
				var parts = date.split(/\W+/);
				var against = format.split(/\W+/), d, m, y, h, min, now = new Date();
				for (var i = 0; i < parts.length; i++) {
					switch (against[i]) {
						case 'd':
						case 'e':
							d = parseInt(parts[i],10);
							break;
						case 'm':
							m = parseInt(parts[i], 10)-1;
							break;
						case 'Y':
						case 'y':
							y = parseInt(parts[i], 10);
							y += y > 100 ? 0 : (y < 29 ? 2000 : 1900);
							break;
						case 'H':
						case 'I':
						case 'k':
						case 'l':
							h = parseInt(parts[i], 10);
							break;
						case 'P':
						case 'p':
							if (/pm/i.test(parts[i]) && h < 12) {
								h += 12;
							} else if (/am/i.test(parts[i]) && h >= 12) {
								h -= 12;
							}
							break;
						case 'M':
							min = parseInt(parts[i], 10);
							break;
					}
				}
				return new Date(
					y === undefined ? now.getFullYear() : y,
					m === undefined ? now.getMonth() : m,
					d === undefined ? now.getDate() : d,
					h === undefined ? now.getHours() : h,
					min === undefined ? now.getMinutes() : min,
					0
				);
			},
			formatDate = function(date, format) {
				var m = date.getMonth();
				var d = date.getDate();
				var y = date.getFullYear();
				var wn = date.getWeekNumber();
				var w = date.getDay();
				var s = {};
				var hr = date.getHours();
				var pm = (hr >= 12);
				var ir = (pm) ? (hr - 12) : hr;
				var dy = date.getDayOfYear();
				if (ir == 0) {
					ir = 12;
				}
				var min = date.getMinutes();
				var sec = date.getSeconds();
				var parts = format.split(''), part;
				for ( var i = 0; i < parts.length; i++ ) {
					part = parts[i];
					switch (parts[i]) {
						case 'a':
							part = date.getDayName();
							break;
						case 'A':
							part = date.getDayName(true);
							break;
						case 'b':
							part = date.getMonthName();
							break;
						case 'B':
							part = date.getMonthName(true);
							break;
						case 'C':
							part = 1 + Math.floor(y / 100);
							break;
						case 'd':
							part = (d < 10) ? ("0" + d) : d;
							break;
						case 'e':
							part = d;
							break;
						case 'H':
							part = (hr < 10) ? ("0" + hr) : hr;
							break;
						case 'I':
							part = (ir < 10) ? ("0" + ir) : ir;
							break;
						case 'j':
							part = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy;
							break;
						case 'k':
							part = hr;
							break;
						case 'l':
							part = ir;
							break;
						case 'm':
							part = (m < 9) ? ("0" + (1+m)) : (1+m);
							break;
						case 'M':
							part = (min < 10) ? ("0" + min) : min;
							break;
						case 'p':
						case 'P':
							part = pm ? "PM" : "AM";
							break;
						case 's':
							part = Math.floor(date.getTime() / 1000);
							break;
						case 'S':
							part = (sec < 10) ? ("0" + sec) : sec;
							break;
						case 'u':
							part = w + 1;
							break;
						case 'w':
							part = w;
							break;
						case 'y':
							part = ('' + y).substr(2, 2);
							break;
						case 'Y':
							part = y;
							break;
					}
					parts[i] = part;
				}
				return parts.join('');
			},
			extendDate = function(options) {
				if (Date.prototype.tempDate) {
					return;
				}
				Date.prototype.tempDate = null;
				Date.prototype.months = options.months;
				Date.prototype.monthsShort = options.monthsShort;
				Date.prototype.days = options.days;
				Date.prototype.daysShort = options.daysShort;
				Date.prototype.getMonthName = function(fullName) {
					return this[fullName ? 'months' : 'monthsShort'][this.getMonth()];
				};
				Date.prototype.getDayName = function(fullName) {
					return this[fullName ? 'days' : 'daysShort'][this.getDay()];
				};
				Date.prototype.addDays = function (n) {
					this.setDate(this.getDate() + n);
					this.tempDate = this.getDate();
				};
				Date.prototype.addMonths = function (n) {
					if (this.tempDate == null) {
						this.tempDate = this.getDate();
					}
					this.setDate(1);
					this.setMonth(this.getMonth() + n);
					this.setDate(Math.min(this.tempDate, this.getMaxDays()));
				};
				Date.prototype.addYears = function (n) {
					if (this.tempDate == null) {
						this.tempDate = this.getDate();
					}
					this.setDate(1);
					this.setFullYear(this.getFullYear() + n);
					this.setDate(Math.min(this.tempDate, this.getMaxDays()));
				};
				Date.prototype.getMaxDays = function() {
					var tmpDate = new Date(Date.parse(this)),
						d = 28, m;
					m = tmpDate.getMonth();
					d = 28;
					while (tmpDate.getMonth() == m) {
						d ++;
						tmpDate.setDate(d);
					}
					return d - 1;
				};
				Date.prototype.getFirstDay = function() {
					var tmpDate = new Date(Date.parse(this));
					tmpDate.setDate(1);
					return tmpDate.getDay();
				};
				Date.prototype.getWeekNumber = function() {
					var tempDate = new Date(this);
					tempDate.setDate(tempDate.getDate() - (tempDate.getDay() + 6) % 7 + 3);
					var dms = tempDate.valueOf();
					tempDate.setMonth(0);
					tempDate.setDate(4);
					return Math.round((dms - tempDate.valueOf()) / (604800000)) + 1;
				};
				Date.prototype.getDayOfYear = function() {
					var now = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
					var then = new Date(this.getFullYear(), 0, 0, 0, 0, 0);
					var time = now - then;
					return Math.floor(time / 24*60*60*1000);
				};
			},
			layout = function (el) {
				var options = $(el).data('datepicker');
				var cal = $('#' + options.id);
				if (!options.extraHeight) {
					var divs = $(el).find('div');					
					options.extraHeight = divs.get(0).offsetHeight + divs.get(1).offsetHeight + divs.get(10).offsetHeight;
					options.extraWidth = divs.get(2).offsetWidth + divs.get(3).offsetWidth 
				}
				var tbl = cal.find('table:first').get(0);
				var width = tbl.offsetWidth;
				var height = tbl.offsetHeight;
				cal.css({
					width: width + options.extraWidth + 'px',
					height: height + options.extraHeight + 'px'
				}).find('div.datepickerContainer').css({
					width: width + 'px',
					height: height + 'px'
				});
			},
			click = function(ev) {
				if ($(ev.target).is('span')) {
					ev.target = ev.target.parentNode;
				}
				var el = $(ev.target);
				if (el.is('a')) {
					ev.target.blur();
					if (el.hasClass('datepickerDisabled')) {
						return false;
					}
					var options = $(this).data('datepicker');
					var parentEl = el.parent();
					var tblEl = parentEl.parent().parent().parent();
					var tblIndex = $('table', this).index(tblEl.get(0)) - 1;
					var tmp = new Date(options.current);
					var changed = false;
					var fillIt = false;
					if (parentEl.is('th')) {
						if (parentEl.hasClass('datepickerWeek') && options.mode == 'range' && !parentEl.next().hasClass('datepickerDisabled')) {
							var val = parseInt(parentEl.next().text(), 10);
							tmp.addMonths(tblIndex - Math.floor(options.calendars/2));
							if (parentEl.next().hasClass('datepickerNotInMonth')) {
								tmp.addMonths(val > 15 ? -1 : 1);
							}
							tmp.setDate(val);
							options.date[0] = (tmp.setHours(0,0,0,0)).valueOf();
							tmp.setHours(23,59,59,0);
							tmp.addDays(6);
							options.date[1] = tmp.valueOf();
							fillIt = true;
							changed = true;
							options.lastSel = false;
						} else if (parentEl.hasClass('datepickerMonth')) {
							tmp.addMonths(tblIndex - Math.floor(options.calendars/2));
							switch (tblEl.get(0).className) {
								case 'datepickerViewDays':
									tblEl.get(0).className = 'datepickerViewMonths';
									el.find('span').text(tmp.getFullYear());
									break;
								case 'datepickerViewMonths':
									tblEl.get(0).className = 'datepickerViewYears';
									el.find('span').text((tmp.getFullYear()-6) + ' - ' + (tmp.getFullYear()+5));
									break;
								case 'datepickerViewYears':
									tblEl.get(0).className = 'datepickerViewDays';
									el.find('span').text(formatDate(tmp, 'B, Y'));
									break;
							}
						} else if (parentEl.parent().parent().is('thead')) {
							switch (tblEl.get(0).className) {
								case 'datepickerViewDays':
									options.current.addMonths(parentEl.hasClass('datepickerGoPrev') ? -1 : 1);
									break;
								case 'datepickerViewMonths':
									options.current.addYears(parentEl.hasClass('datepickerGoPrev') ? -1 : 1);
									break;
								case 'datepickerViewYears':
									options.current.addYears(parentEl.hasClass('datepickerGoPrev') ? -12 : 12);
									break;
							}
							fillIt = true;
						}
					} else if (parentEl.is('td') && !parentEl.hasClass('datepickerDisabled')) {
						switch (tblEl.get(0).className) {
							case 'datepickerViewMonths':
								options.current.setMonth(tblEl.find('tbody.datepickerMonths td').index(parentEl));
								options.current.setFullYear(parseInt(tblEl.find('thead th.datepickerMonth span').text(), 10));
								options.current.addMonths(Math.floor(options.calendars/2) - tblIndex);
								tblEl.get(0).className = 'datepickerViewDays';
								break;
							case 'datepickerViewYears':
								options.current.setFullYear(parseInt(el.text(), 10));
								tblEl.get(0).className = 'datepickerViewMonths';
								break;
							default:
								var val = parseInt(el.text(), 10);
								tmp.addMonths(tblIndex - Math.floor(options.calendars/2));
								if (parentEl.hasClass('datepickerNotInMonth')) {
									tmp.addMonths(val > 15 ? -1 : 1);
								}
								tmp.setDate(val);
								switch (options.mode) {
									case 'multiple':
										val = (tmp.setHours(0,0,0,0)).valueOf();
										if ($.inArray(val, options.date) > -1) {
											$.each(options.date, function(nr, dat){
												if (dat == val) {
													options.date.splice(nr,1);
													return false;
												}
											});
										} else {
											options.date.push(val);
										}
										break;
									case 'range':
										if (!options.lastSel) {
											options.date[0] = (tmp.setHours(0,0,0,0)).valueOf();
										}
										val = (tmp.setHours(23,59,59,0)).valueOf();
										if (val < options.date[0]) {
											options.date[1] = options.date[0] + 86399000;
											options.date[0] = val - 86399000;
										} else {
											options.date[1] = val;
										}
										options.lastSel = !options.lastSel;
										break;
									default:
										options.date = tmp.valueOf();
										break;
								}
								break;
						}
						fillIt = true;
						changed = true;
					}
					if (fillIt) {
						fill(this);
					}
					if (changed) {
						options.onChange.apply(this, prepareDate(options));
					}
				}
				return false;
			},
			clickOK = function() {
				 if(isOpen) { 
		 			SNG_showChooseDates();
		 	    	 SNG_hideWhenMenu();
		 	    }
			},
			prepareDate = function (options) {
				var tmp;
				if (options.mode == 'single') {
					tmp = new Date(options.date);
					return [formatDate(tmp, options.format), tmp, options.el];
				} else {
					tmp = [[],[], options.el];
					$.each(options.date, function(nr, val){
						var date = new Date(val);
						tmp[0].push(formatDate(date, options.format));
						tmp[1].push(date);
					});					
					return tmp;
				}
			},
			getViewport = function () {
				var m = document.compatMode == 'CSS1Compat';
				return {
					l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
					t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
					w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
					h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
				};
			},
			isChildOf = function(parentEl, el, container) {
				if (parentEl == el) {
					return true;
				}
				if (parentEl.contains) {
					return parentEl.contains(el);
				}
				if ( parentEl.compareDocumentPosition ) {
					return !!(parentEl.compareDocumentPosition(el) & 16);
				}
				var prEl = el.parentNode;
				while(prEl && prEl != container) {
					if (prEl == parentEl)
						return true;
					prEl = prEl.parentNode;
				}
				return false;
			},
			show = function (ev) {
				var cal = $('#' + $(this).data('datepickerId'));
				if (!cal.is(':visible')) {
					var calEl = cal.get(0);
					fill(calEl);
					var options = cal.data('datepicker');
					options.onBeforeShow.apply(this, [cal.get(0)]);
					var pos = $(this).offset();
					var viewPort = getViewport();
					var top = pos.top;
					var left = pos.left;
					var oldDisplay = $.curCSS(calEl, 'display');
					cal.css({
						visibility: 'hidden',
						display: 'block'
					});
					layout(calEl);
					switch (options.position){
						case 'top':
							top -= calEl.offsetHeight;
							break;
						case 'left':
							left -= calEl.offsetWidth;
							break;
						case 'right':
							left += this.offsetWidth;
							break;
						case 'bottom':
							top += this.offsetHeight;
							break;
					}
					if (top + calEl.offsetHeight > viewPort.t + viewPort.h) {
						top = pos.top  - calEl.offsetHeight;
					}
					if (top < viewPort.t) {
						top = pos.top + this.offsetHeight + calEl.offsetHeight;
					}
					if (left + calEl.offsetWidth > viewPort.l + viewPort.w) {
						left = pos.left - calEl.offsetWidth;
					}
					if (left < viewPort.l) {
						left = pos.left + this.offsetWidth
					}
					cal.css({
						visibility: 'visible',
						display: 'block',
						top: top + 'px',
						left: left + 'px'
					});
					if (options.onShow.apply(this, [cal.get(0)]) != false) {
						cal.show();
					}
					$(document).bind('mousedown', {cal: cal, trigger: this}, hide);
				}
				return false;
			},
			hide = function (ev) {
				if (ev.target != ev.data.trigger && !isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) {
					if (ev.data.cal.data('datepicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) {
						ev.data.cal.hide();
					}
					$(document).unbind('mousedown', hide);
				}
			};
		return {
			init: function(options){
				options = $.extend({}, defaults, options||{});
				extendDate(options.locale);
				options.calendars = Math.max(1, parseInt(options.calendars,10)||1);
				options.mode = /single|multiple|range/.test(options.mode) ? options.mode : 'single';

				return this.each(function(){
					if (!$(this).data('datepicker')) {
						options.el = this;
						if (options.date.constructor == String) {
							options.date = parseDate(options.date, options.format);
							options.date.setHours(0,0,0,0);
						}
						if (options.mode != 'single') {
							if (options.date.constructor != Array) {
								options.date = [options.date.valueOf()];
								if (options.mode == 'range') {
									options.date.push(((new Date(options.date[0])).setHours(23,59,59,0)).valueOf());
								}
							} else {
								for (var i = 0; i < options.date.length; i++) {
									options.date[i] = (parseDate(options.date[i], options.format).setHours(0,0,0,0)).valueOf();
								}
								if (options.mode == 'range') {
									options.date[1] = ((new Date(options.date[1])).setHours(23,59,59,0)).valueOf();
								}
							}
						} else {
							options.date = options.date.valueOf();
						}
						if (!options.current) {
							options.current = new Date();
						} else {
							options.current = parseDate(options.current, options.format);
						} 
						options.current.setDate(1);
						options.current.setHours(0,0,0,0);
						var id = 'datepicker_' + parseInt(Math.random() * 1000), cnt;
						options.id = id;
						$(this).data('datepickerId', options.id);
						var cal = $(tpl.wrapper).attr('id', id).bind('click', click).data('datepicker', options);
						if (options.className) {
							cal.addClass(options.className);
						}
						var html = '';
						for (var i = 0; i < options.calendars; i++) {
							cnt = options.starts;
							if (i > 0) {
								html += tpl.space;
							}
							html += tmpl(tpl.head.join(''), {
									/*week: options.locale.weekMin,*/
									prev: options.prev,
									next: options.next,
									day1: options.locale.daysMin[(cnt++)%7],
									day2: options.locale.daysMin[(cnt++)%7],
									day3: options.locale.daysMin[(cnt++)%7],
									day4: options.locale.daysMin[(cnt++)%7],
									day5: options.locale.daysMin[(cnt++)%7],
									day6: options.locale.daysMin[(cnt++)%7],
									day7: options.locale.daysMin[(cnt++)%7]
								});
						}
						cal
							.find('tr:first').append(html)
								.find('table').addClass(views[options.view]);
						fill(cal.get(0));
						if (options.flat) {
							cal.appendTo(this).show().css('position', 'relative');
							layout(cal.get(0));
						} else {
							cal.appendTo(document.body);
							cal.appendTo(inner);
							$(this).bind(options.eventName, show);
						}
					}
					$('.SNG_calendarOKBtn').bind('click', clickOK);
				});
				 
			},
			showPicker: function() {
				return this.each( function () {
					if ($(this).data('datepickerId')) {
						show.apply(this);
					}
				});
			},
			hidePicker: function() {
				return this.each( function () {
					if ($(this).data('datepickerId')) {
						$('#' + $(this).data('datepickerId')).hide();
					}
				});
			},
			setDate: function(date, shiftTo){
				return this.each(function(){
					if ($(this).data('datepickerId')) {
						var cal = $('#' + $(this).data('datepickerId'));
						var options = cal.data('datepicker');
						options.date = date;
						if (options.date.constructor == String) {
							options.date = parseDate(options.date, options.format);
							options.date.setHours(0,0,0,0);
						}
						if (options.mode != 'single') {
							if (options.date.constructor != Array) {
								options.date = [options.date.valueOf()];
								if (options.mode == 'range') {
									options.date.push(((new Date(options.date[0])).setHours(23,59,59,0)).valueOf());
								}
							} else {
								for (var i = 0; i < options.date.length; i++) {
									options.date[i] = (parseDate(options.date[i], options.format).setHours(0,0,0,0)).valueOf();
								}
								if (options.mode == 'range') {
									options.date[1] = ((new Date(options.date[1])).setHours(23,59,59,0)).valueOf();
								}
							}
						} else {
							options.date = options.date.valueOf();
						}
						if (shiftTo) {
							options.current = new Date (options.mode != 'single' ? options.date[0] : options.date);
						}
						fill(cal.get(0));
					}
				});
			},
			getDate: function(formated) {
				if (this.size() > 0) {
					return prepareDate($('#' + $(this).data('datepickerId')).data('datepicker'))[formated ? 0 : 1];
				}
			},
			clear: function(){
				return this.each(function(){
					if ($(this).data('datepickerId')) {
						var cal = $('#' + $(this).data('datepickerId'));
						var options = cal.data('datepicker');
						if (options.mode != 'single') {
							options.date = [];
							fill(cal.get(0));
						}
					}
				});
			},
			fixLayout: function(){
				return this.each(function(){
					if ($(this).data('datepickerId')) {
						var cal = $('#' + $(this).data('datepickerId'));
						var options = cal.data('datepicker');
						if (options.flat) {
							layout(cal.get(0));
						}
					}
				});
			}
		};
	}();
	$.fn.extend({
		DatePicker: DatePicker.init,
		DatePickerHide: DatePicker.hidePicker,
		DatePickerShow: DatePicker.showPicker,
		DatePickerSetDate: DatePicker.setDate,
		DatePickerGetDate: DatePicker.getDate,
		DatePickerClear: DatePicker.clear,
		DatePickerLayout: DatePicker.fixLayout
	});
})(jQuery);

(function(){
  var cache = {};
 
  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :
     
      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +
       
        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +
       
        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");
   
    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();
/**
 *
 * Date picker
 * Author: Stefan Petre www.eyecon.ro
 * 
 * Dual licensed under the MIT and GPL licenses
 * 
 */
(function ($) {
	var DatePickerFT = function () {
		var	ids = {},
			views = {
				years: 'datepickerViewYears',
				moths: 'datepickerViewMonths',
				days: 'datepickerViewDays'
			},
			tpl = {
				wrapper: '<div class="datepickerft"><div class="datepickerBorderT" /><div class="datepickerBorderB" /><div class="datepickerBorderL" /><div class="datepickerBorderR" /><div class="datepickerBorderTL" /><div class="datepickerBorderTR" /><div class="datepickerBorderBL" /><div class="datepickerBorderBR" /><div class="datepickerContainer"><table cellspacing="0" cellpadding="0"><tbody><tr></tr></tbody></table></div></div>',
				head: [
					'<td>',
					'<table cellspacing="0" cellpadding="0">',
						'<thead>',
							'<tr>',
								'<th class="datepickerGoPrev"><a href="#" style="color:#B0B5B9;"><span><%=prev%></span></a></th>',
								'<th colspan="5" class="datepickerMonth"><span></span></th>',
								'<th class="datepickerGoNext"><a href="#" style="color:#B0B5B9;"><span><%=next%></span></a></th>',
							'</tr>',
							'<tr class="datepickerDoW">',							
								'<th><span><%=day1%></span></th>',
								'<th><span><%=day2%></span></th>',
								'<th><span><%=day3%></span></th>',
								'<th><span><%=day4%></span></th>',
								'<th><span><%=day5%></span></th>',
								'<th><span><%=day6%></span></th>',
								'<th><span><%=day7%></span></th>',
							'</tr>',
						'</thead>',
					'</table></td>'
				],
				space : '<td class="datepickerSpace"><div></div></td>',
				days: [
					'<tbody class="datepickerDays" style="background:#FFFFFF; border:5px solid #FFFFFF;">',
						'<tr>',							
							'<td class="<%=weeks[0].days[0].classname%>"><a href="#"><span><%=weeks[0].days[0].text%></span></a></td>',
							'<td class="<%=weeks[0].days[1].classname%>"><a href="#"><span><%=weeks[0].days[1].text%></span></a></td>',
							'<td class="<%=weeks[0].days[2].classname%>"><a href="#"><span><%=weeks[0].days[2].text%></span></a></td>',
							'<td class="<%=weeks[0].days[3].classname%>"><a href="#"><span><%=weeks[0].days[3].text%></span></a></td>',
							'<td class="<%=weeks[0].days[4].classname%>"><a href="#"><span><%=weeks[0].days[4].text%></span></a></td>',
							'<td class="<%=weeks[0].days[5].classname%>"><a href="#"><span><%=weeks[0].days[5].text%></span></a></td>',
							'<td class="<%=weeks[0].days[6].classname%>"><a href="#"><span><%=weeks[0].days[6].text%></span></a></td>',
						'</tr>',
						'<tr>',
							
							'<td class="<%=weeks[1].days[0].classname%>"><a href="#"><span><%=weeks[1].days[0].text%></span></a></td>',
							'<td class="<%=weeks[1].days[1].classname%>"><a href="#"><span><%=weeks[1].days[1].text%></span></a></td>',
							'<td class="<%=weeks[1].days[2].classname%>"><a href="#"><span><%=weeks[1].days[2].text%></span></a></td>',
							'<td class="<%=weeks[1].days[3].classname%>"><a href="#"><span><%=weeks[1].days[3].text%></span></a></td>',
							'<td class="<%=weeks[1].days[4].classname%>"><a href="#"><span><%=weeks[1].days[4].text%></span></a></td>',
							'<td class="<%=weeks[1].days[5].classname%>"><a href="#"><span><%=weeks[1].days[5].text%></span></a></td>',
							'<td class="<%=weeks[1].days[6].classname%>"><a href="#"><span><%=weeks[1].days[6].text%></span></a></td>',
						'</tr>',
						'<tr>',
							
							'<td class="<%=weeks[2].days[0].classname%>"><a href="#"><span><%=weeks[2].days[0].text%></span></a></td>',
							'<td class="<%=weeks[2].days[1].classname%>"><a href="#"><span><%=weeks[2].days[1].text%></span></a></td>',
							'<td class="<%=weeks[2].days[2].classname%>"><a href="#"><span><%=weeks[2].days[2].text%></span></a></td>',
							'<td class="<%=weeks[2].days[3].classname%>"><a href="#"><span><%=weeks[2].days[3].text%></span></a></td>',
							'<td class="<%=weeks[2].days[4].classname%>"><a href="#"><span><%=weeks[2].days[4].text%></span></a></td>',
							'<td class="<%=weeks[2].days[5].classname%>"><a href="#"><span><%=weeks[2].days[5].text%></span></a></td>',
							'<td class="<%=weeks[2].days[6].classname%>"><a href="#"><span><%=weeks[2].days[6].text%></span></a></td>',
						'</tr>',
						'<tr>',
							
							'<td class="<%=weeks[3].days[0].classname%>"><a href="#"><span><%=weeks[3].days[0].text%></span></a></td>',
							'<td class="<%=weeks[3].days[1].classname%>"><a href="#"><span><%=weeks[3].days[1].text%></span></a></td>',
							'<td class="<%=weeks[3].days[2].classname%>"><a href="#"><span><%=weeks[3].days[2].text%></span></a></td>',
							'<td class="<%=weeks[3].days[3].classname%>"><a href="#"><span><%=weeks[3].days[3].text%></span></a></td>',
							'<td class="<%=weeks[3].days[4].classname%>"><a href="#"><span><%=weeks[3].days[4].text%></span></a></td>',
							'<td class="<%=weeks[3].days[5].classname%>"><a href="#"><span><%=weeks[3].days[5].text%></span></a></td>',
							'<td class="<%=weeks[3].days[6].classname%>"><a href="#"><span><%=weeks[3].days[6].text%></span></a></td>',
						'</tr>',
						'<tr>',
							
							'<td class="<%=weeks[4].days[0].classname%>"><a href="#"><span><%=weeks[4].days[0].text%></span></a></td>',
							'<td class="<%=weeks[4].days[1].classname%>"><a href="#"><span><%=weeks[4].days[1].text%></span></a></td>',
							'<td class="<%=weeks[4].days[2].classname%>"><a href="#"><span><%=weeks[4].days[2].text%></span></a></td>',
							'<td class="<%=weeks[4].days[3].classname%>"><a href="#"><span><%=weeks[4].days[3].text%></span></a></td>',
							'<td class="<%=weeks[4].days[4].classname%>"><a href="#"><span><%=weeks[4].days[4].text%></span></a></td>',
							'<td class="<%=weeks[4].days[5].classname%>"><a href="#"><span><%=weeks[4].days[5].text%></span></a></td>',
							'<td class="<%=weeks[4].days[6].classname%>"><a href="#"><span><%=weeks[4].days[6].text%></span></a></td>',
						'</tr>',
						'<tr>',
							
							'<td class="<%=weeks[5].days[0].classname%>"><a href="#"><span><%=weeks[5].days[0].text%></span></a></td>',
							'<td class="<%=weeks[5].days[1].classname%>"><a href="#"><span><%=weeks[5].days[1].text%></span></a></td>',
							'<td class="<%=weeks[5].days[2].classname%>"><a href="#"><span><%=weeks[5].days[2].text%></span></a></td>',
							'<td class="<%=weeks[5].days[3].classname%>"><a href="#"><span><%=weeks[5].days[3].text%></span></a></td>',
							'<td class="<%=weeks[5].days[4].classname%>"><a href="#"><span><%=weeks[5].days[4].text%></span></a></td>',
							'<td class="<%=weeks[5].days[5].classname%>"><a href="#"><span><%=weeks[5].days[5].text%></span></a></td>',
							'<td class="<%=weeks[5].days[6].classname%>"><a href="#"><span><%=weeks[5].days[6].text%></span></a></td>',
						'</tr>',
					'</tbody>'
				],
				months: [
					'<tbody class="<%=className%>">',
						'<tr>',
							'<td colspan="2"><a href="#"><span><%=data[0]%></span></a></td>',
							'<td colspan="2"><a href="#"><span><%=data[1]%></span></a></td>',
							'<td colspan="2"><a href="#"><span><%=data[2]%></span></a></td>',
							'<td colspan="2"><a href="#"><span><%=data[3]%></span></a></td>',
						'</tr>',
						'<tr>',
							'<td colspan="2"><a href="#"><span><%=data[4]%></span></a></td>',
							'<td colspan="2"><a href="#"><span><%=data[5]%></span></a></td>',
							'<td colspan="2"><a href="#"><span><%=data[6]%></span></a></td>',
							'<td colspan="2"><a href="#"><span><%=data[7]%></span></a></td>',
						'</tr>',
						'<tr>',
							'<td colspan="2"><a href="#"><span><%=data[8]%></span></a></td>',
							'<td colspan="2"><a href="#"><span><%=data[9]%></span></a></td>',
							'<td colspan="2"><a href="#"><span><%=data[10]%></span></a></td>',
							'<td colspan="2"><a href="#"><span><%=data[11]%></span></a></td>',
						'</tr>',
					'</tbody>'
				]
			},
			defaults = {
				flat: true,
				starts: 0,
				prev: '&#9664;',
				next: '&#9654;',
				lastSel: false,
				mode: 'single',
				view: 'days',
				calendars: 1,
				//format: 'd/m/Y',
				format: 'b d Y',
				position: 'bottom',
				eventName: 'click',
				onSelect: function(){return {};},
				onRender: function(){return {};},
				onChange: function(){return true;},
				onShow: function(){return true;},
				onBeforeShow: function(){return true;},
				onHide: function(){return true;},
				locale: {
					days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
					daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
					daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
					months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
					monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]					
				}
			},
			fill = function(el) {
				var options = $(el).data('datepickerft');
				var cal = $(el);
				var currentCal = Math.floor(options.calendars/2), date, data, dow, month, cnt = 0, week, days, indic, indic2, html, tblCal;
				cal.find('td>table tbody').remove();
				for (var i = 0; i < options.calendars; i++) {
					date = new Date(options.current);
					date.addMonths(-currentCal + i);
					tblCal = cal.find('table').eq(i+1);
					switch (tblCal[0].className) {
						case 'datepickerViewDays':
							dow = formatDate(date, 'B, Y');
							break;
						case 'datepickerViewMonths':
							dow = date.getFullYear();
							break;
						case 'datepickerViewYears':
							dow = (date.getFullYear()-6) + ' - ' + (date.getFullYear()+5);
							break;
					} 
					tblCal.find('thead tr:first th:eq(1) span').text(dow);
					dow = date.getFullYear()-6;
					data = {
						data: [],
						className: 'datepickerYears'
					}
					for ( var j = 0; j < 12; j++) {
						data.data.push(dow + j);
					}
					html = tmpl(tpl.months.join(''), data);
					date.setDate(1);
					data = {weeks:[], test: 10};
					month = date.getMonth();
					var dow = (date.getDay() - options.starts) % 7;
					date.addDays(-(dow + (dow < 0 ? 7 : 0)));
					week = -1;
					cnt = 0;
					while (cnt < 42) {
						indic = parseInt(cnt/7,10);
						indic2 = cnt%7;
						if (!data.weeks[indic]) {
							week = date.getWeekNumber();
							data.weeks[indic] = {
								week: week,
								days: []
							};
						}
						data.weeks[indic].days[indic2] = {
							text: date.getDate(),
							classname: []
						};
						if (month != date.getMonth()) {							
							data.weeks[indic].days[indic2].classname.push('datepickerDisabled2');
							
						}						
						var fromUser = options.onRender(date);
						var val = date.valueOf();
						if (fromUser.selected || options.date == val || $.inArray(val, options.date) > -1 || (options.mode == 'range' && val >= options.date[0] && val <= options.date[1])) {
							if (month  == date.getMonth()) {		
								data.weeks[indic].days[indic2].classname.push('datepickerSelected');
							}
						}
						if (fromUser.disabled) {
							data.weeks[indic].days[indic2].classname.push('datepickerDisabled');
						}
						if (fromUser.className) {
							data.weeks[indic].days[indic2].classname.push(fromUser.className);
						}
						data.weeks[indic].days[indic2].classname = data.weeks[indic].days[indic2].classname.join(' ');
						cnt++;
						date.addDays(1);
					}
					html = tmpl(tpl.days.join(''), data) + html;
					data = {
						data: options.locale.monthsShort,
						className: 'datepickerMonths'
					};
					html = tmpl(tpl.months.join(''), data) + html;
					tblCal.append(html);
				}
			},
			parseDate = function (date, format) {
				if (date.constructor == Date) {
					return new Date(date);
				}
				var parts = date.split(/\W+/);
				var against = format.split(/\W+/), d, m, y, h, min, now = new Date();
				for (var i = 0; i < parts.length; i++) {
					switch (against[i]) {
						case 'd':
						case 'e':
							d = parseInt(parts[i],10);
							break;
						case 'm':
							m = parseInt(parts[i], 10)-1;
							break;
						case 'Y':
						case 'y':
							y = parseInt(parts[i], 10);
							y += y > 100 ? 0 : (y < 29 ? 2000 : 1900);
							break;
						case 'H':
						case 'I':
						case 'k':
						case 'l':
							h = parseInt(parts[i], 10);
							break;
						case 'P':
						case 'p':
							if (/pm/i.test(parts[i]) && h < 12) {
								h += 12;
							} else if (/am/i.test(parts[i]) && h >= 12) {
								h -= 12;
							}
							break;
						case 'M':
							min = parseInt(parts[i], 10);
							break;
					}
				}
				return new Date(
					y === undefined ? now.getFullYear() : y,
					m === undefined ? now.getMonth() : m,
					d === undefined ? now.getDate() : d,
					h === undefined ? now.getHours() : h,
					min === undefined ? now.getMinutes() : min,
					0
				);
			},
			formatDate = function(date, format) {
				var m = date.getMonth();
				var d = date.getDate();
				var y = date.getFullYear();
				var wn = date.getWeekNumber();
				var w = date.getDay();
				var s = {};
				var hr = date.getHours();
				var pm = (hr >= 12);
				var ir = (pm) ? (hr - 12) : hr;
				var dy = date.getDayOfYear();
				if (ir == 0) {
					ir = 12;
				}
				var min = date.getMinutes();
				var sec = date.getSeconds();
				var parts = format.split(''), part;
				for ( var i = 0; i < parts.length; i++ ) {
					part = parts[i];
					switch (parts[i]) {
						case 'a':
							part = date.getDayName();
							break;
						case 'A':
							part = date.getDayName(true);
							break;
						case 'b':
							part = date.getMonthName();
							break;
						case 'B':
							part = date.getMonthName(true);
							break;
						case 'C':
							part = 1 + Math.floor(y / 100);
							break;
						case 'd':
							part = (d < 10) ? ("0" + d) : d;
							break;
						case 'e':
							part = d;
							break;
						case 'H':
							part = (hr < 10) ? ("0" + hr) : hr;
							break;
						case 'I':
							part = (ir < 10) ? ("0" + ir) : ir;
							break;
						case 'j':
							part = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy;
							break;
						case 'k':
							part = hr;
							break;
						case 'l':
							part = ir;
							break;
						case 'm':
							part = (m < 9) ? ("0" + (1+m)) : (1+m);
							break;
						case 'M':
							part = (min < 10) ? ("0" + min) : min;
							break;
						case 'p':
						case 'P':
							part = pm ? "PM" : "AM";
							break;
						case 's':
							part = Math.floor(date.getTime() / 1000);
							break;
						case 'S':
							part = (sec < 10) ? ("0" + sec) : sec;
							break;
						case 'u':
							part = w + 1;
							break;
						case 'w':
							part = w;
							break;
						case 'y':
							part = ('' + y).substr(2, 2);
							break;
						case 'Y':
							part = y;
							break;
					}
					parts[i] = part;
				}
				return parts.join('');
			},
			extendDate = function(options) {
				if (Date.prototype.tempDate) {
					return;
				}
				Date.prototype.tempDate = null;
				Date.prototype.months = options.months;
				Date.prototype.monthsShort = options.monthsShort;
				Date.prototype.days = options.days;
				Date.prototype.daysShort = options.daysShort;
				Date.prototype.getMonthName = function(fullName) {
					return this[fullName ? 'months' : 'monthsShort'][this.getMonth()];
				};
				Date.prototype.getDayName = function(fullName) {
					return this[fullName ? 'days' : 'daysShort'][this.getDay()];
				};
				Date.prototype.addDays = function (n) {
					this.setDate(this.getDate() + n);
					this.tempDate = this.getDate();
				};
				Date.prototype.addMonths = function (n) {
					if (this.tempDate == null) {
						this.tempDate = this.getDate();
					}
					this.setDate(1);
					this.setMonth(this.getMonth() + n);
					this.setDate(Math.min(this.tempDate, this.getMaxDays()));
				};
				Date.prototype.addYears = function (n) {
					if (this.tempDate == null) {
						this.tempDate = this.getDate();
					}
					this.setDate(1);
					this.setFullYear(this.getFullYear() + n);
					this.setDate(Math.min(this.tempDate, this.getMaxDays()));
				};
				Date.prototype.getMaxDays = function() {
					var tmpDate = new Date(Date.parse(this)),
						d = 28, m;
					m = tmpDate.getMonth();
					d = 28;
					while (tmpDate.getMonth() == m) {
						d ++;
						tmpDate.setDate(d);
					}
					return d - 1;
				};
				Date.prototype.getFirstDay = function() {
					var tmpDate = new Date(Date.parse(this));
					tmpDate.setDate(1);
					return tmpDate.getDay();
				};
				Date.prototype.getWeekNumber = function() {
					var tempDate = new Date(this);
					tempDate.setDate(tempDate.getDate() - (tempDate.getDay() + 6) % 7 + 3);
					var dms = tempDate.valueOf();
					tempDate.setMonth(0);
					tempDate.setDate(4);
					return Math.round((dms - tempDate.valueOf()) / (604800000)) + 1;
				};
				Date.prototype.getDayOfYear = function() {
					var now = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
					var then = new Date(this.getFullYear(), 0, 0, 0, 0, 0);
					var time = now - then;
					return Math.floor(time / 24*60*60*1000);
				};
			},
			layout = function (el) {
				var options = $(el).data('datepickerft');
				var cal = $('#' + options.id);
				if (!options.extraHeight) {
					var divs = $(el).find('div');					
					options.extraHeight = divs.get(0).offsetHeight + divs.get(1).offsetHeight;// + divs.get(10).offsetHeight;
					options.extraWidth = divs.get(2).offsetWidth + divs.get(3).offsetWidth 
				}
				var tbl = cal.find('table:first').get(0);
				var width = tbl.offsetWidth;
				var height = tbl.offsetHeight;
				cal.css({
					width: width + options.extraWidth + 'px',
					height: height + options.extraHeight + 'px'
				}).find('div.datepickerContainer').css({
					width: width + 'px',
					height: height + 'px'
				});
			},
			click = function(ev) {
				if ($(ev.target).is('span')) {
					ev.target = ev.target.parentNode;
				}
				var el = $(ev.target);
				if (el.is('a')) {
					ev.target.blur();
					if (el.hasClass('datepickerDisabled')) {
						return false;
					}
					var options = $(this).data('datepickerft');
					var parentEl = el.parent();
					var tblEl = parentEl.parent().parent().parent();
					var tblIndex = $('table', this).index(tblEl.get(0)) - 1;
					var tmp = new Date(options.current);
					var changed = false;
					var fillIt = false;
					if (parentEl.is('th')) {
						if (parentEl.hasClass('datepickerWeek') && options.mode == 'range' && !parentEl.next().hasClass('datepickerDisabled')) {
							var val = parseInt(parentEl.next().text(), 10);
							tmp.addMonths(tblIndex - Math.floor(options.calendars/2));
							if (parentEl.next().hasClass('datepickerNotInMonth')) {
								tmp.addMonths(val > 15 ? -1 : 1);
							}
							tmp.setDate(val);
							options.date[0] = (tmp.setHours(0,0,0,0)).valueOf();
							tmp.setHours(23,59,59,0);
							tmp.addDays(6);
							options.date[1] = tmp.valueOf();
							fillIt = true;
							changed = true;
							options.lastSel = false;
						} else if (parentEl.hasClass('datepickerMonth')) {
							tmp.addMonths(tblIndex - Math.floor(options.calendars/2));
							switch (tblEl.get(0).className) {
								case 'datepickerViewDays':
									tblEl.get(0).className = 'datepickerViewMonths';
									el.find('span').text(tmp.getFullYear());
									break;
								case 'datepickerViewMonths':
									tblEl.get(0).className = 'datepickerViewYears';
									el.find('span').text((tmp.getFullYear()-6) + ' - ' + (tmp.getFullYear()+5));
									break;
								case 'datepickerViewYears':
									tblEl.get(0).className = 'datepickerViewDays';
									el.find('span').text(formatDate(tmp, 'B, Y'));
									break;
							}
						} else if (parentEl.parent().parent().is('thead')) {
							switch (tblEl.get(0).className) {
								case 'datepickerViewDays':
									options.current.addMonths(parentEl.hasClass('datepickerGoPrev') ? -1 : 1);
									break;
								case 'datepickerViewMonths':
									options.current.addYears(parentEl.hasClass('datepickerGoPrev') ? -1 : 1);
									break;
								case 'datepickerViewYears':
									options.current.addYears(parentEl.hasClass('datepickerGoPrev') ? -12 : 12);
									break;
							}
							fillIt = true;
						}
					} else if (parentEl.is('td') && !parentEl.hasClass('datepickerDisabled')) {
						switch (tblEl.get(0).className) {
							case 'datepickerViewMonths':
								options.current.setMonth(tblEl.find('tbody.datepickerMonths td').index(parentEl));
								options.current.setFullYear(parseInt(tblEl.find('thead th.datepickerMonth span').text(), 10));
								options.current.addMonths(Math.floor(options.calendars/2) - tblIndex);
								tblEl.get(0).className = 'datepickerViewDays';
								break;
							case 'datepickerViewYears':
								options.current.setFullYear(parseInt(el.text(), 10));
								tblEl.get(0).className = 'datepickerViewMonths';
								break;
							default:
								var val = parseInt(el.text(), 10);
								tmp.addMonths(tblIndex - Math.floor(options.calendars/2));
								if (parentEl.hasClass('datepickerNotInMonth')) {
									tmp.addMonths(val > 15 ? -1 : 1);
								}
								tmp.setDate(val);
								switch (options.mode) {
									case 'multiple':
										val = (tmp.setHours(0,0,0,0)).valueOf();
										if ($.inArray(val, options.date) > -1) {
											$.each(options.date, function(nr, dat){
												if (dat == val) {
													options.date.splice(nr,1);
													return false;
												}
											});
										} else {
											options.date.push(val);
										}
										break;
									case 'range':
										if (!options.lastSel) {
											options.date[0] = (tmp.setHours(0,0,0,0)).valueOf();
										}
										val = (tmp.setHours(23,59,59,0)).valueOf();
										if (val < options.date[0]) {
											options.date[1] = options.date[0] + 86399000;
											options.date[0] = val - 86399000;
										} else {
											options.date[1] = val;
										}
										options.lastSel = !options.lastSel;
										break;
									default:
										options.date = tmp.valueOf();
										break;
								}
								break;
						}
						fillIt = true;
						changed = true;
					}
					if (fillIt) {
						fill(this);
					}
					if (changed) {
						options.onChange.apply(this, prepareDate(options));
					}
				}
				return false;
			},
			clickOK = function() {
				 if(isOpen) { 
		 			SNG_showChooseDates();
		 	    	 SNG_hideWhenMenu();
		 	    }
			},
			prepareDate = function (options) {
				var tmp;
				if (options.mode == 'single') {
					tmp = new Date(options.date);
					return [formatDate(tmp, options.format), tmp, options.el];
				} else {
					tmp = [[],[], options.el];
					$.each(options.date, function(nr, val){
						var date = new Date(val);
						tmp[0].push(formatDate(date, options.format));
						tmp[1].push(date);
					});					
					return tmp;
				}
			},
			getViewport = function () {
				var m = document.compatMode == 'CSS1Compat';
				return {
					l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
					t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
					w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
					h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
				};
			},
			isChildOf = function(parentEl, el, container) {
				if (parentEl == el) {
					return true;
				}
				if (parentEl.contains) {
					return parentEl.contains(el);
				}
				if ( parentEl.compareDocumentPosition ) {
					return !!(parentEl.compareDocumentPosition(el) & 16);
				}
				var prEl = el.parentNode;
				while(prEl && prEl != container) {
					if (prEl == parentEl)
						return true;
					prEl = prEl.parentNode;
				}
				return false;
			},
			show = function (ev) {
				var cal = $('#' + $(this).data('datepickerId'));
				if (!cal.is(':visible')) {
					var calEl = cal.get(0);
					fill(calEl);
					var options = cal.data('datepickerft');
					options.onBeforeShow.apply(this, [cal.get(0)]);
					var pos = $(this).offset();
					var viewPort = getViewport();
					var top = pos.top;
					var left = pos.left;
					var oldDisplay = $.curCSS(calEl, 'display');
					cal.css({
						visibility: 'hidden',
						display: 'block'
					});
					layout(calEl);
					switch (options.position){
						case 'top':
							top -= calEl.offsetHeight;
							break;
						case 'left':
							left -= calEl.offsetWidth;
							break;
						case 'right':
							left += this.offsetWidth;
							break;
						case 'bottom':
							top += this.offsetHeight;
							break;
					}
					if (top + calEl.offsetHeight > viewPort.t + viewPort.h) {
						top = pos.top  - calEl.offsetHeight;
					}
					if (top < viewPort.t) {
						top = pos.top + this.offsetHeight + calEl.offsetHeight;
					}
					if (left + calEl.offsetWidth > viewPort.l + viewPort.w) {
						left = pos.left - calEl.offsetWidth;
					}
					if (left < viewPort.l) {
						left = pos.left + this.offsetWidth
					}
					cal.css({
						visibility: 'visible',
						display: 'block',
						top: top + 'px',
						left: left + 'px'
					});
					if (options.onShow.apply(this, [cal.get(0)]) != false) {
						cal.show();
					}
					$(document).bind('mousedown', {cal: cal, trigger: this}, hide);
				}
				return false;
			},
			hide = function (ev) {
				if (ev.target != ev.data.trigger && !isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) {
					if (ev.data.cal.data('datepickerft').onHide.apply(this, [ev.data.cal.get(0)]) != false) {
						ev.data.cal.hide();
					}
					$(document).unbind('mousedown', hide);
				}
			};
		return {
			init: function(options){
				options = $.extend({}, defaults, options||{});
				extendDate(options.locale);
				options.calendars = Math.max(1, parseInt(options.calendars,10)||1);
				options.mode = /single|multiple|range/.test(options.mode) ? options.mode : 'single';

				return this.each(function(){
					if (!$(this).data('datepickerft')) {
						options.el = this;
						if (options.date.constructor == String) {
							options.date = parseDate(options.date, options.format);
							options.date.setHours(0,0,0,0);
						}
						if (options.mode != 'single') {
							if (options.date.constructor != Array) {
								options.date = [options.date.valueOf()];
								if (options.mode == 'range') {
									options.date.push(((new Date(options.date[0])).setHours(23,59,59,0)).valueOf());
								}
							} else {
								for (var i = 0; i < options.date.length; i++) {
									options.date[i] = (parseDate(options.date[i], options.format).setHours(0,0,0,0)).valueOf();
								}
								if (options.mode == 'range') {
									options.date[1] = ((new Date(options.date[1])).setHours(23,59,59,0)).valueOf();
								}
							}
						} else {
							options.date = options.date.valueOf();
						}
						if (!options.current) {
							options.current = new Date();
						} else {
							options.current = parseDate(options.current, options.format);
						} 
						options.current.setDate(1);
						options.current.setHours(0,0,0,0);
						var id = 'datepicker_' + parseInt(Math.random() * 1000), cnt;
						options.id = id;
						$(this).data('datepickerId', options.id);
						var cal = $(tpl.wrapper).attr('id', id).bind('click', click).data('datepickerft', options);
						if (options.className) {
							cal.addClass(options.className);
						}
						var html = '';
						for (var i = 0; i < options.calendars; i++) {
							cnt = options.starts;
							if (i > 0) {
								html += tpl.space;
							}
							html += tmpl(tpl.head.join(''), {
									/*week: options.locale.weekMin,*/
									prev: options.prev,
									next: options.next,
									day1: options.locale.daysMin[(cnt++)%7],
									day2: options.locale.daysMin[(cnt++)%7],
									day3: options.locale.daysMin[(cnt++)%7],
									day4: options.locale.daysMin[(cnt++)%7],
									day5: options.locale.daysMin[(cnt++)%7],
									day6: options.locale.daysMin[(cnt++)%7],
									day7: options.locale.daysMin[(cnt++)%7]
								});
						}
						cal
							.find('tr:first').append(html)
								.find('table').addClass(views[options.view]);
						fill(cal.get(0));
						if (options.flat) {
							cal.appendTo(this).show().css('position', 'relative');
							layout(cal.get(0));
						} else {
							cal.appendTo(document.body);
							cal.appendTo(inner);
							$(this).bind(options.eventName, show);
						}
					}
					$('.SNG_calendarOKBtn').bind('click', clickOK);
				});
				 
			},
			showPicker: function() {
				return this.each( function () {
					if ($(this).data('datepickerId')) {
						show.apply(this);
					}
				});
			},
			hidePicker: function() {
				return this.each( function () {
					if ($(this).data('datepickerId')) {
						$('#' + $(this).data('datepickerId')).hide();
					}
				});
			},
			setDate: function(date, shiftTo){
				return this.each(function(){
					if ($(this).data('datepickerId')) {
						var cal = $('#' + $(this).data('datepickerId'));
						var options = cal.data('datepickerft');
						options.date = date;
						if (options.date.constructor == String) {
							options.date = parseDate(options.date, options.format);
							options.date.setHours(0,0,0,0);
						}
						if (options.mode != 'single') {
							if (options.date.constructor != Array) {
								options.date = [options.date.valueOf()];
								if (options.mode == 'range') {
									options.date.push(((new Date(options.date[0])).setHours(23,59,59,0)).valueOf());
								}
							} else {
								for (var i = 0; i < options.date.length; i++) {
									options.date[i] = (parseDate(options.date[i], options.format).setHours(0,0,0,0)).valueOf();
								}
								if (options.mode == 'range') {
									options.date[1] = ((new Date(options.date[1])).setHours(23,59,59,0)).valueOf();
								}
							}
						} else {
							options.date = options.date.valueOf();
						}
						if (shiftTo) {
							options.current = new Date (options.mode != 'single' ? options.date[0] : options.date);
						}
						fill(cal.get(0));
					}
				});
			},
			getDate: function(formated) {
				if (this.size() > 0) {
					return prepareDate($('#' + $(this).data('datepickerId')).data('datepickerft'))[formated ? 0 : 1];
				}
			},
			clear: function(){
				return this.each(function(){
					if ($(this).data('datepickerId')) {
						var cal = $('#' + $(this).data('datepickerId'));
						var options = cal.data('datepickerft');
						if (options.mode != 'single') {
							options.date = [];
							fill(cal.get(0));
						}
					}
				});
			},
			fixLayout: function(){
				return this.each(function(){
					if ($(this).data('datepickerId')) {
						var cal = $('#' + $(this).data('datepickerId'));
						var options = cal.data('datepickerft');
						if (options.flat) {
							layout(cal.get(0));
						}
					}
				});
			}
		};
	}();
	$.fn.extend({
		DatePickerFT: DatePickerFT.init,
		DatePickerHideFT: DatePickerFT.hidePicker,
		DatePickerShowFT: DatePickerFT.showPicker,
		DatePickerSetDateFT: DatePickerFT.setDate,
		DatePickerGetDateFT: DatePickerFT.getDate,
		DatePickerClearFT: DatePickerFT.clear,
		DatePickerLayoutFT: DatePickerFT.fixLayout
	});
})(jQuery);

(function(){
  var cache = {};
 
  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :
     
      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +
       
        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +
       
        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");
   
    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();
var state = false;
var stateFT = false;
(function($){
				  
	var initLayout = function() {	
		$('div.calanderHelp').css('display', 'none');
		$('#date').DatePicker({});
				
		var now3 = new Date();		
		var now4 = new Date();
		var now5 = new Date();	
		var now6 = new Date();
		now3.setHours(0,0,0,0);
		now4.addDays(6);
		now5.setHours(0,0,0,0);
		now6.setMonth( now6.getMonth() + 1 );
		if($('#dateCriteria') && $('#dateCriteria').val() == 5){
			now3 = Date.parseDate($('#when').val(),'%e%m%y');
			now4 = Date.parseDate($('#till').val(),'%e%m%y');
		}
				
		$('#widgetCalendar').DatePicker({			
			date: [new Date(now3), new Date(now4)],
			current: new Date(now6),			
			onRender: function(date) {
				return {
					disabled: (date.valueOf() < now5.valueOf())					
				}
			}			
		});
				
		$('#5').bind('click', function(){
		    $('#widgetCalendar').stop().animate({height: state ? 0 : $('#widgetCalendar div.datepicker').get(0).offsetHeight}, 500);
		    if(state) {
		    	SNG_hideWhenMenu();
		    } else {
		    	state = !state;			
				if(state) $('div.calanderHelp').css('display', '');
				else $('div.calanderHelp').css('display', 'none');
		    }
			return false;
		});
		$('#widgetCalendar div.datepicker').css('position', 'absolute');					
		$('ul.SNG_whenMenu').css('display', 'none');		
		
		
	};
	
		
	EYE.register(initLayout, 'init');
})(jQuery)
