/* SWFObject v2.1 <http://code.google.com/p/swfobject/>
	Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis
	This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject=function(){var b="undefined",Q="object",n="Shockwave Flash",p="ShockwaveFlash.ShockwaveFlash",P="application/x-shockwave-flash",m="SWFObjectExprInst",j=window,K=document,T=navigator,o=[],N=[],i=[],d=[],J,Z=null,M=null,l=null,e=false,A=false;var h=function(){var v=typeof K.getElementById!=b&&typeof K.getElementsByTagName!=b&&typeof K.createElement!=b,AC=[0,0,0],x=null;if(typeof T.plugins!=b&&typeof T.plugins[n]==Q){x=T.plugins[n].description;if(x&&!(typeof T.mimeTypes!=b&&T.mimeTypes[P]&&!T.mimeTypes[P].enabledPlugin)){x=x.replace(/^.*\s+(\S+\s+\S+$)/,"$1");AC[0]=parseInt(x.replace(/^(.*)\..*$/,"$1"),10);AC[1]=parseInt(x.replace(/^.*\.(.*)\s.*$/,"$1"),10);AC[2]=/r/.test(x)?parseInt(x.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof j.ActiveXObject!=b){var y=null,AB=false;try{y=new ActiveXObject(p+".7")}catch(t){try{y=new ActiveXObject(p+".6");AC=[6,0,21];y.AllowScriptAccess="always"}catch(t){if(AC[0]==6){AB=true}}if(!AB){try{y=new ActiveXObject(p)}catch(t){}}}if(!AB&&y){try{x=y.GetVariable("$version");if(x){x=x.split(" ")[1].split(",");AC=[parseInt(x[0],10),parseInt(x[1],10),parseInt(x[2],10)]}}catch(t){}}}}var AD=T.userAgent.toLowerCase(),r=T.platform.toLowerCase(),AA=/webkit/.test(AD)?parseFloat(AD.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,q=false,z=r?/win/.test(r):/win/.test(AD),w=r?/mac/.test(r):/mac/.test(AD);/*@cc_on q=true;@if(@_win32)z=true;@elif(@_mac)w=true;@end@*/return{w3cdom:v,pv:AC,webkit:AA,ie:q,win:z,mac:w}}();var L=function(){if(!h.w3cdom){return }f(H);if(h.ie&&h.win){try{K.write("<script id=__ie_ondomload defer=true src=//:><\/script>");J=C("__ie_ondomload");if(J){I(J,"onreadystatechange",S)}}catch(q){}}if(h.webkit&&typeof K.readyState!=b){Z=setInterval(function(){if(/loaded|complete/.test(K.readyState)){E()}},10)}if(typeof K.addEventListener!=b){K.addEventListener("DOMContentLoaded",E,null)}R(E)}();function S(){if(J.readyState=="complete"){J.parentNode.removeChild(J);E()}}function E(){if(e){return }if(h.ie&&h.win){var v=a("span");try{var u=K.getElementsByTagName("body")[0].appendChild(v);u.parentNode.removeChild(u)}catch(w){return }}e=true;if(Z){clearInterval(Z);Z=null}var q=o.length;for(var r=0;r<q;r++){o[r]()}}function f(q){if(e){q()}else{o[o.length]=q}}function R(r){if(typeof j.addEventListener!=b){j.addEventListener("load",r,false)}else{if(typeof K.addEventListener!=b){K.addEventListener("load",r,false)}else{if(typeof j.attachEvent!=b){I(j,"onload",r)}else{if(typeof j.onload=="function"){var q=j.onload;j.onload=function(){q();r()}}else{j.onload=r}}}}}function H(){var t=N.length;for(var q=0;q<t;q++){var u=N[q].id;if(h.pv[0]>0){var r=C(u);if(r){N[q].width=r.getAttribute("width")?r.getAttribute("width"):"0";N[q].height=r.getAttribute("height")?r.getAttribute("height"):"0";if(c(N[q].swfVersion)){if(h.webkit&&h.webkit<312){Y(r)}W(u,true)}else{if(N[q].expressInstall&&!A&&c("6.0.65")&&(h.win||h.mac)){k(N[q])}else{O(r)}}}}else{W(u,true)}}}function Y(t){var q=t.getElementsByTagName(Q)[0];if(q){var w=a("embed"),y=q.attributes;if(y){var v=y.length;for(var u=0;u<v;u++){if(y[u].nodeName=="DATA"){w.setAttribute("src",y[u].nodeValue)}else{w.setAttribute(y[u].nodeName,y[u].nodeValue)}}}var x=q.childNodes;if(x){var z=x.length;for(var r=0;r<z;r++){if(x[r].nodeType==1&&x[r].nodeName=="PARAM"){w.setAttribute(x[r].getAttribute("name"),x[r].getAttribute("value"))}}}t.parentNode.replaceChild(w,t)}}function k(w){A=true;var u=C(w.id);if(u){if(w.altContentId){var y=C(w.altContentId);if(y){M=y;l=w.altContentId}}else{M=G(u)}if(!(/%$/.test(w.width))&&parseInt(w.width,10)<310){w.width="310"}if(!(/%$/.test(w.height))&&parseInt(w.height,10)<137){w.height="137"}K.title=K.title.slice(0,47)+" - Flash Player Installation";var z=h.ie&&h.win?"ActiveX":"PlugIn",q=K.title,r="MMredirectURL="+j.location+"&MMplayerType="+z+"&MMdoctitle="+q,x=w.id;if(h.ie&&h.win&&u.readyState!=4){var t=a("div");x+="SWFObjectNew";t.setAttribute("id",x);u.parentNode.insertBefore(t,u);u.style.display="none";var v=function(){u.parentNode.removeChild(u)};I(j,"onload",v)}U({data:w.expressInstall,id:m,width:w.width,height:w.height},{flashvars:r},x)}}function O(t){if(h.ie&&h.win&&t.readyState!=4){var r=a("div");t.parentNode.insertBefore(r,t);r.parentNode.replaceChild(G(t),r);t.style.display="none";var q=function(){t.parentNode.removeChild(t)};I(j,"onload",q)}else{t.parentNode.replaceChild(G(t),t)}}function G(v){var u=a("div");if(h.win&&h.ie){u.innerHTML=v.innerHTML}else{var r=v.getElementsByTagName(Q)[0];if(r){var w=r.childNodes;if(w){var q=w.length;for(var t=0;t<q;t++){if(!(w[t].nodeType==1&&w[t].nodeName=="PARAM")&&!(w[t].nodeType==8)){u.appendChild(w[t].cloneNode(true))}}}}}return u}function U(AG,AE,t){var q,v=C(t);if(v){if(typeof AG.id==b){AG.id=t}if(h.ie&&h.win){var AF="";for(var AB in AG){if(AG[AB]!=Object.prototype[AB]){if(AB.toLowerCase()=="data"){AE.movie=AG[AB]}else{if(AB.toLowerCase()=="styleclass"){AF+=' class="'+AG[AB]+'"'}else{if(AB.toLowerCase()!="classid"){AF+=" "+AB+'="'+AG[AB]+'"'}}}}}var AD="";for(var AA in AE){if(AE[AA]!=Object.prototype[AA]){AD+='<param name="'+AA+'" value="'+AE[AA]+'" />'}}v.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+AF+">"+AD+"</object>";i[i.length]=AG.id;q=C(AG.id)}else{if(h.webkit&&h.webkit<312){var AC=a("embed");AC.setAttribute("type",P);for(var z in AG){if(AG[z]!=Object.prototype[z]){if(z.toLowerCase()=="data"){AC.setAttribute("src",AG[z])}else{if(z.toLowerCase()=="styleclass"){AC.setAttribute("class",AG[z])}else{if(z.toLowerCase()!="classid"){AC.setAttribute(z,AG[z])}}}}}for(var y in AE){if(AE[y]!=Object.prototype[y]){if(y.toLowerCase()!="movie"){AC.setAttribute(y,AE[y])}}}v.parentNode.replaceChild(AC,v);q=AC}else{var u=a(Q);u.setAttribute("type",P);for(var x in AG){if(AG[x]!=Object.prototype[x]){if(x.toLowerCase()=="styleclass"){u.setAttribute("class",AG[x])}else{if(x.toLowerCase()!="classid"){u.setAttribute(x,AG[x])}}}}for(var w in AE){if(AE[w]!=Object.prototype[w]&&w.toLowerCase()!="movie"){F(u,w,AE[w])}}v.parentNode.replaceChild(u,v);q=u}}}return q}function F(t,q,r){var u=a("param");u.setAttribute("name",q);u.setAttribute("value",r);t.appendChild(u)}function X(r){var q=C(r);if(q&&(q.nodeName=="OBJECT"||q.nodeName=="EMBED")){if(h.ie&&h.win){if(q.readyState==4){B(r)}else{j.attachEvent("onload",function(){B(r)})}}else{q.parentNode.removeChild(q)}}}function B(t){var r=C(t);if(r){for(var q in r){if(typeof r[q]=="function"){r[q]=null}}r.parentNode.removeChild(r)}}function C(t){var q=null;try{q=K.getElementById(t)}catch(r){}return q}function a(q){return K.createElement(q)}function I(t,q,r){t.attachEvent(q,r);d[d.length]=[t,q,r]}function c(t){var r=h.pv,q=t.split(".");q[0]=parseInt(q[0],10);q[1]=parseInt(q[1],10)||0;q[2]=parseInt(q[2],10)||0;return(r[0]>q[0]||(r[0]==q[0]&&r[1]>q[1])||(r[0]==q[0]&&r[1]==q[1]&&r[2]>=q[2]))?true:false}function V(v,r){if(h.ie&&h.mac){return }var u=K.getElementsByTagName("head")[0],t=a("style");t.setAttribute("type","text/css");t.setAttribute("media","screen");if(!(h.ie&&h.win)&&typeof K.createTextNode!=b){t.appendChild(K.createTextNode(v+" {"+r+"}"))}u.appendChild(t);if(h.ie&&h.win&&typeof K.styleSheets!=b&&K.styleSheets.length>0){var q=K.styleSheets[K.styleSheets.length-1];if(typeof q.addRule==Q){q.addRule(v,r)}}}function W(t,q){var r=q?"visible":"hidden";if(e&&C(t)){C(t).style.visibility=r}else{V("#"+t,"visibility:"+r)}}function g(s){var r=/[\\\"<>\.;]/;var q=r.exec(s)!=null;return q?encodeURIComponent(s):s}var D=function(){if(h.ie&&h.win){window.attachEvent("onunload",function(){var w=d.length;for(var v=0;v<w;v++){d[v][0].detachEvent(d[v][1],d[v][2])}var t=i.length;for(var u=0;u<t;u++){X(i[u])}for(var r in h){h[r]=null}h=null;for(var q in swfobject){swfobject[q]=null}swfobject=null})}}();return{registerObject:function(u,q,t){if(!h.w3cdom||!u||!q){return }var r={};r.id=u;r.swfVersion=q;r.expressInstall=t?t:false;N[N.length]=r;W(u,false)},getObjectById:function(v){var q=null;if(h.w3cdom){var t=C(v);if(t){var u=t.getElementsByTagName(Q)[0];if(!u||(u&&typeof t.SetVariable!=b)){q=t}else{if(typeof u.SetVariable!=b){q=u}}}}return q},embedSWF:function(x,AE,AB,AD,q,w,r,z,AC){if(!h.w3cdom||!x||!AE||!AB||!AD||!q){return }AB+="";AD+="";if(c(q)){W(AE,false);var AA={};if(AC&&typeof AC===Q){for(var v in AC){if(AC[v]!=Object.prototype[v]){AA[v]=AC[v]}}}AA.data=x;AA.width=AB;AA.height=AD;var y={};if(z&&typeof z===Q){for(var u in z){if(z[u]!=Object.prototype[u]){y[u]=z[u]}}}if(r&&typeof r===Q){for(var t in r){if(r[t]!=Object.prototype[t]){if(typeof y.flashvars!=b){y.flashvars+="&"+t+"="+r[t]}else{y.flashvars=t+"="+r[t]}}}}f(function(){U(AA,y,AE);if(AA.id==AE){W(AE,true)}})}else{if(w&&!A&&c("6.0.65")&&(h.win||h.mac)){A=true;W(AE,false);f(function(){var AF={};AF.id=AF.altContentId=AE;AF.width=AB;AF.height=AD;AF.expressInstall=w;k(AF)})}}},getFlashPlayerVersion:function(){return{major:h.pv[0],minor:h.pv[1],release:h.pv[2]}},hasFlashPlayerVersion:c,createSWF:function(t,r,q){if(h.w3cdom){return U(t,r,q)}else{return undefined}},removeSWF:function(q){if(h.w3cdom){X(q)}},createCSS:function(r,q){if(h.w3cdom){V(r,q)}},addDomLoadEvent:f,addLoadEvent:R,getQueryParamValue:function(v){var u=K.location.search||K.location.hash;if(v==null){return g(u)}if(u){var t=u.substring(1).split("&");for(var r=0;r<t.length;r++){if(t[r].substring(0,t[r].indexOf("="))==v){return g(t[r].substring((t[r].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(A&&M){var q=C(m);if(q){q.parentNode.replaceChild(M,q);if(l){W(l,true);if(h.ie&&h.win){M.style.display="block"}}M=null;l=null;A=false}}}}}();/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;/*
 * 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")}})})();/* Copyright (c) 2006 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * $LastChangedDate: 2007-12-20 09:02:08 -0600 (Thu, 20 Dec 2007) $
 * $Rev: 4265 $
 *
 * Version: 3.0
 * 
 * Requires: $ 1.2.2+
 */

(function($) {

$.event.special.mousewheel = {
	setup: function() {
		var handler = $.event.special.mousewheel.handler;
		
		// Fix pageX, pageY, clientX and clientY for mozilla
		if ($.browser.mozilla) {
			$(this).bind('mousemove.mousewheel', function(event){
				$.data(this, 'mwcursorposdata', {
					pageX: event.pageX,
					pageY: event.pageY,
					clientX: event.clientX,
					clientY: event.clientY
				});
			});
		}
		
		if (this.addEventListener) {
			this.addEventListener(($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
		} else {
			this.onmousewheel = handler;
		}
	},
	
	teardown: function() {
		var handler = $.event.special.mousewheel.handler;
		
		$(this).unbind('mousemove.mousewheel');
		
		if (this.removeEventListener) {
			this.removeEventListener(($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
		} else {
			this.onmousewheel = function(){};
		}
		$.removeData(this, 'mwcursorposdata');
	},
	
	handler: function(event) {
		var args = Array.prototype.slice.call( arguments, 1 );
		
		event = $.event.fix(event || window.event);
		// Get correct pageX, pageY, clientX and clientY for mozilla
		$.extend( event, $.data(this, 'mwcursorposdata') || {} );
		var delta = 0, returnValue = true;
		
		if (event.wheelDelta) {
			delta = event.wheelDelta / 120;
		}
		if (event.detail) {
			delta = -event.detail / 3;
		}
//		if ( $.browser.opera  ) delta = -event.wheelDelta;
		
		event.data  = event.data || {};
		event.type  = "mousewheel";
		
		// Add delta to the front of the arguments
		args.unshift(delta);
		// Add event to the front of the arguments
		args.unshift(event);

		return $.event.handle.apply(this, args);
	}
};

$.fn.extend({
	mousewheel: function(fn) {
		return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
	},
	
	unmousewheel: function(fn) {
		return this.unbind("mousewheel", fn);
	}
});

})(jQuery);
/* Copyright (c) 2006 Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * See http://kelvinluck.com/assets/jquery/jScrollPane/
 * $Id: jScrollPane.js 66 2009-03-15 01:18:07Z kelvin.luck $
 */

/**
 * Replace the vertical scroll bars on any matched elements with a fancy
 * styleable (via CSS) version. With JS disabled the elements will
 * gracefully degrade to the browsers own implementation of overflow:auto.
 * If the mousewheel plugin has been included on the page then the scrollable areas will also
 * respond to the mouse wheel.
 *
 * @example jQuery(".scroll-pane").jScrollPane();
 *
 * @name jScrollPane
 * @type jQuery
 * @param Object	settings	hash with options, described below.
 *								scrollbarWidth	-	The width of the generated scrollbar in pixels
 *								scrollbarMargin	-	The amount of space to leave on the side of the scrollbar in pixels
 *								wheelSpeed		-	The speed the pane will scroll in response to the mouse wheel in pixels
 *								showArrows		-	Whether to display arrows for the user to scroll with
 *								arrowSize		-	The height of the arrow buttons if showArrows=true
 *								animateTo		-	Whether to animate when calling scrollTo and scrollBy
 *								dragMinHeight	-	The minimum height to allow the drag bar to be
 *								dragMaxHeight	-	The maximum height to allow the drag bar to be
 *								animateInterval	-	The interval in milliseconds to update an animating scrollPane (default 100)
 *								animateStep		-	The amount to divide the remaining scroll distance by when animating (default 3)
 *								maintainPosition-	Whether you want the contents of the scroll pane to maintain it's position when you re-initialise it - so it doesn't scroll as you add more content (default true)
 *								scrollbarOnLeft	-	Display the scrollbar on the left side?  (needs stylesheet changes, see examples.html)
 *								reinitialiseOnImageLoad - Whether the jScrollPane should automatically re-initialise itself when any contained images are loaded
 * @return jQuery
 * @cat Plugins/jScrollPane
 * @author Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 */

(function($) {

$.jScrollPane = {
	active : []
};
$.fn.jScrollPane = function(settings)
{
	settings = $.extend({}, $.fn.jScrollPane.defaults, settings);

	var rf = function() { return false; };
	
	return this.each(
		function()
		{
			var $this = $(this);
			// Switch the element's overflow to hidden to ensure we get the size of the element without the scrollbars [http://plugins.jquery.com/node/1208]
			$this.css('overflow', 'hidden');
			var paneEle = this;
			
			if ($(this).parent().is('.jScrollPaneContainer')) {
				var currentScrollPosition = settings.maintainPosition ? $this.position().top : 0;
				var $c = $(this).parent();
				var paneWidth = $c.innerWidth();
				var paneHeight = $c.outerHeight();
				var trackHeight = paneHeight;
				$('>.jScrollPaneTrack, >.jScrollArrowUp, >.jScrollArrowDown', $c).remove();
				$this.css({'top':0});
			} else {
				var currentScrollPosition = 0;
				this.originalPadding = $this.css('paddingTop') + ' ' + $this.css('paddingRight') + ' ' + $this.css('paddingBottom') + ' ' + $this.css('paddingLeft');
				this.originalSidePaddingTotal = (parseInt($this.css('paddingLeft')) || 0) + (parseInt($this.css('paddingRight')) || 0);
				var paneWidth = $this.innerWidth();

            if (settings.fixedWidth > 0) {
              paneWidth = settings.fixedWidth;
            }
								
		        if (settings.ie6ScrollFix && /msie|MSIE 6/.test(navigator.userAgent)) {
		            paneWidth = paneWidth - 10;
		        }  

		        if (settings.fixedHeight > 0) {
		            var paneHeight = settings.fixedHeight;
		        } else {		        
  		        if ($this.parents('.module-content-container').size() > 0) {  		          
  		          // modules in content container will get a height up to 270px (2 grid rows)  		          
  		          $this.removeClass('module-listinnerfix');
  		          var actualHeight = $this.outerHeight(true);  	              	           
  	            var paneHeight = (actualHeight > 270) ? 270 : actualHeight;
  		        } else {  		        
        				/* Custom height calculation for teaser slots */
        				//var paneHeight = $this.innerHeight();				
        				var h = 0;				
        				$this.siblings().each(function() {
    				        h += $(this).outerHeight(true);
                });
        				
        				var p = $this;    				
        				// there has to be a parent element with either "module" or "modulefix" as class!
        				while (p.size() > 0 && !p.parent().hasClass('.module') && !p.parent().hasClass('.modulefix')) {
        				  p = p.parent();
        				}
        				
        				if (p.size() > 0 && p != $this) {
        				  p.siblings().each(function() {
            		      if(!$(this).hasClass('.ignorecalc')) {    					  
       					    h += $(this).outerHeight(true);
            			  }
                  });
        				}
        				var paneHeight = ($this.parents('.module,.modulefix').innerHeight() - h);
  		        }
		        }
				var trackHeight = paneHeight;
				$this.wrap(
					$('<div></div>').attr(
						{'className':'jScrollPaneContainer'}
					).css(
						{
							'height':paneHeight+'px', 
							'width':paneWidth+'px'
						}
					).attr(
						'tabindex', 
						settings.tabIndex
					)
				);
				// deal with text size changes (if the jquery.em plugin is included)
				// and re-initialise the scrollPane so the track maintains the
				// correct size
				$(document).bind(
					'emchange', 
					function(e, cur, prev)
					{
						$this.jScrollPane(settings);
					}
				);				
			}
			
			if (settings.reinitialiseOnImageLoad) {
				// code inspired by jquery.onImagesLoad: http://plugins.jquery.com/project/onImagesLoad
				// except we re-initialise the scroll pane when each image loads so that the scroll pane is always up to size...
				// TODO: Do I even need to store it in $.data? Is a local variable here the same since I don't pass the reinitialiseOnImageLoad when I re-initialise?
				var $imagesToLoad = $.data(paneEle, 'jScrollPaneImagesToLoad') || $('img', $this);
				var loadedImages = [];
				
				if ($imagesToLoad.length) {
					$imagesToLoad.each(function(i, val)	{
						$(this).bind('load readystatechange', function() {
							if($.inArray(i, loadedImages) == -1){ //don't double count images
								loadedImages.push(val); //keep a record of images we've seen
								$imagesToLoad = $.grep($imagesToLoad, function(n, i) {
									return n != val;
								});
								$.data(paneEle, 'jScrollPaneImagesToLoad', $imagesToLoad);
								var s2 = $.extend(settings, {reinitialiseOnImageLoad:false});
								$this.jScrollPane(s2); // re-initialise
							}
						}).each(function(i, val) {
							if(this.complete || this.complete===undefined) { 
								//needed for potential cached images
								this.src = this.src; 
							} 
						});
					});
				};
			}

			var p = this.originalSidePaddingTotal;
			var realPaneWidth = paneWidth - settings.scrollbarWidth - settings.scrollbarMargin - p;

			var cssToApply = {
				'height':'auto',
				'width': realPaneWidth + 'px'
			}

			if(settings.scrollbarOnLeft) {
				cssToApply.paddingLeft = settings.scrollbarMargin + settings.scrollbarWidth + 'px';
			} else {
				cssToApply.paddingRight = settings.scrollbarMargin + 'px';
			}

			$this.css(cssToApply);

			var contentHeight = $this.outerHeight();
			var percentInView = paneHeight / contentHeight;

			if (percentInView < .99) {
				var $container = $this.parent();
				$container.append(
					$('<div></div>').attr({'className':'jScrollPaneTrack'}).css({'width':settings.scrollbarWidth+'px'}).append(
						$('<div></div>').attr({'className':'jScrollPaneDrag'}).css({'width':settings.scrollbarWidth+'px'}).append(
							$('<div></div>').attr({'className':'jScrollPaneDragTop'}).css({'width':settings.scrollbarWidth+'px'}),
							$('<div></div>').attr({'className':'jScrollPaneDragBottom'}).css({'width':settings.scrollbarWidth+'px'})
						)
					)
				);
				
				var $track = $('>.jScrollPaneTrack', $container);
				var $drag = $('>.jScrollPaneTrack .jScrollPaneDrag', $container);
				
				
				var currentArrowDirection;
				var currentArrowTimerArr = [];// Array is used to store timers since they can stack up when dealing with keyboard events. This ensures all timers are cleaned up in the end, preventing an acceleration bug.
				var currentArrowInc;
				var whileArrowButtonDown = function() 
				{
					if (currentArrowInc > 4 || currentArrowInc % 4 == 0) {
						positionDrag(dragPosition + currentArrowDirection * mouseWheelMultiplier);
					}
					currentArrowInc++;
				};

				if (settings.enableKeyboardNavigation) {
					$container.bind(
						'keydown.jscrollpane',
						function(e) 
						{
							switch (e.keyCode) {
								case 38: //up
									currentArrowDirection = -1;
									currentArrowInc = 0;
									whileArrowButtonDown();
									currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
									return false;
								case 40: //down
									currentArrowDirection = 1;
									currentArrowInc = 0;
									whileArrowButtonDown();
									currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
									return false;
								case 33: // page up
								case 34: // page down
									// TODO
									return false;
								default:
							}
						}
					).bind(
						'keyup.jscrollpane',
						function(e) 
						{
							if (e.keyCode == 38 || e.keyCode == 40) {
								for (var i = 0; i < currentArrowTimerArr.length; i++) {
									clearInterval(currentArrowTimerArr[i]);
								}
								return false;
							}
						}
					);
				}

				if (settings.showArrows) {
					
					var currentArrowButton;
					var currentArrowInterval;

					var onArrowMouseUp = function(event)
					{
						$('html').unbind('mouseup', onArrowMouseUp);
						currentArrowButton.removeClass('jScrollActiveArrowButton');
						clearInterval(currentArrowInterval);
					};
					var onArrowMouseDown = function() {
						$('html').bind('mouseup', onArrowMouseUp);
						currentArrowButton.addClass('jScrollActiveArrowButton');
						currentArrowInc = 0;
						whileArrowButtonDown();
						currentArrowInterval = setInterval(whileArrowButtonDown, 100);
					};
					$container
						.append(
							$('<a></a>')
								.attr({'href':'javascript:;', 'className':'jScrollArrowUp', 'tabindex':-1})
								.css({'width':settings.scrollbarWidth+'px'})
								.html('Scroll up')
								.bind('mousedown', function()
								{
									currentArrowButton = $(this);
									currentArrowDirection = -1;
									onArrowMouseDown();
									this.blur();
									return false;
								})
								.bind('click', rf),
							$('<a></a>')
								.attr({'href':'javascript:;', 'className':'jScrollArrowDown', 'tabindex':-1})
								.css({'width':settings.scrollbarWidth+'px'})
								.html('Scroll down')
								.bind('mousedown', function()
								{
									currentArrowButton = $(this);
									currentArrowDirection = 1;
									onArrowMouseDown();
									this.blur();
									return false;
								})
								.bind('click', rf)
						);
					var $upArrow = $('>.jScrollArrowUp', $container);
					var $downArrow = $('>.jScrollArrowDown', $container);
					if (settings.arrowSize) {
						trackHeight = paneHeight - settings.arrowSize - settings.arrowSize;
						$track
							.css({'height': trackHeight+'px', top:settings.arrowSize+'px'})
					} else {
						var topArrowHeight = $upArrow.height();
						settings.arrowSize = topArrowHeight;
						trackHeight = paneHeight - topArrowHeight - $downArrow.height();
						$track
							.css({'height': trackHeight+'px', top:topArrowHeight+'px'})
					}
				}
				
				var $pane = $(this).css({'position':'absolute', 'overflow':'visible'});
				
				var currentOffset;
				var maxY;
				var mouseWheelMultiplier;
				// store this in a seperate variable so we can keep track more accurately than just updating the css property..
				var dragPosition = 0;
				var dragMiddle = percentInView*paneHeight/2;
				
				// pos function borrowed from tooltip plugin and adapted...
				var getPos = function (event, c) {
					var p = c == 'X' ? 'Left' : 'Top';
					return event['page' + c] || (event['client' + c] + (document.documentElement['scroll' + p] || document.body['scroll' + p])) || 0;
				};
				
				var ignoreNativeDrag = function() {	return false; };
				
				var initDrag = function()
				{
					ceaseAnimation();
					currentOffset = $drag.offset(false);
					currentOffset.top -= dragPosition;
					maxY = trackHeight - $drag[0].offsetHeight;
					mouseWheelMultiplier = 2 * settings.wheelSpeed * maxY / contentHeight;
				};
				
				var onStartDrag = function(event)
				{
					initDrag();
					dragMiddle = getPos(event, 'Y') - dragPosition - currentOffset.top;
					$('html').bind('mouseup', onStopDrag).bind('mousemove', updateScroll);
					if ($.browser.msie) {
						$('html').bind('dragstart', ignoreNativeDrag).bind('selectstart', ignoreNativeDrag);
					}
					return false;
				};
				var onStopDrag = function()
				{
					$('html').unbind('mouseup', onStopDrag).unbind('mousemove', updateScroll);
					dragMiddle = percentInView*paneHeight/2;
					if ($.browser.msie) {
						$('html').unbind('dragstart', ignoreNativeDrag).unbind('selectstart', ignoreNativeDrag);
					}
				};
				var positionDrag = function(destY)
				{
					destY = destY < 0 ? 0 : (destY > maxY ? maxY : destY);
					dragPosition = destY;
					$drag.css({'top':destY+'px'});
					var p = destY / maxY;
					$this.data('jScrollPanePosition', (paneHeight-contentHeight)*-p);
					$pane.css({'top':((paneHeight-contentHeight)*p) + 'px'});
					$this.trigger('scroll');
					if (settings.showArrows) {
						$upArrow[destY == 0 ? 'addClass' : 'removeClass']('disabled');
						$downArrow[destY == maxY ? 'addClass' : 'removeClass']('disabled');
					}
				};
				var updateScroll = function(e)
				{
					positionDrag(getPos(e, 'Y') - currentOffset.top - dragMiddle);
				};
				
				var dragH = Math.max(Math.min(percentInView*(paneHeight-settings.arrowSize*2), settings.dragMaxHeight), settings.dragMinHeight);
				
				$drag.css(
					{'height':dragH+'px'}
				).bind('mousedown', onStartDrag);
				
				var trackScrollInterval;
				var trackScrollInc;
				var trackScrollMousePos;
				var doTrackScroll = function()
				{
					if (trackScrollInc > 8 || trackScrollInc%4==0) {
						positionDrag((dragPosition - ((dragPosition - trackScrollMousePos) / 2)));
					}
					trackScrollInc ++;
				};
				var onStopTrackClick = function()
				{
					clearInterval(trackScrollInterval);
					$('html').unbind('mouseup', onStopTrackClick).unbind('mousemove', onTrackMouseMove);
				};
				var onTrackMouseMove = function(event)
				{
					trackScrollMousePos = getPos(event, 'Y') - currentOffset.top - dragMiddle;
				};
				var onTrackClick = function(event)
				{
					initDrag();
					onTrackMouseMove(event);
					trackScrollInc = 0;
					$('html').bind('mouseup', onStopTrackClick).bind('mousemove', onTrackMouseMove);
					trackScrollInterval = setInterval(doTrackScroll, 100);
					doTrackScroll();
					return false;
				};
				
				$track.bind('mousedown', onTrackClick);
				
				$container.bind(
					'mousewheel',
					function (event, delta) {
						initDrag();
						ceaseAnimation();
						var d = dragPosition;
						positionDrag(dragPosition - delta * mouseWheelMultiplier);
						var dragOccured = d != dragPosition;
						return !dragOccured;
					}
				);

				var _animateToPosition;
				var _animateToInterval;
				function animateToPosition()
				{
					var diff = (_animateToPosition - dragPosition) / settings.animateStep;
					if (diff > 1 || diff < -1) {
						positionDrag(dragPosition + diff);
					} else {
						positionDrag(_animateToPosition);
						ceaseAnimation();
					}
				}
				var ceaseAnimation = function()
				{
					if (_animateToInterval) {
						clearInterval(_animateToInterval);
						delete _animateToPosition;
					}
				};
				var scrollTo = function(pos, preventAni)
				{
					if (typeof pos == "string") {
						$e = $(pos, $this);
						if (!$e.length) return;
						pos = $e.offset().top - $this.offset().top;
					}
					$container.scrollTop(0);
					ceaseAnimation();
					var maxScroll = contentHeight - paneHeight;
					pos = pos > maxScroll ? maxScroll : pos;
					$this.data('jScrollPaneMaxScroll', maxScroll);
					var destDragPosition = pos/maxScroll * maxY;
					if (preventAni || !settings.animateTo) {
						positionDrag(destDragPosition);
					} else {
						_animateToPosition = destDragPosition;
						_animateToInterval = setInterval(animateToPosition, settings.animateInterval);
					}
				};
				$this[0].scrollTo = scrollTo;
				
				$this[0].scrollBy = function(delta)
				{
					var currentPos = -parseInt($pane.css('top')) || 0;
					scrollTo(currentPos + delta);
				};
				
				initDrag();
				
				scrollTo(-currentScrollPosition, true);
			
				// Deal with it when the user tabs to a link or form element within this scrollpane
				$('*', this).bind(
					'focus',
					function(event)
					{
						var $e = $(this);
						
						// loop through parents adding the offset top of any elements that are relatively positioned between
						// the focused element and the jScrollPaneContainer so we can get the true distance from the top
						// of the focused element to the top of the scrollpane...
						var eleTop = 0;
						
						while ($e[0] != $this[0]) {
							eleTop += $e.position().top;
							$e = $e.offsetParent();
						}
						
						var viewportTop = -parseInt($pane.css('top')) || 0;
						var maxVisibleEleTop = viewportTop + paneHeight;
						var eleInView = eleTop > viewportTop && eleTop < maxVisibleEleTop;
						if (!eleInView) {
							var destPos = eleTop - settings.scrollbarMargin;
							if (eleTop > viewportTop) { // element is below viewport - scroll so it is at bottom.
								destPos += $(this).height() + 15 + settings.scrollbarMargin - paneHeight;
							}
							scrollTo(destPos);
						}
					}
				)
				
				
				if (location.hash) {
					setTimeout(function() {scrollTo(location.hash);}, $.browser.safari ? 100 : 0);
				}
				
				// use event delegation to listen for all clicks on links and hijack them if they are links to
				// anchors within our content...
				$(document).bind(
					'click',
					function(e)
					{
						$target = $(e.target);
						if ($target.is('a')) {
							var h = $target.attr('href');
							if (h && h.substr(0, 1) == '#') {
								setTimeout(function() {scrollTo(h, !settings.animateToInternalLinks);}, $.browser.safari ? 100 : 0);
							}
						}
					}
				); 
				
				// Deal with dragging and selecting text to make the scrollpane scroll...
				function onSelectScrollMouseDown(e)
				{
				   $(document).bind('mousemove.jScrollPaneDragging', onTextSelectionScrollMouseMove);
				   $(document).bind('mouseup.jScrollPaneDragging',   onSelectScrollMouseUp);
				  
				}
				
				var textDragDistanceAway;
				var textSelectionInterval;
				
				function onTextSelectionInterval()
				{
					direction = textDragDistanceAway < 0 ? -1 : 1;
					$this[0].scrollBy(textDragDistanceAway / 2);
				}

				function clearTextSelectionInterval()
				{
					if (textSelectionInterval) {
						clearInterval(textSelectionInterval);
						textSelectionInterval = undefined;
					}
				}
				
				function onTextSelectionScrollMouseMove(e)
				{
					var offset = $this.parent().offset().top;
					var maxOffset = offset + paneHeight;
					var mouseOffset = getPos(e, 'Y');
					textDragDistanceAway = mouseOffset < offset ? mouseOffset - offset : (mouseOffset > maxOffset ? mouseOffset - maxOffset : 0);
					if (textDragDistanceAway == 0) {
						clearTextSelectionInterval();
					} else {
						if (!textSelectionInterval) {
							textSelectionInterval  = setInterval(onTextSelectionInterval, 100);
						}
					}
				}

				function onSelectScrollMouseUp(e)
				{
				   $(document)
					  .unbind('mousemove.jScrollPaneDragging')
					  .unbind('mouseup.jScrollPaneDragging');
				   clearTextSelectionInterval();
				}

				$container.bind('mousedown.jScrollPane', onSelectScrollMouseDown);

				
				$.jScrollPane.active.push($this[0]);
				
			} else {
				$this.css(
					{
						'height':paneHeight+'px',
						'width':paneWidth-this.originalSidePaddingTotal+'px',
						'padding':this.originalPadding
					}
				);
				// clean up listeners
				$this.parent().unbind('mousewheel').unbind('mousedown.jScrollPane').unbind('keydown.jscrollpane').unbind('keyup.jscrollpane');
			}
			
		}
	)
};

$.fn.jScrollPaneRemove = function()
{
	$(this).each(function()
	{
		$this = $(this);
		var $c = $this.parent();
		if ($c.is('.jScrollPaneContainer')) {
			$this.css(
				{
					'top':'',
					'height':'',
					'width':'',
					'padding':'',
					'overflow':'',
					'position':''
				}
			);
			$c.after($this).remove();
		}
	});
}

$.fn.jScrollPane.defaults = {
	scrollbarWidth : 10,
	scrollbarMargin : 5,
	wheelSpeed : 18,
	showArrows : false,
	arrowSize : 0,
	animateTo : false,
	dragMinHeight : 1,
	dragMaxHeight : 99999,
	animateInterval : 100,
	animateStep: 3,
	maintainPosition: true,
	scrollbarOnLeft: false,
	reinitialiseOnImageLoad: false,
	tabIndex : 0,
	enableKeyboardNavigation: true,
	animateToInternalLinks: false,
	ie6ScrollFix: false,
	fixedHeight: 0,
	fixedWidth: 0
};

// clean up the scrollTo expandos
$(window)
	.bind('unload', function() {
		var els = $.jScrollPane.active; 
		for (var i=0; i<els.length; i++) {
			els[i].scrollTo = els[i].scrollBy = null;
		}
	}
);

})(jQuery);
/*
 * jQuery UI 1.7
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
;jQuery.ui || (function($) {

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

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

	// $.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 Tabs 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Tabs
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.tabs", {

	_init: function() {
		if (this.options.deselectable !== undefined) {
			this.options.collapsible = this.options.deselectable;
		}
		this._tabify(true);
	},

	_setData: function(key, value) {
		if (key == 'selected') {
			if (this.options.collapsible && value == this.options.selected) {
				return;
			}
			this.select(value);
		}
		else {
			this.options[key] = value;
			if (key == 'deselectable') {
				this.options.collapsible = value;
			}
			this._tabify();
		}
	},

	_tabId: function(a) {
		return a.title && a.title.replace(/\s/g, '_').replace(/[^A-Za-z0-9\-_:\.]/g, '') ||
			this.options.idPrefix + $.data(a);
	},

	_sanitizeSelector: function(hash) {
		return hash.replace(/:/g, '\\:'); // we need this because an id may contain a ":"
	},

	_cookie: function() {
		var cookie = this.cookie || (this.cookie = this.options.cookie.name || 'ui-tabs-' + $.data(this.list[0]));
		return $.cookie.apply(null, [cookie].concat($.makeArray(arguments)));
	},

	_ui: function(tab, panel) {
		return {
			tab: tab,
			panel: panel,
			index: this.anchors.index(tab)
		};
	},

	_cleanup: function() {
		// restore all former loading tabs labels
		this.lis.filter('.ui-state-processing').removeClass('ui-state-processing')
				.find('span:data(label.tabs)')
				.each(function() {
					var el = $(this);
					el.html(el.data('label.tabs')).removeData('label.tabs');
				});
	},

	_tabify: function(init) {

		this.list = this.element.children('ul:first');
		this.lis = $('li:has(a[href])', this.list);
		this.anchors = this.lis.map(function() { return $('a', this)[0]; });
		this.panels = $([]);

		var self = this, o = this.options;

		var fragmentId = /^#.+/; // Safari 2 reports '#' for an empty hash
		this.anchors.each(function(i, a) {
			var href = $(a).attr('href');

			// For dynamically created HTML that contains a hash as href IE < 8 expands
			// such href to the full page url with hash and then misinterprets tab as ajax.
			// Same consideration applies for an added tab with a fragment identifier
			// since a[href=#fragment-identifier] does unexpectedly not match.
			// Thus normalize href attribute...
			var hrefBase = href.split('#')[0], baseEl;
			if (hrefBase && (hrefBase === location.toString().split('#')[0] ||
					(baseEl = $('base')[0]) && hrefBase === baseEl.href)) {
				href = a.hash;
				a.href = href;
			}

			// inline tab
			if (fragmentId.test(href)) {
				self.panels = self.panels.add(self._sanitizeSelector(href));
			}

			// remote tab
			else if (href != '#') { // prevent loading the page itself if href is just "#"
				$.data(a, 'href.tabs', href); // required for restore on destroy

				// TODO until #3808 is fixed strip fragment identifier from url
				// (IE fails to load from such url)
				$.data(a, 'load.tabs', href.replace(/#.*$/, '')); // mutable data

				var id = self._tabId(a);
				a.href = '#' + id;
				var $panel = $('#' + id);
				if (!$panel.length) {
					$panel = $(o.panelTemplate).attr('id', id).addClass('ui-tabs-panel ui-widget-content ui-corner-bottom')
						.insertAfter(self.panels[i - 1] || self.list);
					$panel.data('destroy.tabs', true);
				}
				self.panels = self.panels.add($panel);
			}

			// invalid tab href
			else {
				o.disabled.push(i);
			}
		});

		// initialization from scratch
		if (init) {

			// attach necessary classes for styling
			this.element.addClass('ui-tabs ui-widget ui-widget-content ui-corner-all');
			this.list.addClass('ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all');
			this.lis.addClass('ui-state-default ui-corner-top');
			this.panels.addClass('ui-tabs-panel ui-widget-content ui-corner-bottom');

			// Selected tab
			// use "selected" option or try to retrieve:
			// 1. from fragment identifier in url
			// 2. from cookie
			// 3. from selected class attribute on <li>
			if (o.selected === undefined) {
				if (location.hash) {
					this.anchors.each(function(i, a) {
						if (a.hash == location.hash) {
							o.selected = i;
							return false; // break
						}
					});
				}
				if (typeof o.selected != 'number' && o.cookie) {
					o.selected = parseInt(self._cookie(), 10);
				}
				if (typeof o.selected != 'number' && this.lis.filter('.ui-tabs-selected').length) {
					o.selected = this.lis.index(this.lis.filter('.ui-tabs-selected'));
				}
				o.selected = o.selected || 0;
			}
			else if (o.selected === null) { // usage of null is deprecated, TODO remove in next release
				o.selected = -1;
			}

			// sanity check - default to first tab...
			o.selected = ((o.selected >= 0 && this.anchors[o.selected]) || o.selected < 0) ? o.selected : 0;

			// Take disabling tabs via class attribute from HTML
			// into account and update option properly.
			// A selected tab cannot become disabled.
			o.disabled = $.unique(o.disabled.concat(
				$.map(this.lis.filter('.ui-state-disabled'),
					function(n, i) { return self.lis.index(n); } )
			)).sort();

			if ($.inArray(o.selected, o.disabled) != -1) {
				o.disabled.splice($.inArray(o.selected, o.disabled), 1);
			}

			// highlight selected tab
			this.panels.addClass('ui-tabs-hide');
			this.lis.removeClass('ui-tabs-selected ui-state-active');
			if (o.selected >= 0 && this.anchors.length) { // check for length avoids error when initializing empty list
				this.panels.eq(o.selected).removeClass('ui-tabs-hide');
				this.lis.eq(o.selected).addClass('ui-tabs-selected ui-state-active');

				// seems to be expected behavior that the show callback is fired
				self.element.queue("tabs", function() {
					self._trigger('show', null, self._ui(self.anchors[o.selected], self.panels[o.selected]));
				});
				
				this.load(o.selected);
			}

			// clean up to avoid memory leaks in certain versions of IE 6
			$(window).bind('unload', function() {
				self.lis.add(self.anchors).unbind('.tabs');
				self.lis = self.anchors = self.panels = null;
			});

		}
		// update selected after add/remove
		else {
			o.selected = this.lis.index(this.lis.filter('.ui-tabs-selected'));
		}

		// update collapsible
		this.element[o.collapsible ? 'addClass' : 'removeClass']('ui-tabs-collapsible');

		// set or update cookie after init and add/remove respectively
		if (o.cookie) {
			this._cookie(o.selected, o.cookie);
		}

		// disable tabs
		for (var i = 0, li; (li = this.lis[i]); i++) {
			$(li)[$.inArray(i, o.disabled) != -1 &&
				!$(li).hasClass('ui-tabs-selected') ? 'addClass' : 'removeClass']('ui-state-disabled');
		}

		// reset cache if switching from cached to not cached
		if (o.cache === false) {
			this.anchors.removeData('cache.tabs');
		}

		// remove all handlers before, tabify may run on existing tabs after add or option change
		this.lis.add(this.anchors).unbind('.tabs');

		if (o.event != 'mouseover') {
			var addState = function(state, el) {
				if (el.is(':not(.ui-state-disabled)')) {
					el.addClass('ui-state-' + state);
				}
			};
			var removeState = function(state, el) {
				el.removeClass('ui-state-' + state);
			};
			this.lis.bind('mouseover.tabs', function() {
				addState('hover', $(this));
			});
			this.lis.bind('mouseout.tabs', function() {
				removeState('hover', $(this));
			});
			this.anchors.bind('focus.tabs', function() {
				addState('focus', $(this).closest('li'));
			});
			this.anchors.bind('blur.tabs', function() {
				removeState('focus', $(this).closest('li'));
			});
		}

		// set up animations
		var hideFx, showFx;
		if (o.fx) {
			if ($.isArray(o.fx)) {
				hideFx = o.fx[0];
				showFx = o.fx[1];
			}
			else {
				hideFx = showFx = o.fx;
			}
		}

		// Reset certain styles left over from animation
		// and prevent IE's ClearType bug...
		function resetStyle($el, fx) {
			$el.css({ display: '' });
			if ($.browser.msie && fx.opacity) {
				$el[0].style.removeAttribute('filter');
			}
		}

		// Show a tab...
		var showTab = showFx ?
			function(clicked, $show) {
				$(clicked).closest('li').removeClass('ui-state-default').addClass('ui-tabs-selected ui-state-active');
				$show.hide().removeClass('ui-tabs-hide') // avoid flicker that way
					.animate(showFx, showFx.duration || 'normal', function() {
						resetStyle($show, showFx);
						self._trigger('show', null, self._ui(clicked, $show[0]));
					});
			} :
			function(clicked, $show) {
				$(clicked).closest('li').removeClass('ui-state-default').addClass('ui-tabs-selected ui-state-active');
				$show.removeClass('ui-tabs-hide');
				self._trigger('show', null, self._ui(clicked, $show[0]));
			};

		// Hide a tab, $show is optional...
		var hideTab = hideFx ?
			function(clicked, $hide) {
				$hide.animate(hideFx, hideFx.duration || 'normal', function() {
					self.lis.removeClass('ui-tabs-selected ui-state-active').addClass('ui-state-default');
					$hide.addClass('ui-tabs-hide');
					resetStyle($hide, hideFx);
					self.element.dequeue("tabs");
				});
			} :
			function(clicked, $hide, $show) {
				self.lis.removeClass('ui-tabs-selected ui-state-active').addClass('ui-state-default');
				$hide.addClass('ui-tabs-hide');
				self.element.dequeue("tabs");
			};

		// attach tab event handler, unbind to avoid duplicates from former tabifying...
		this.anchors.bind(o.event + '.tabs', function() {
			var el = this, $li = $(this).closest('li'), $hide = self.panels.filter(':not(.ui-tabs-hide)'),
					$show = $(self._sanitizeSelector(this.hash));

			// If tab is already selected and not collapsible or tab disabled or
			// or is already loading or click callback returns false stop here.
			// Check if click handler returns false last so that it is not executed
			// for a disabled or loading tab!
			if (($li.hasClass('ui-tabs-selected') && !o.collapsible) ||
				$li.hasClass('ui-state-disabled') ||
				$li.hasClass('ui-state-processing') ||
				self._trigger('select', null, self._ui(this, $show[0])) === false) {
				this.blur();
				return false;
			}

			o.selected = self.anchors.index(this);

			self.abort();

			// if tab may be closed
			if (o.collapsible) {
				if ($li.hasClass('ui-tabs-selected')) {
					o.selected = -1;

					if (o.cookie) {
						self._cookie(o.selected, o.cookie);
					}

					self.element.queue("tabs", function() {
						hideTab(el, $hide);
					}).dequeue("tabs");
					
					this.blur();
					return false;
				}
				else if (!$hide.length) {
					if (o.cookie) {
						self._cookie(o.selected, o.cookie);
					}
					
					self.element.queue("tabs", function() {
						showTab(el, $show);
					});

					self.load(self.anchors.index(this)); // TODO make passing in node possible, see also http://dev.jqueryui.com/ticket/3171
					
					this.blur();
					return false;
				}
			}

			if (o.cookie) {
				self._cookie(o.selected, o.cookie);
			}

			// show new tab
			if ($show.length) {
				if ($hide.length) {
					self.element.queue("tabs", function() {
						hideTab(el, $hide);
					});
				}
				self.element.queue("tabs", function() {
					showTab(el, $show);
				});
				
				self.load(self.anchors.index(this));
			}
			else {
				throw 'jQuery UI Tabs: Mismatching fragment identifier.';
			}

			// Prevent IE from keeping other link focussed when using the back button
			// and remove dotted border from clicked link. This is controlled via CSS
			// in modern browsers; blur() removes focus from address bar in Firefox
			// which can become a usability and annoying problem with tabs('rotate').
			if ($.browser.msie) {
				this.blur();
			}

		});

		// disable click in any case
		this.anchors.bind('click.tabs', function(){return false;});

	},

	destroy: function() {
		var o = this.options;

		this.abort();
		
		this.element.unbind('.tabs')
			.removeClass('ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible')
			.removeData('tabs');

		this.list.removeClass('ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all');

		this.anchors.each(function() {
			var href = $.data(this, 'href.tabs');
			if (href) {
				this.href = href;
			}
			var $this = $(this).unbind('.tabs');
			$.each(['href', 'load', 'cache'], function(i, prefix) {
				$this.removeData(prefix + '.tabs');
			});
		});

		this.lis.unbind('.tabs').add(this.panels).each(function() {
			if ($.data(this, 'destroy.tabs')) {
				$(this).remove();
			}
			else {
				$(this).removeClass([
					'ui-state-default',
					'ui-corner-top',
					'ui-tabs-selected',
					'ui-state-active',
					'ui-state-hover',
					'ui-state-focus',
					'ui-state-disabled',
					'ui-tabs-panel',
					'ui-widget-content',
					'ui-corner-bottom',
					'ui-tabs-hide'
				].join(' '));
			}
		});

		if (o.cookie) {
			this._cookie(null, o.cookie);
		}
	},

	add: function(url, label, index) {
		if (index === undefined) {
			index = this.anchors.length; // append by default
		}

		var self = this, o = this.options,
			$li = $(o.tabTemplate.replace(/#\{href\}/g, url).replace(/#\{label\}/g, label)),
			id = !url.indexOf('#') ? url.replace('#', '') : this._tabId($('a', $li)[0]);

		$li.addClass('ui-state-default ui-corner-top').data('destroy.tabs', true);

		// try to find an existing element before creating a new one
		var $panel = $('#' + id);
		if (!$panel.length) {
			$panel = $(o.panelTemplate).attr('id', id).data('destroy.tabs', true);
		}
		$panel.addClass('ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide');

		if (index >= this.lis.length) {
			$li.appendTo(this.list);
			$panel.appendTo(this.list[0].parentNode);
		}
		else {
			$li.insertBefore(this.lis[index]);
			$panel.insertBefore(this.panels[index]);
		}

		o.disabled = $.map(o.disabled,
			function(n, i) { return n >= index ? ++n : n; });

		this._tabify();

		if (this.anchors.length == 1) { // after tabify
			$li.addClass('ui-tabs-selected ui-state-active');
			$panel.removeClass('ui-tabs-hide');
			this.element.queue("tabs", function() {
				self._trigger('show', null, self._ui(self.anchors[0], self.panels[0]));
			});
				
			this.load(0);
		}

		// callback
		this._trigger('add', null, this._ui(this.anchors[index], this.panels[index]));
	},

	remove: function(index) {
		var o = this.options, $li = this.lis.eq(index).remove(),
			$panel = this.panels.eq(index).remove();

		// If selected tab was removed focus tab to the right or
		// in case the last tab was removed the tab to the left.
		if ($li.hasClass('ui-tabs-selected') && this.anchors.length > 1) {
			this.select(index + (index + 1 < this.anchors.length ? 1 : -1));
		}

		o.disabled = $.map($.grep(o.disabled, function(n, i) { return n != index; }),
			function(n, i) { return n >= index ? --n : n; });

		this._tabify();

		// callback
		this._trigger('remove', null, this._ui($li.find('a')[0], $panel[0]));
	},

	enable: function(index) {
		var o = this.options;
		if ($.inArray(index, o.disabled) == -1) {
			return;
		}

		this.lis.eq(index).removeClass('ui-state-disabled');
		o.disabled = $.grep(o.disabled, function(n, i) { return n != index; });

		// callback
		this._trigger('enable', null, this._ui(this.anchors[index], this.panels[index]));
	},

	disable: function(index) {
		var self = this, o = this.options;
		if (index != o.selected) { // cannot disable already selected tab
			this.lis.eq(index).addClass('ui-state-disabled');

			o.disabled.push(index);
			o.disabled.sort();

			// callback
			this._trigger('disable', null, this._ui(this.anchors[index], this.panels[index]));
		}
	},

	select: function(index) {
		if (typeof index == 'string') {
			index = this.anchors.index(this.anchors.filter('[href$=' + index + ']'));
		}
		else if (index === null) { // usage of null is deprecated, TODO remove in next release
			index = -1;
		}
		if (index == -1 && this.options.collapsible) {
			index = this.options.selected;
		}

		this.anchors.eq(index).trigger(this.options.event + '.tabs');
	},

	load: function(index) {
		var self = this, o = this.options, a = this.anchors.eq(index)[0], url = $.data(a, 'load.tabs');

		this.abort();

		// not remote or from cache
		if (!url || this.element.queue("tabs").length !== 0 && $.data(a, 'cache.tabs')) {
			this.element.dequeue("tabs");
			if (o.cachedLoadEvent) {
				self._trigger('load', null, self._ui(self.anchors[index], self.panels[index]));
			}
			return;
		}

		// load remote from here on
		this.lis.eq(index).addClass('ui-state-processing');

		if (o.spinner) {
			var span = $('span', a);
			span.data('label.tabs', span.html()).html(o.spinner);
		}

		this.xhr = $.ajax($.extend({}, o.ajaxOptions, {
			url: url,
			success: function(r, s) {
				$(self._sanitizeSelector(a.hash)).html(r);

				// take care of tab labels
				self._cleanup();

				if (o.cache) {
					$.data(a, 'cache.tabs', true); // if loaded once do not load them again
				}

				// callbacks
				self._trigger('load', null, self._ui(self.anchors[index], self.panels[index]));
				try {
					o.ajaxOptions.success(r, s);
				}
				catch (e) {}

			}
		}));
		
		// last, so that load event is fired before show...
		self.element.dequeue("tabs");
		return this;
	},

	abort: function() {
		// stop possibly running animations
		this.element.queue([]);
		this.panels.stop(false, true);

		// terminate pending requests from other tabs
		if (this.xhr) {
			this.xhr.abort();
			delete this.xhr;
		}

		// take care of tab labels
		this._cleanup();

	},

	url: function(index, url) {
		this.anchors.eq(index).removeData('cache.tabs').data('load.tabs', url);
	},

	length: function() {
		return this.anchors.length;
	}

});

$.extend($.ui.tabs, {
	version: '1.7.1',
	getter: 'length',
	defaults: {
		ajaxOptions: null,
		cache: false,
		cookie: null, // e.g. { expires: 7, path: '/', domain: 'jquery.com', secure: true }
		collapsible: false,
		disabled: [],
		event: 'click',
		fx: null, // e.g. { height: 'toggle', opacity: 'toggle', duration: 200 }
		idPrefix: 'ui-tabs-',
		panelTemplate: '<div></div>',
		spinner: '<em>Loading&#8230;</em>',
		tabTemplate: '<li><a href="#{href}"><span>#{label}</span></a></li>'
	}
});

/*
 * Tabs Extensions
 */

/*
 * Rotate
 */
$.extend($.ui.tabs.prototype, {
	rotation: null,
	rotate: function(ms, continuing) {

		var self = this, o = this.options;
		
		var rotate = self._rotate || (self._rotate = function(e) {
			clearTimeout(self.rotation);
			self.rotation = setTimeout(function() {
				var t = o.selected;
				self.select( ++t < self.anchors.length ? t : 0 );
			}, ms);
			
			if (e) {
				e.stopPropagation();
			}
		});
		
		var stop = self._unrotate || (self._unrotate = !continuing ?
			function(e) {
				if (e.clientX) { // in case of a true click
					self.rotate(null);
				}
			} :
			function(e) {
				t = o.selected;
				rotate();
			});

		// start rotation
		if (ms) {
			this.element.bind('tabsshow', rotate);
			this.anchors.bind(o.event + '.tabs', stop);
			rotate();
		}
		// stop rotation
		else {
			clearTimeout(self.rotation);
			this.element.unbind('tabsshow', rotate);
			this.anchors.unbind(o.event + '.tabs', stop);
			delete this._rotate;
			delete this._unrotate;
		}
	}
});

})(jQuery);

/**
 * Function to be called when the onclick event for a tab is generated.
 *
 * @param tabId the id of the tab element.
 * @param tabTitle the title of the tab.
 * @param event the onclick browser event.
 */
function onTabClick(tabId, tabTitle, adReloadTriggerObj, agofCode, event, pageTitle) {
  var tabElement = document.getElementById(tabId);
  if (tabElement != null) {
    tabElement.simTrackerMetainfo.title = tabTitle;
    tabElement.simTrackerMetainfo.agofCode = agofCode;
    simTracker.track(tabElement, event);
    adReloadTriggerObj.registerClick();
  }
}

$.fn.pager = function(clas, options) {
	
	var settings = {		
		navId: 'nav',
		navClass: 'pg-nav',
		navAttach: 'append',
		highlightClass: 'pg-highlight',
		prevText: 'Zur�ck',
		nextText: 'Weiter',
		linkText: null,		
		height: null,		
		type: 'default',
		showIndicator: false,
		pageSize: 1,
		startPage: 1,
		endPage: 1,
		numberPagerPadding: 3,
		showPrevNext: true,
		prevNextPosition: 'outer',
		overviewText : '�bersicht',
		overviewLink : '#',
		counterText : 'Seite ',
		counterSeparatorText: ' von ',
		alternatePagingClass: null,
		alternateCounterText: '',
		thumbImg: '/img/module/paging_thumb_overview.gif',
		thumbImg2: '/img/module/paging_thumb_normal.gif',
		ajax: 0,
		ajax_url: "",
		ajax_noLoadingClass: "",
		gallery_track: undefined,
		resetLastTrackedImageName: undefined
	};
	if (options) {
		$.extend(settings, options);
	}
	
	return this.each( function () {
		
		var me = $(this);
		var size;		
	  	var currentPage = 1;		
		var navid = '#'+settings.navId;		
		var items;
		var pages;		
		
		function init () {			
			$(me).find(clas).show();
			if (settings.alternatePagingClass) {
				$(me).find(settings.alternatePagingClass).hide();
			}
						
			items = $(clas, me).not(navid);		
			size = items.size();						
			pages = Math.ceil(size / settings.pageSize);			
			
			if(settings.height == null) {			
				settings.height = getHighest();
			}

			if(size > 1 || settings.alternatePagingClass) {
				makeNav();							
				goTo(settings.startPage);
			}			
			sizePanel();

			// switch between normal and alternate view
			if (settings.alternatePagingClass) {
				var thumbImageLink = $('.pg-thumb a');
				thumbImageLink.unbind('click');
			    thumbImageLink.click(function() {
				var altclass = settings.alternatePagingClass;				
				settings.alternatePagingClass = clas;								
				var thumb = settings.thumbImg;				
				settings.thumbImg = settings.thumbImg2;
				settings.thumbImg2 = thumb;
				
                // set alternate Counter-Text (used in image-gallery)
                if (settings.alternateCounterText != '') {
                    var altCounterText = settings.alternateCounterText;
                    $('.pg-counter').text(settings.alternateCounterText);
                    settings.alternateCounterText = settings.counterText;
                    settings.counterText = altCounterText;
                    if (altCounterText == 'Seite ') {
                    	var additions = {description : '', copyright: ''};
                    	switchDescription(additions);
                    }
                    else {
                    	if (settings.additions) {
                    	  switchDescription(settings.additions[0]);
                    	}
                    }
                }				
                settings.startPage = 1;
				$(navid).remove();				
				$('#' + me.attr('id')).pager(altclass, settings);
				
				if (settings.resetLastTrackedImageName) {
				  // set last tracked image name to first one, because the thumb-nail button
				  // toggles always to first image in image gallery
				  settings.resetLastTrackedImageName($('.pic-thumbview a').attr("imageName"));
				}
				
				return false;
			  });
              var thumbLinks = $('.pic-thumbview a');
              thumbLinks.unbind(('click'));
			  thumbLinks.bind('click',function() {
				  
				  var classIdx = $(this).attr("class");

					var altclass = settings.alternatePagingClass;				
					settings.alternatePagingClass = clas;								
					var thumb = settings.thumbImg;				
					settings.thumbImg = settings.thumbImg2;
					settings.thumbImg2 = thumb;

	                // set alternate Counter-Text (used in image-gallery)
	                if (settings.alternateCounterText != '') {
	                    var altCounterText = settings.alternateCounterText;
	                    $('.pg-counter').text(settings.alternateCounterText);
	                    settings.alternateCounterText = settings.counterText;
	                    settings.counterText = altCounterText;                  
	                }				
					
					$(navid).remove();
					
					settings.startPage = classIdx.replace('img', '')*1 + 1;
					
					$('#' + me.attr('id')).pager(altclass, settings);
					
					if (settings.additions) {
					  switchDescription(settings.additions[settings.startPage-1]);
					}
					
					if (settings.resetLastTrackedImageName) {
					  settings.resetLastTrackedImageName($(this).attr("imageName"));
					}
					return false;
			  });
			}
		}
				
		
		/*
		* Previous- / Next-Link + separate Pagenumber Links
		*/
		function numberPager () {			
			var str = makePrevLink();						
			
			var begin = (currentPage - settings.numberPagerPadding) > 0 ? currentPage - settings.numberPagerPadding : 0;
            var end = (currentPage + settings.numberPagerPadding) < pages ? currentPage + settings.numberPagerPadding : pages;
 
    	    if (currentPage - settings.numberPagerPadding > 0) {
                str += '<a href="#" class="pg-link" rel="1">';
                str += (settings.linkText == null) ? 1 : settings.linkText[0];
                str += '</a> ... ';
    	    }						
			for(var i = begin; i < end; i++) {
				var j = i+1;
				str += '<a href="#" class="pg-link" rel="'+j+'">';
				str += (settings.linkText == null) ? j : settings.linkText[j-1];				
				str += '</a>';
			}								
			if(currentPage + settings.numberPagerPadding < pages) {
			    str += '... <a href="#" class="pg-link" rel="'+pages+'">';
			    str += (settings.linkText == null) ? pages : settings.linkText[pages-1];
			    str += '</a>';
			}
			
			str += makeNextLink();
			return str;
		}
		
		/*
		 * NumberPager with images instead of numbers
		 */
		
		 function numberpicturePager () {
				if (pages <= 1) return "";
		   
		    var str = makePrevLink();						
				
				var begin = (currentPage - settings.numberpicturePagerPadding) > 0 ? currentPage - settings.numberpicturePagerPadding : 0;
	      var end = (currentPage + settings.numberpicturePagerPadding) < pages ? currentPage + settings.numberpicturePagerPadding : pages;
	 
	      if (currentPage - settings.numberpicturePagerPadding > 0) {	    	
	        str += '<a href="#" class="pg-link-picture" rel="1">';
	        str += '<img src="'+settings.thumbImg+'" name="pagerpicture"/>';
	        str += '</a>';
	    	}						
				for(var i = begin; i < end; i++) {
					var j = i+1;
					str += '<a href="#" class="pg-link-picture" rel="'+j+'">';
					str += '<img src="'+settings.thumbImg+'" name="pagerpicture"/>';	
					str += '</a>';
				}								
				if(currentPage + settings.numberpicturePagerPadding < pages) {
				  str += '... <a href="#" class="pg-link-picture" rel="'+pages+'">';
				  str += '<img src="'+settings.thumbImg+'" name="pagerpicture"/>';
				  str += '</a>';
				}
				
				str += makeNextLink();
				return str;
		}
		
		/* 
		* Previous- / Next-Link
		*/
		function defaultPager() {			
			var str = makePrevLink();
			str += makeNextLink();
			return str;
		}

		/* 
		* Previous- / Next-Link + Overview-Link
		*/		
		function linkPager() {
			var str = makePrevLink();
			str += '<a href="' + settings.overviewLink + '" class="pg-overview">'+settings.overviewText+'</a>';
			str += makeNextLink();
			return str;
		}

		/* 
		* Previous- / Next-Link + Page x of y
		*/		
		function counterPager() {
			var str = makePrevLink();			
			str += '<span class="pg-counter">' + settings.counterText + '</span>';
			str += '<span class="pg-pagecurrent">' + currentPage + '</span>';			
			str += settings.counterSeparatorText;
			str += '<span class="pg-pagemax">' + pages + '</span>';						
			str += makeNextLink();
			return str;
		}
		
		
		function makePrevLink() {
			var str = '';			
			if (settings.showPrevNext) {
				var cssclass = '';
				switch (settings.prevNextPosition) {
					case 'inner':
						str = '<div class="pg-middle"><a href="#" class="pg-prev" rel="prev">'+settings.prevText+'</a>';														
						break;
					default:
						str = '<a href="#" class="pg-prev outer-left" rel="prev">'+settings.prevText+'</a><div class="pg-middle">';						
						break;
				}	
			}
			return str;
		}
		
		
		function makeNextLink() {
			var str = '';			
			if (settings.showPrevNext) {
				var cssclass = '';
				switch (settings.prevNextPosition) {
					case 'inner':
						str = '<a href="#" class="pg-next" rel="next">'+settings.nextText+'</a></div>';										
						break;
					default:
						str = '</div><a href="#" class="pg-next outer-right" rel="next">'+settings.nextText+'</a>';		
						break;
				}	
			}
			return str;
		}
		
		
		function makeNav () {			
			var pager = '<div id="'+settings.navId+'" class="'+settings.navClass+'">';		
			if (settings.showIndicator) {
				pager += '<div class="pg-indicator"><img id="' + settings.navId + '_ind" src="/img/module/paging_indicator.gif" /></div>';
			}
			switch (settings.type) {		
				case 'link':
					pager += linkPager();
					break;
				case 'counter':
					pager += counterPager();
					break;
				case 'number':
					//pager += numberPager();
					break;
				case 'numberpicture':
					//needs new function
					break;	
				default:
					pager += defaultPager();
					break;
			}
			
			if (settings.prevNextPosition == 'inner' && settings.alternatePagingClass) {
				pager += '<div class="pg-thumb"><a href="#"><img src="' + settings.thumbImg + '"/></a></div>';
			}
			pager += '</div>';
		
			switch (settings.navAttach) {		
				case 'before':
					$(me).before(pager);
					break;
				case 'after':		
					$(me).after(pager);
					break;
				case 'prepend':
					$(me).prepend(pager);
					break;
				default:
					$(me).append(pager);
					break;
			}
			
			
			$(me).find(".pg-prev").click(function(event){
				goPrev();
				callGalleryTrack(event);
				return false;
			});
			$(me).find(".pg-next").click(function(event){
				goNext();
				callGalleryTrack(event);
				return false;
			});
			$(me).find(".pg-link").click(function(){				
				goTo(parseInt($(this).attr('rel'), 10));
				return false;
			});	
			checkDisableNavLinks();
		}
		
		
		function checkDisableNavLinks() {
			return;
			/* function disabled */
			
			/*
			if (currentPage == 1) {
				// disable "Previous"-Link
				$(me).find(".pg-prev").hide();
			} else {
			    $(me).find(".pg-prev").show();
			}
			
			if (currentPage == pages) {
				// disable "Next"-Link
				$(me).find(".pg-next").hide();
			} else {
				$(me).find(".pg-next").show();
			}
			*/			
		}
		
		function addUrlParameter(url, param, value) {
			if (url.lastIndexOf('?') >= 0) {
				url = url + "&";
			}
			else {
				url = url + "?";
			}
	
			url = url + param + "=" + value;
			
			return url;
		}
		
		function goTo(page) {			
			var start = (page-1) * settings.pageSize;
			
			if (start < 0 || start >= size) {
				return;
			}
			// hide all items
			items.hide();
			
			//ajax loading section
			if (settings.ajax == 1 && start != 0 && ((start-settings.endPage)!=0) ) {
				// estimate loading items by using only the wanted ones (not ajax_noLoadingClass)
				var loadingItems = items.slice(start, (start+settings.pageSize)).not(settings.ajax_noLoadingClass);
				// find the children child
				var child = loadingItems.children().children();
				// fill with the desired image
				if ($("img", child).size() == 0) {
				  child.load(addUrlParameter(settings.ajax_url, "image", (page-1)));
				}
        //do preloading for smoother paging
        if (((start-settings.endPage) < -1)) { 
          var preloadingItems = items.slice((start+1), (start+settings.pageSize+1)).not(settings.ajax_noLoadingClass);
          var preloadChild = preloadingItems.children().children();
          if ($("img", preloadChild).size() == 0) {
            preloadChild.load(addUrlParameter(settings.ajax_url, "image", page));
          }
        } 								
			}
			
			// show desired page
			items.slice(start, (start+settings.pageSize)).show();	
			
			currentPage = page;

	        if (settings.type == 'number') {	          
	            updateNumberPager();
	        }
	        
	        if (settings.type == 'numberpicture') {	          
	            updateNumberPicturePager();
	        }
			
			$(me).find(".pg-pagecurrent").text(currentPage);									
			updateIndicator();		
			highlight();
			checkDisableNavLinks();
			

		}
		

    function callGalleryTrack(event) {
      if (settings.gallery_track) {
        settings.gallery_track(event);
      }
    }

    function goPrev() {
      if (settings.additions) {
        if (currentPage > 1) {
          switchDescription(settings.additions[currentPage - 2]);
        }

      } else if (settings.galleryAdditions) {
        if (currentPage > 1) {
          var galleryIndex = (currentPage - 2) * 6;

          for (var i = galleryIndex; i < galleryIndex + 6 && i < settings.galleryAdditions.length; i++) {
            switchGalleryDescription(settings.galleryAdditions[i], i);
          }
        }
      }
      goTo(currentPage - 1);
    }


    function goNext() {
      if (settings.additions) {
        if (settings.additions.length > currentPage) {
          switchDescription(settings.additions[currentPage]);
        } else {
          var additions = {description : '', copyright: ''};
          switchDescription(additions);
        }
      } else if (settings.galleryAdditions) {
        var galleryIndex = currentPage * 6;

        for (var i = galleryIndex; i < galleryIndex + 6 && i < settings.galleryAdditions.length; i++) {
            switchGalleryDescription(settings.galleryAdditions[i], i);
        }
      }
      goTo(currentPage + 1);
    }


    function switchDescription(additions) {
      if (additions && (additions.copyright.length > 0) && (settings.alternateCounterText == 'Seite ')) {
        $('.unit > .text .copyright').html("&copy; " + additions.copyright);
      } else {
        $('.unit > .text .copyright').html("&nbsp;");
      }
      if (additions && (additions.description.length > 0) && (settings.alternateCounterText == 'Seite ')) {
        $('.unit > .text p').html(additions.description);
      } else {
        if (settings.alternateCounterText == 'Bild ') {
          $('.unit > .text p').html(settings.galleryDescription);
        } else {
          $('.unit > .text p').html("&nbsp;");
        }
      }
    }

    function switchGalleryDescription(additions, index) {
      var copyrightArray = $('.unit > .text .copyright');
      var descriptionArray = $('.unit > .text p');

      if (copyrightArray && copyrightArray.length > 0 && copyrightArray.length > index + 1) {
        if (additions && additions.copyright.length > 0 && settings.alternateCounterText == 'Seite ') {
          $(copyrightArray[index]).html("&copy; " + additions.copyright);
        } else {
          $(copyrightArray[index]).html("&nbsp;");
        }
      }

      if (descriptionArray && descriptionArray.length > 0 && descriptionArray.length > index + 1) {
        if (additions && additions.description.length > 0 && settings.alternateCounterText == 'Seite ') {
          $(descriptionArray[index]).html(additions.description);
        } else {
          if (settings.alternateCounterText == 'Bild ') {
            $(descriptionArray[index]).html(settings.galleryDescription);
          } else {
            $(descriptionArray[index]).html("&nbsp;");
          }
        }
      }
    }


    function updateNumberPager() {
        $(me).find('.pg-nav').html(numberPager());

            $(me).find(".pg-prev").click(function(event){
              
              goPrev();
              callGalleryTrack(event);
              return false;
            });
            $(me).find(".pg-next").click(function(event){
              
                goNext();
                callGalleryTrack(event);
                return false;
            });
            $(me).find(".pg-link").click(function(){                
                goTo(parseInt($(this).attr('rel'), 10));
                return false;
            }); 
		}
		
		function updateIndicator() {
			if (!settings.showIndicator) {
				return;
			}						
			var progress = Math.ceil(currentPage/pages * 100);			
			$(me).find('#' + settings.navId + '_ind').css('width', progress + '%');						
		}
		

		function highlight () {			
			$(me).find(navid).find('a.pg-link').removeClass(settings.highlightClass);
			var show;
			if (settings.type == 'number') {
			  show = $(me).find(navid).find('a.pg-link[rel=' + currentPage + ']');   
			} else {
			  show = $(me).find(navid).find('a.pg-link').get(currentPage-1);
			}			
			$(show).addClass(settings.highlightClass);			
		}
		
		function highlightpicture () {			
			//$(me).find(navid).find('a.pg-link-picture').removeClass(settings.highlightClass);
			
			$(me).find(navid).find('a.pg-link-picture img').attr('src', settings.thumbImg);
			
			var show = $(me).find(navid).find('a.pg-link-picture[rel=' + currentPage + ']');   
			$('img', show).attr('src', settings.thumbImg2);
			
			//$(show).addClass(settings.highlightClass);	
			//$(show).images['pagerpicture'].src=settings.thumbImg2;
		}

		
		function sizePanel () {
			var pagingarea = $(me).find(".paging");
			if($.browser.msie && $.browser.version == "6.0") {
				pagingarea.css('height', settings.height);				
			} else {
				pagingarea.css('minHeight', settings.height);								
			}
		}
		
		
		function getHighest () {			
			var highest = 0;			
			for (var i = 0; i < pages; i++) {
				var pageheight = 0;			
				var start = i * settings.pageSize;
				items.slice(start, (start+settings.pageSize)).each( function () {
					pageheight += this.offsetHeight;
				});
				if(pageheight > highest) {
					highest = pageheight;
				}
			}			
			highest = highest + "px";
			return highest;			
		}
		
		
		function getNavHeight () {
			var nav = $(navid).get(0);
			return nav.offsetHeight;
		}
		
		/* 
		 * Neuer Fall "Numberpager mit Bildern
		 */
		
		function updateNumberPicturePager() {		    
			    $(me).find('.pg-nav').html(numberpicturePager());

	            $(me).find(".pg-prev").click(function(event){
                goPrev();
                callGalleryTrack(event);
                return false;
	            });
	            $(me).find(".pg-next").click(function(event){
                goNext();
                callGalleryTrack(event);
                return false;
	            });
	            $(me).find(".pg-link-picture").click(function(){                
	                goTo(parseInt($(this).attr('rel'), 10));
	                return false;
	            }); 
	            $(me).find(".pg-pagecurrent").text(currentPage);									
				updateIndicator();		
				highlightpicture();
				checkDisableNavLinks();
				return false;
		}
		
         
		
		/*
		* Init Pager
		*/
		init();
		
	});	
};/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};function redrawSelectBoxesByParent(parent) {
    $(".ddn-container, .ddn", parent).remove();
    var $selectBoxes = $("[selectzor='1']");
    for (var i = 0; i < $selectBoxes.length; i++) {
        var ddl = $selectBoxes.get(i);
        var selText = ddl.selectedIndex != null && ddl.selectedIndex >= 0 ? ddl.options[ddl.selectedIndex].text : "";
        var div = "<div class='ddn ddn-selector' parent='" + ddl.id + "' id='div_" + ddl.id +
                          "'>" + selText + "</div><div id='div_" + ddl.id + "_Container' class='ddn-container'>";
        /* set this var o = 0 and you get the first (descriptional) option-value on the optionslist again */
        for (var o = 0; ddl.options[o]; o++) {
            div += "<div index='" + o + "' class='ddn-item' parent='" + ddl.id + "'>" + ddl.options[o].text + "</div>";
        }
        div += "</div>";
        $("#" + ddl.id, parent).after(div);
        $("#" + ddl.id, parent).css("display", "none");
    }
    $(".ddn-container", parent).hide();
    $(".ddn-selector", parent).click(function(e) {
        var id = $(this).attr("id");
        var $container = $("#" + id + "_Container", parent);
        if (!$container.css("display") || $container.css("display") == "none") { 
			$container.slideDown();
		} else {
			$container.slideUp();
		}
        e.preventDefault();
    });
    $(".ddn-item", parent).click(function() {
        var $this = $(this);
        var $parentId = $this.attr("parent");
        var $parent = $("#" + $parentId, parent);
        $parent[0].selectedIndex = $(this).attr("index");
        $("#div_" + $parentId, parent).text($(this).text());
        $("#div_" + $parentId, parent).trigger('click');
        if ($parent[0].attributes["onchange"]) {
			eval($parent[0].attributes["onchange"].value);
		}
    });
    $(".ddn-item", parent).hover(function() {
      $(".ddn-item", parent).removeClass('ddn-item-hover');
      $(this).addClass("ddn-item-hover");
    },
    function() {                       
        $(".ddn-item", parent).removeClass("ddn-item-hover");
    });
}

/* For Selectboxes with onchange-event and relocation */
/* This is the first change, just take this Javascript-Function, if you need to reload the page with
 * a new url
 */
function redrawSelectBoxesByParent2(parent) {
    $(".ddn-container, .ddn", parent).remove();
    /* this is Nr. 2 of the 3 changes: for this "branch" just set the selectzor-value on 2 */
    var $selectBoxes = $("[selectzor='2']");
    for (var i = 0; i < $selectBoxes.length; i++) {
        var ddl = $selectBoxes.get(i);
        var selText = ddl.selectedIndex != null && ddl.selectedIndex >= 0 ? ddl.options[ddl.selectedIndex].text : "";
        var div = "<div class='ddn ddn-selector' parent='" + ddl.id + "' id='div_" + ddl.id +
                          "'>" + selText + "</div><div id='div_" + ddl.id + "_Container' class='ddn-container'>";
        /* set this var o = 0 and you get the first (descriptional) option-value on the optionslist again */
        for (var o = 1; ddl.options[o]; o++) {
            div += "<div index='" + o + "' class='ddn-item' parent='" + ddl.id + "'>" + ddl.options[o].text + "</div>";
        }
        div += "</div>";
        $("#" + ddl.id, parent).after(div);
        $("#" + ddl.id, parent).css("display", "none");
    }
    $(".ddn-container", parent).hide();
    $(".ddn-selector", parent).click(function(e) {
        var id = $(this).attr("id");
        var $container = $("#" + id + "_Container", parent);
        if (!$container.css("display") || $container.css("display") == "none") { 
			$container.slideDown();
		} else {
			$container.slideUp();
		}
        e.preventDefault();
    });
    $(".ddn-item", parent).click(function() {
        var $this = $(this);
        var $parentId = $this.attr("parent");
        var $parent = $("#" + $parentId, parent);
        $parent[0].selectedIndex = $(this).attr("index");
        $("#div_" + $parentId, parent).text($(this).text());
        $("#div_" + $parentId, parent).trigger('click');
        if ($parent[0].attributes["onchange"]) {
			/* this is the last of the 3 changes. remove the eval-function and set this on the value */
			window.location.href = ddl.options[ddl.selectedIndex].value;
		}
    });
    $(".ddn-item", parent).hover(function() {
        $(".ddn-item", parent).removeClass('ddn-item-hover');
        $(this).addClass("ddn-item-hover");
    },
    function() {                       
        $(".ddn-item", parent).removeClass("ddn-item-hover");
    });
}
$.fn.broadcast = function() {
  //hide broadcast flyout
  $("a.close").click(function() {   
    var show = $("#menu").find('a#sendungen'); 
    $(".broadcast-flyout").hide();
    $(show).removeClass('aktiv'); 
    return false;
  });

  //set position for broadcast flyout
  $('.broadcast-flyout').css({
      'display' : 'none',
      'left' : '16px'
  });

  //hide listview and show rasterview
  $("a.raster-open").click(function() {   
    $(".list").hide();
    $(".raster").show();
    $(".switch-list-open").hide();
    $(".switch-list-close").show();
    $(".switch-raster-open").show();
    $(".switch-raster-close").hide();    
    return false;
  }); 
  //show listview and hide rasterview
  $("a.list-open").click(function() {   
    $(".list").show();
    $(".raster").hide();
    $(".switch-list-open").show();
    $(".switch-list-close").hide();
    $(".switch-raster-open").hide();
    $(".switch-raster-close").show();        
    return false;
  }); 
  
   //show recently and hide highlights and a-z
  $("a.recently").click(function() {   
    $(".contenta-z").hide();
    $(".contentrecently").show();
    $(".contenthighlights").hide();
    $(".horizontala-z").hide();
    $(".horizontalrecently").show();
    $(".horizontalhighlights").hide();    
    return false;
  }); 
   //show highlights and hide recently and a-z
  $("a.highlights").click(function() {   
    $(".contenta-z").hide();
    $(".contentrecently").hide();
    $(".contenthighlights").show();
    $(".horizontala-z").hide();
    $(".horizontalrecently").hide();
    $(".horizontalhighlights").show();    
    return false;
  });  
  //show a-z and hide recently and highlights
  $("a.a-z").click(function() {   
    $(".contenta-z").show();
    $(".contentrecently").hide();
    $(".contenthighlights").hide();
    $(".horizontala-z").show();
    $(".horizontalrecently").hide();
    $(".horizontalhighlights").hide();
    return false;
  });  
  
  $("#contentHighlights").ajaxStop(function() {
	  //window.console.log("Rollover");
	  //show rollover on mouseover
	  $("div.thumb").mouseover(function() {  
	    $("div:first",this).show();
	    //$(this).("border").show();
	    return false;
	  });
	  $("div.thumb").mouseout(function() {   
	    $("div:first",this).hide();
	    return false;  
	  }); 
  });
};

function doBoadcastFlyoutHighlightsPaging() {
	$('#pagingbox45678').pager('.page', {
        navId: 'paging45678',          
        prevText: '&lt; Zurück ',
        nextText: 'Weiter &gt;',    
        counterText: '',
        counterSeparatorText: '...',
        showPrevNext: false,   
        pageSize: 1,
        type: 'numberpicture',
        showIndicator: false,
        prevNextPosition: 'outer',
        alternatePagingClass: ".page2",
        thumbImg: '/img/broadcast/icon_paging.gif',
        thumbImg2: '/img/broadcast/icon_paging_active.gif'         
   });
	
	$('#pagingbox45679').pager('.page', {
        navId: 'paging45679',          
        prevText: '&lt; Zurück ',
        nextText: 'Weiter &gt;',    
        counterText: '',
        counterSeparatorText: '...',
        showPrevNext: false,   
        pageSize: 1,
        type: 'numberpicture',
        showIndicator: false,
        prevNextPosition: 'outer',
        alternatePagingClass: ".page2",
        thumbImg: '/img/broadcast/icon_paging.gif',
        thumbImg2: '/img/broadcast/icon_paging_active.gif'          
   });
}

function doBoadcastFlyoutAtoZPaging() {
	$('#pagingbox_raster_38971').pager('.page', {
        navId: 'paging_raster_38971',          
        prevText: '&lt; Zurück ',
        nextText: 'Weiter &gt;',    
        counterText: '',
        counterSeparatorText: '...',
        showPrevNext: false,   
        pageSize: 1,
        type: 'numberpicture',
        showIndicator: false,
        prevNextPosition: 'outer',
        alternatePagingClass: ".page2",
        thumbImg: '/img/broadcast/icon_paging.gif',
        thumbImg2: '/img/broadcast/icon_paging_active.gif'          
   });
	$('#pagingbox_list_38972').pager('.page', {
        navId: 'paging_list_38972',          
        prevText: '&lt; Zurück ',
        nextText: 'Weiter &gt;',    
        counterText: '',
        counterSeparatorText: '...',
        showPrevNext: false,   
        pageSize: 1,
        type: 'numberpicture',
        showIndicator: false,
        prevNextPosition: 'outer',
        alternatePagingClass: ".page2",
        thumbImg: '/img/broadcast/icon_paging.gif',
        thumbImg2: '/img/broadcast/icon_paging_active.gif'         
   });
}

function doBoadcastFlyoutRecentlyPaging() {
	$('#pagingbox45683').pager('.page', {
		navId : 'paging45683',
		prevText : '&lt; Zurück ',
		nextText : 'Weiter &gt;',
		counterText : '',
		counterSeparatorText : '...',
		showPrevNext : false,
		pageSize : 1,
		type : 'numberpicture',
		showIndicator : false,
		prevNextPosition : 'outer',
		alternatePagingClass : ".page2",
		thumbImg : '/img/broadcast/icon_paging.gif',
		thumbImg2 : '/img/broadcast/icon_paging_active.gif'
	});
	$('#pagingbox45681').pager('.page', {
		navId : 'paging45681',
		prevText : '&lt; Zurück ',
		nextText : 'Weiter &gt;',
		counterText : '',
		counterSeparatorText : '...',
		showPrevNext : false,
		pageSize : 1,
		type : 'numberpicture',
		showIndicator : false,
		prevNextPosition : 'outer',
		alternatePagingClass : ".page2",
		thumbImg : '/img/broadcast/icon_paging.gif',
		thumbImg2 : '/img/broadcast/icon_paging_active.gif'
	});
}/*
 * jQuery UI Datepicker 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Datepicker
 *
 * Depends:
 *	ui.core.js
 */

(function($) { // hide the namespace

$.extend($.ui, { datepicker: { version: "1.7.1" } });

var PROP_NAME = 'datepicker';

/* Date picker manager.
   Use the singleton instance of this class, $.datepicker, to interact with the date picker.
   Settings for (groups of) date pickers are maintained in an instance object,
   allowing multiple different settings on the same page. */

function Datepicker() {
	this.debug = false; // Change this to true to start debugging
	this._curInst = null; // The current instance in use
	this._keyEvent = false; // If the last event was a key event
	this._disabledInputs = []; // List of date picker inputs that have been disabled
	this._datepickerShowing = false; // True if the popup picker is showing , false if not
	this._inDialog = false; // True if showing within a "dialog", false if not
	this._mainDivId = 'ui-datepicker-div'; // The ID of the main datepicker division
	this._inlineClass = 'ui-datepicker-inline'; // The name of the inline marker class
	this._appendClass = 'ui-datepicker-append'; // The name of the append marker class
	this._triggerClass = 'ui-datepicker-trigger'; // The name of the trigger marker class
	this._dialogClass = 'ui-datepicker-dialog'; // The name of the dialog marker class
	this._disableClass = 'ui-datepicker-disabled'; // The name of the disabled covering marker class
	this._unselectableClass = 'ui-datepicker-unselectable'; // The name of the unselectable cell marker class
	this._currentClass = 'ui-datepicker-current-day'; // The name of the current day marker class
	this._dayOverClass = 'ui-datepicker-days-cell-over'; // The name of the day hover marker class
	this.regional = []; // Available regional settings, indexed by language code
	this.regional[''] = { // Default regional settings
		closeText: 'Done', // Display text for close link
		prevText: 'Prev', // Display text for previous month link
		nextText: 'Next', // Display text for next month link
		currentText: 'Today', // Display text for current month link
		monthNames: ['January','February','March','April','May','June',
			'July','August','September','October','November','December'], // Names of months for drop-down and formatting
		monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting
		dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting
		dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting
		dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'], // Column headings for days starting at Sunday
		dateFormat: 'mm/dd/yy', // See format options on parseDate
		firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
		isRTL: false // True if right-to-left language, false if left-to-right
	};
	this._defaults = { // Global defaults for all the date picker instances
		showOn: 'focus', // 'focus' for popup on focus,
			// 'button' for trigger button, or 'both' for either
		showAnim: 'show', // Name of jQuery animation for popup
		showOptions: {}, // Options for enhanced animations
		defaultDate: null, // Used when field is blank: actual date,
			// +/-number for offset from today, null for today
		appendText: '', // Display text following the input box, e.g. showing the format
		buttonText: '...', // Text for trigger button
		buttonImage: '', // URL for trigger button image
		buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
		hideIfNoPrevNext: false, // True to hide next/previous month links
			// if not applicable, false to just disable them
		navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
		gotoCurrent: false, // True if today link goes back to current selection instead
		changeMonth: false, // True if month can be selected directly, false if only prev/next
		changeYear: false, // True if year can be selected directly, false if only prev/next
		showMonthAfterYear: false, // True if the year select precedes month, false for month then year
		yearRange: '-10:+10', // Range of years to display in drop-down,
			// either relative to current year (-nn:+nn) or absolute (nnnn:nnnn)
		showOtherMonths: false, // True to show dates in other months, false to leave blank
		calculateWeek: this.iso8601Week, // How to calculate the week of the year,
			// takes a Date and returns the number of the week for it
		shortYearCutoff: '+10', // Short year values < this are in the current century,
			// > this are in the previous century,
			// string value starting with '+' for current year + value
		minDate: null, // The earliest selectable date, or null for no limit
		maxDate: null, // The latest selectable date, or null for no limit
		duration: 'normal', // Duration of display/closure
		beforeShowDay: null, // Function that takes a date and returns an array with
			// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '',
			// [2] = cell title (optional), e.g. $.datepicker.noWeekends
		beforeShow: null, // Function that takes an input field and
			// returns a set of custom settings for the date picker
		onSelect: null, // Define a callback function when a date is selected
		onChangeMonthYear: null, // Define a callback function when the month or year is changed
		onClose: null, // Define a callback function when the datepicker is closed
		numberOfMonths: 1, // Number of months to show at a time
		showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
		stepMonths: 1, // Number of months to step back/forward
		stepBigMonths: 12, // Number of months to step back/forward for the big links
		altField: '', // Selector for an alternate field to store selected dates into
		altFormat: '', // The date format to use for the alternate field
		constrainInput: true, // The input is constrained by the current date format
		showButtonPanel: false, // True to show button panel, false to not show it
		positionTop: -1, // Custom Positioning
		positionLeft: -1, // Custom Positioning
		additionalTop: 0, // Custom Positioning
		additionalLeft: 0, // Custom Positioning
		closeIcon: '' // URL for Custom Close-Icon
	};
	$.extend(this._defaults, this.regional['']);
	this.dpDiv = $('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible"></div>');
}

$.extend(Datepicker.prototype, {
	/* Class name added to elements to indicate already configured with a date picker. */
	markerClassName: 'hasDatepicker',

	/* Debug logging (if enabled). */
	log: function () {
		if (this.debug)
			console.log.apply('', arguments);
	},

	/* Override the default settings for all instances of the date picker.
	   @param  settings  object - the new settings to use as defaults (anonymous object)
	   @return the manager object */
	setDefaults: function(settings) {
		extendRemove(this._defaults, settings || {});
		return this;
	},

	/* Attach the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span
	   @param  settings  object - the new settings to use for this date picker instance (anonymous) */
	_attachDatepicker: function(target, settings) {
		// check for settings on the control itself - in namespace 'date:'
		var inlineSettings = null;
		for (var attrName in this._defaults) {
			var attrValue = target.getAttribute('date:' + attrName);
			if (attrValue) {
				inlineSettings = inlineSettings || {};
				try {
					inlineSettings[attrName] = eval(attrValue);
				} catch (err) {
					inlineSettings[attrName] = attrValue;
				}
			}
		}
		var nodeName = target.nodeName.toLowerCase();
		var inline = (nodeName == 'div' || nodeName == 'span');
		if (!target.id)
			target.id = 'dp' + (++this.uuid);
		var inst = this._newInst($(target), inline);
		inst.settings = $.extend({}, settings || {}, inlineSettings || {});		
		if (nodeName == 'input') {
			this._connectDatepicker(target, inst);
		} else if (inline) {
			this._inlineDatepicker(target, inst);
		}
	},

	/* Create a new instance object. */
	_newInst: function(target, inline) {
		var id = target[0].id.replace(/([:\[\]\.])/g, '\\\\$1'); // escape jQuery meta chars
		return {id: id, input: target, // associated target
			selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
			drawMonth: 0, drawYear: 0, // month being drawn
			inline: inline, // is datepicker inline or not
			dpDiv: (!inline ? this.dpDiv : // presentation div
			$('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))};
	},

	/* Attach the date picker to an input field. */
	_connectDatepicker: function(target, inst) {
		var input = $(target);		
		inst.trigger = $([]);
		if (input.hasClass(this.markerClassName))			
		    return;
		var appendText = this._get(inst, 'appendText');
		var isRTL = this._get(inst, 'isRTL');
		if (appendText)
			input[isRTL ? 'before' : 'after']('<span class="' + this._appendClass + '">' + appendText + '</span>');
		var showOn = this._get(inst, 'showOn');		  
		if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field		    
		  input.focus(this._showDatepicker).click(this._showDatepicker);
		  //input.focus(this._showDatepicker);
		    /*//input.click(this._showDatepicker);
		    input.click(function(){
	              if ($.datepicker._datepickerShowing && $.datepicker._lastInput == target) {	                
	                $.datepicker._hideDatepicker();
	              } else {	                
	                $.datepicker._showDatepicker(target);
	              }
	              return false;
		    });*/
		if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked
			var buttonText = this._get(inst, 'buttonText');
			var buttonImage = this._get(inst, 'buttonImage');
			inst.trigger = $(this._get(inst, 'buttonImageOnly') ?
				$('<img/>').addClass(this._triggerClass).
					attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
				$('<button type="button"></button>').addClass(this._triggerClass).
					html(buttonImage == '' ? buttonText : $('<img/>').attr(
					{ src:buttonImage, alt:buttonText, title:buttonText })));
			input[isRTL ? 'before' : 'after'](inst.trigger);
			inst.trigger.click(function() {
				if ($.datepicker._datepickerShowing && $.datepicker._lastInput == target)
					$.datepicker._hideDatepicker();
				else
					$.datepicker._showDatepicker(target);
				return false;
			});
		}
		input.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).
			bind("setData.datepicker", function(event, key, value) {
				inst.settings[key] = value;
			}).bind("getData.datepicker", function(event, key) {
				return this._get(inst, key);
			});
		$.data(target, PROP_NAME, inst);
	},

	/* Attach an inline date picker to a div. */
	_inlineDatepicker: function(target, inst) {
		var divSpan = $(target);
		if (divSpan.hasClass(this.markerClassName))
			return;
		divSpan.addClass(this.markerClassName).append(inst.dpDiv).
			bind("setData.datepicker", function(event, key, value){
				inst.settings[key] = value;
			}).bind("getData.datepicker", function(event, key){
				return this._get(inst, key);
			});
		$.data(target, PROP_NAME, inst);
		this._setDate(inst, this._getDefaultDate(inst));
		this._updateDatepicker(inst);
		this._updateAlternate(inst);
	},

	/* Pop-up the date picker in a "dialog" box.
	   @param  input     element - ignored
	   @param  dateText  string - the initial date to display (in the current format)
	   @param  onSelect  function - the function(dateText) to call when a date is selected
	   @param  settings  object - update the dialog date picker instance's settings (anonymous object)
	   @param  pos       int[2] - coordinates for the dialog's position within the screen or
	                     event - with x/y coordinates or
	                     leave empty for default (screen centre)
	   @return the manager object */
	_dialogDatepicker: function(input, dateText, onSelect, settings, pos) {
		var inst = this._dialogInst; // internal instance
		if (!inst) {
			var id = 'dp' + (++this.uuid);
			this._dialogInput = $('<input type="text" id="' + id +
				'" size="1" style="position: absolute; top: -100px;"/>');
			this._dialogInput.keydown(this._doKeyDown);
			$('body').append(this._dialogInput);
			inst = this._dialogInst = this._newInst(this._dialogInput, false);
			inst.settings = {};
			$.data(this._dialogInput[0], PROP_NAME, inst);
		}
		extendRemove(inst.settings, settings || {});
		this._dialogInput.val(dateText);

		this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
		if (!this._pos) {
			var browserWidth = window.innerWidth || document.documentElement.clientWidth ||	document.body.clientWidth;
			var browserHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
			var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
			var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
			this._pos = // should use actual width/height below
				[(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
		}

		// move input on screen for focus, but hidden behind dialog
		this._dialogInput.css('left', this._pos[0] + 'px').css('top', this._pos[1] + 'px');
		inst.settings.onSelect = onSelect;
		this._inDialog = true;
		this.dpDiv.addClass(this._dialogClass);
		this._showDatepicker(this._dialogInput[0]);
		if ($.blockUI)
			$.blockUI(this.dpDiv);
		$.data(this._dialogInput[0], PROP_NAME, inst);
		return this;
	},

	/* Detach a datepicker from its control.
	   @param  target    element - the target input field or division or span */
	_destroyDatepicker: function(target) {
		var $target = $(target);
		var inst = $.data(target, PROP_NAME);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		$.removeData(target, PROP_NAME);
		if (nodeName == 'input') {
			inst.trigger.remove();
			$target.siblings('.' + this._appendClass).remove().end().
				removeClass(this.markerClassName).
				unbind('focus', this._showDatepicker).
				unbind('keydown', this._doKeyDown).
				unbind('keypress', this._doKeyPress);
		} else if (nodeName == 'div' || nodeName == 'span')
			$target.removeClass(this.markerClassName).empty();
	},

	/* Enable the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span */
	_enableDatepicker: function(target) {
		var $target = $(target);
		var inst = $.data(target, PROP_NAME);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		if (nodeName == 'input') {
		target.disabled = false;
			inst.trigger.filter("button").
			each(function() { this.disabled = false; }).end().
				filter("img").
				css({opacity: '1.0', cursor: ''});
		}
		else if (nodeName == 'div' || nodeName == 'span') {
			var inline = $target.children('.' + this._inlineClass);
			inline.children().removeClass('ui-state-disabled');
		}
		this._disabledInputs = $.map(this._disabledInputs,
			function(value) { return (value == target ? null : value); }); // delete entry
	},

	/* Disable the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span */
	_disableDatepicker: function(target) {
		var $target = $(target);
		var inst = $.data(target, PROP_NAME);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		if (nodeName == 'input') {
		target.disabled = true;
			inst.trigger.filter("button").
			each(function() { this.disabled = true; }).end().
				filter("img").
				css({opacity: '0.5', cursor: 'default'});
		}
		else if (nodeName == 'div' || nodeName == 'span') {
			var inline = $target.children('.' + this._inlineClass);
			inline.children().addClass('ui-state-disabled');
		}
		this._disabledInputs = $.map(this._disabledInputs,
			function(value) { return (value == target ? null : value); }); // delete entry
		this._disabledInputs[this._disabledInputs.length] = target;
	},

	/* Is the first field in a jQuery collection disabled as a datepicker?
	   @param  target    element - the target input field or division or span
	   @return boolean - true if disabled, false if enabled */
	_isDisabledDatepicker: function(target) {
		if (!target) {
			return false;
		}
		for (var i = 0; i < this._disabledInputs.length; i++) {
			if (this._disabledInputs[i] == target)
				return true;
		}
		return false;
	},

	/* Retrieve the instance data for the target control.
	   @param  target  element - the target input field or division or span
	   @return  object - the associated instance data
	   @throws  error if a jQuery problem getting data */
	_getInst: function(target) {
		try {
			return $.data(target, PROP_NAME);
		}
		catch (err) {
			throw 'Missing instance data for this datepicker';
		}
	},

	/* Update the settings for a date picker attached to an input field or division.
	   @param  target  element - the target input field or division or span
	   @param  name    object - the new settings to update or
	                   string - the name of the setting to change or
	   @param  value   any - the new value for the setting (omit if above is an object) */
	_optionDatepicker: function(target, name, value) {
		var settings = name || {};
		if (typeof name == 'string') {
			settings = {};
			settings[name] = value;
		}
		var inst = this._getInst(target);
		if (inst) {
			if (this._curInst == inst) {
				this._hideDatepicker(null);
			}
			extendRemove(inst.settings, settings);
			var date = new Date();
			extendRemove(inst, {rangeStart: null, // start of range
				endDay: null, endMonth: null, endYear: null, // end of range
				selectedDay: date.getDate(), selectedMonth: date.getMonth(),
				selectedYear: date.getFullYear(), // starting point
				currentDay: date.getDate(), currentMonth: date.getMonth(),
				currentYear: date.getFullYear(), // current selection
				drawMonth: date.getMonth(), drawYear: date.getFullYear()}); // month being drawn
			this._updateDatepicker(inst);
		}
	},

	// change method deprecated
	_changeDatepicker: function(target, name, value) {
		this._optionDatepicker(target, name, value);
	},

	/* Redraw the date picker attached to an input field or division.
	   @param  target  element - the target input field or division or span */
	_refreshDatepicker: function(target) {
		var inst = this._getInst(target);
		if (inst) {
			this._updateDatepicker(inst);
		}
	},

	/* Set the dates for a jQuery selection.
	   @param  target   element - the target input field or division or span
	   @param  date     Date - the new date
	   @param  endDate  Date - the new end date for a range (optional) */
	_setDateDatepicker: function(target, date, endDate) {
		var inst = this._getInst(target);
		if (inst) {
			this._setDate(inst, date, endDate);
			this._updateDatepicker(inst);
			this._updateAlternate(inst);
		}
	},

	/* Get the date(s) for the first entry in a jQuery selection.
	   @param  target  element - the target input field or division or span
	   @return Date - the current date or
	           Date[2] - the current dates for a range */
	_getDateDatepicker: function(target) {
		var inst = this._getInst(target);
		if (inst && !inst.inline)
			this._setDateFromField(inst);
		return (inst ? this._getDate(inst) : null);
	},

	/* Handle keystrokes. */
	_doKeyDown: function(event) {
		var inst = $.datepicker._getInst(event.target);
		var handled = true;
		var isRTL = inst.dpDiv.is('.ui-datepicker-rtl');
		inst._keyEvent = true;
		if ($.datepicker._datepickerShowing)
			switch (event.keyCode) {
				case 9:  $.datepicker._hideDatepicker(null, '');
						break; // hide on tab out
				case 13: var sel = $('td.' + $.datepicker._dayOverClass +
							', td.' + $.datepicker._currentClass, inst.dpDiv);
						if (sel[0])
							$.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
						else
							$.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration'));
						return false; // don't submit the form
						break; // select the value on enter
				case 27: $.datepicker._hideDatepicker(null, $.datepicker._get(inst, 'duration'));
						break; // hide on escape
				case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
							-$.datepicker._get(inst, 'stepBigMonths') :
							-$.datepicker._get(inst, 'stepMonths')), 'M');
						break; // previous month/year on page up/+ ctrl
				case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
							+$.datepicker._get(inst, 'stepBigMonths') :
							+$.datepicker._get(inst, 'stepMonths')), 'M');
						break; // next month/year on page down/+ ctrl
				case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target);
						handled = event.ctrlKey || event.metaKey;
						break; // clear on ctrl or command +end
				case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target);
						handled = event.ctrlKey || event.metaKey;
						break; // current on ctrl or command +home
				case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D');
						handled = event.ctrlKey || event.metaKey;
						// -1 day on ctrl or command +left
						if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
									-$.datepicker._get(inst, 'stepBigMonths') :
									-$.datepicker._get(inst, 'stepMonths')), 'M');
						// next month/year on alt +left on Mac
						break;
				case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D');
						handled = event.ctrlKey || event.metaKey;
						break; // -1 week on ctrl or command +up
				case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D');
						handled = event.ctrlKey || event.metaKey;
						// +1 day on ctrl or command +right
						if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
									+$.datepicker._get(inst, 'stepBigMonths') :
									+$.datepicker._get(inst, 'stepMonths')), 'M');
						// next month/year on alt +right
						break;
				case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D');
						handled = event.ctrlKey || event.metaKey;
						break; // +1 week on ctrl or command +down
				default: handled = false;
			}
		else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home
			$.datepicker._showDatepicker(this);
		else {
			handled = false;
		}
		if (handled) {
			event.preventDefault();
			event.stopPropagation();
		}
	},

	/* Filter entered characters - based on date format. */
	_doKeyPress: function(event) {
		var inst = $.datepicker._getInst(event.target);
		if ($.datepicker._get(inst, 'constrainInput')) {
			var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat'));
			var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode);
			return event.ctrlKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1);
		}
	},

	/* Pop-up the date picker for a given input field.
	   @param  input  element - the input field attached to the date picker or
	                  event - if triggered by focus */
	_showDatepicker: function(input) {
		input = input.target || input;
		if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger			
		    input = $('input', input.parentNode)[0];
		if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here
			return;
		var inst = $.datepicker._getInst(input);
		var beforeShow = $.datepicker._get(inst, 'beforeShow');
		extendRemove(inst.settings, (beforeShow ? beforeShow.apply(input, [input, inst]) : {}));
		$.datepicker._hideDatepicker(null, '');
		$.datepicker._lastInput = input;
		$.datepicker._setDateFromField(inst);
		if ($.datepicker._inDialog) // hide cursor
			input.value = '';
		if (!$.datepicker._pos) { // position below input
			$.datepicker._pos = $.datepicker._findPos(input);
			$.datepicker._pos[1] += input.offsetHeight; // add the height
		}
		var isFixed = false;
		$(input).parents().each(function() {
			isFixed |= $(this).css('position') == 'fixed';
			return !isFixed;
		});
		if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled
			$.datepicker._pos[0] -= document.documentElement.scrollLeft;
			$.datepicker._pos[1] -= document.documentElement.scrollTop;
		}
		var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
		$.datepicker._pos = null;
		inst.rangeStart = null;
		// determine sizing offscreen
		inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'});
		$.datepicker._updateDatepicker(inst);
		// fix width for dynamic number of date pickers
		// and adjust position before showing
		offset = $.datepicker._checkOffset(inst, offset, isFixed);
	
		var positionTop = $.datepicker._get(inst, 'positionTop');
		var positionLeft = $.datepicker._get(inst, 'positionLeft');
        var top = (positionTop != -1) ? positionTop : offset.top;
        var left = (positionLeft != -1) ? positionLeft : offset.left;		
        top += $.datepicker._get(inst, 'additionalTop');
        left += $.datepicker._get(inst, 'additionalLeft');
        
		inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
			'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none',
			left: left + 'px', top: top + 'px'});			
		    
		
		
		if (!inst.inline) {
			var showAnim = $.datepicker._get(inst, 'showAnim') || 'show';
			var duration = $.datepicker._get(inst, 'duration');
			var postProcess = function() {
				$.datepicker._datepickerShowing = true;
				if ($.browser.msie && parseInt($.browser.version,10) < 7) // fix IE < 7 select problems
					$('iframe.ui-datepicker-cover').css({width: inst.dpDiv.width() + 4,
						height: inst.dpDiv.height() + 4});
			};
			if ($.effects && $.effects[showAnim])
				inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess);
			else
				inst.dpDiv[showAnim](duration, postProcess);
			if (duration == '')
				postProcess();
			if (inst.input[0].type != 'hidden')
				inst.input[0].focus();
			$.datepicker._curInst = inst;
		}
	},

	/* Generate the date picker content. */
	_updateDatepicker: function(inst) {
		var dims = {width: inst.dpDiv.width() + 4,
			height: inst.dpDiv.height() + 4};
		var self = this;
		inst.dpDiv.empty().append(this._generateHTML(inst))
			.find('iframe.ui-datepicker-cover').
				css({width: dims.width, height: dims.height})
			.end()
			.find('button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a')
				.bind('mouseout', function(){
					$(this).removeClass('ui-state-hover');
					if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).removeClass('ui-datepicker-prev-hover');
					if(this.className.indexOf('ui-datepicker-next') != -1) $(this).removeClass('ui-datepicker-next-hover');
				})
				.bind('mouseover', function(){
					if (!self._isDisabledDatepicker( inst.inline ? inst.dpDiv.parent()[0] : inst.input[0])) {
						$(this).parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover');
						$(this).addClass('ui-state-hover');
						if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).addClass('ui-datepicker-prev-hover');
						if(this.className.indexOf('ui-datepicker-next') != -1) $(this).addClass('ui-datepicker-next-hover');
					}
				})
			.end()
			.find('.' + this._dayOverClass + ' a')
				.trigger('mouseover')
			.end();
		var numMonths = this._getNumberOfMonths(inst);
		var cols = numMonths[1];
		var width = 17;
		if (cols > 1) {
			inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', (width * cols) + 'em');
		} else {
			inst.dpDiv.removeClass('ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4').width('');
		}
		inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') +
			'Class']('ui-datepicker-multi');
		inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') +
			'Class']('ui-datepicker-rtl');
		if (inst.input && inst.input[0].type != 'hidden' && inst == $.datepicker._curInst)
			$(inst.input[0]).focus();
	},

	/* Check positioning to remain on screen. */
	_checkOffset: function(inst, offset, isFixed) {
		var dpWidth = inst.dpDiv.outerWidth();
		var dpHeight = inst.dpDiv.outerHeight();
		var inputWidth = inst.input ? inst.input.outerWidth() : 0;
		var inputHeight = inst.input ? inst.input.outerHeight() : 0;
		var viewWidth = (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) + $(document).scrollLeft();
		var viewHeight = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight) + $(document).scrollTop();

		offset.left -= (this._get(inst, 'isRTL') ? (dpWidth - inputWidth) : 0);
		offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0;
		offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;

		// now check if datepicker is showing outside window viewport - move to a better place if so.
		offset.left -= (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0;
		offset.top -= (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(offset.top + dpHeight + inputHeight*2 - viewHeight) : 0;

		return offset;
	},

	/* Find an object's position on the screen. */
	_findPos: function(obj) {
        while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) {
            obj = obj.nextSibling;
        }
        var position = $(obj).offset();
	    return [position.left, position.top];
	},

	/* Hide the date picker from view.
	   @param  input  element - the input field attached to the date picker
	   @param  duration  string - the duration over which to close the date picker */
	_hideDatepicker: function(input, duration) {
		var inst = this._curInst;
		if (!inst || (input && inst != $.data(input, PROP_NAME)))
			return;
		if (inst.stayOpen)
			this._selectDate('#' + inst.id, this._formatDate(inst,
				inst.currentDay, inst.currentMonth, inst.currentYear));
		inst.stayOpen = false;
		if (this._datepickerShowing) {
			duration = (duration != null ? duration : this._get(inst, 'duration'));
			var showAnim = this._get(inst, 'showAnim');
			var postProcess = function() {
				$.datepicker._tidyDialog(inst);
			};
			if (duration != '' && $.effects && $.effects[showAnim])
				inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'),
					duration, postProcess);
			else
				inst.dpDiv[(duration == '' ? 'hide' : (showAnim == 'slideDown' ? 'slideUp' :
					(showAnim == 'fadeIn' ? 'fadeOut' : 'hide')))](duration, postProcess);
			if (duration == '')
				this._tidyDialog(inst);
			var onClose = this._get(inst, 'onClose');
			if (onClose)
				onClose.apply((inst.input ? inst.input[0] : null),
					[(inst.input ? inst.input.val() : ''), inst]);  // trigger custom callback
			this._datepickerShowing = false;
			this._lastInput = null;
			if (this._inDialog) {
				this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' });
				if ($.blockUI) {
					$.unblockUI();
					$('body').append(this.dpDiv);
				}
			}
			this._inDialog = false;
		}
		this._curInst = null;
	},

	/* Tidy up after a dialog display. */
	_tidyDialog: function(inst) {
		inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar');
	},

	/* Close date picker if clicked elsewhere. */
	_checkExternalClick: function(event) {	  
	  var $target = $(event.target);
	  if (!$.datepicker._curInst) {	      
	    // additional logic to hide Selectzor-Divs	    
	    $(".ddn-container").not($(event.target)).not($(event.target).parents('.ddn-container')).hide();	        
		  return;			
	  }	
	     
		if ($target.hasClass('ui-datepicker-closeicon') || ($target.parents('#' + $.datepicker._mainDivId).length == 0) &&
				!$target.hasClass($.datepicker.markerClassName) &&
				!$target.hasClass($.datepicker._triggerClass) &&
				$.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI))			
		  $.datepicker._hideDatepicker(null, '');
	},

	/* Adjust one of the date sub-fields. */
	_adjustDate: function(id, offset, period) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (this._isDisabledDatepicker(target[0])) {
			return;
		}
		this._adjustInstDate(inst, offset +
			(period == 'M' ? this._get(inst, 'showCurrentAtPos') : 0), // undo positioning
			period);
		this._updateDatepicker(inst);
	},

	/* Action for current link. */
	_gotoToday: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (this._get(inst, 'gotoCurrent') && inst.currentDay) {
			inst.selectedDay = inst.currentDay;
			inst.drawMonth = inst.selectedMonth = inst.currentMonth;
			inst.drawYear = inst.selectedYear = inst.currentYear;
		}
		else {
		var date = new Date();
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		}
		this._notifyChange(inst);
		this._adjustDate(target);
	},

	/* Action for selecting a new month/year. */
	_selectMonthYear: function(id, select, period) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		inst._selectingMonthYear = false;
		inst['selected' + (period == 'M' ? 'Month' : 'Year')] =
		inst['draw' + (period == 'M' ? 'Month' : 'Year')] =
			parseInt(select.options[select.selectedIndex].value,10);
		this._notifyChange(inst);
		this._adjustDate(target);
	},

	/* Restore input focus after not changing month/year. */
	_clickMonthYear: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (inst.input && inst._selectingMonthYear && !$.browser.msie)
			inst.input[0].focus();
		inst._selectingMonthYear = !inst._selectingMonthYear;
	},

	/* Action for selecting a day. */
	_selectDay: function(id, month, year, td) {
		var target = $(id);
		if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
			return;
		}
		var inst = this._getInst(target[0]);
		inst.selectedDay = inst.currentDay = $('a', td).html();
		inst.selectedMonth = inst.currentMonth = month;
		inst.selectedYear = inst.currentYear = year;
		if (inst.stayOpen) {
			inst.endDay = inst.endMonth = inst.endYear = null;
		}
		this._selectDate(id, this._formatDate(inst,
			inst.currentDay, inst.currentMonth, inst.currentYear));
		if (inst.stayOpen) {
			inst.rangeStart = this._daylightSavingAdjust(
				new Date(inst.currentYear, inst.currentMonth, inst.currentDay));
			this._updateDatepicker(inst);
		}
	},

	/* Erase the input field and hide the date picker. */
	_clearDate: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		inst.stayOpen = false;
		inst.endDay = inst.endMonth = inst.endYear = inst.rangeStart = null;
		this._selectDate(target, '');
	},

	/* Update the input field with the selected date. */
	_selectDate: function(id, dateStr) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
		if (inst.input)
			inst.input.val(dateStr);
		this._updateAlternate(inst);
		var onSelect = this._get(inst, 'onSelect');
		if (onSelect)
			onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);  // trigger custom callback
		else if (inst.input)
			inst.input.trigger('change'); // fire the change event
		if (inst.inline)
			this._updateDatepicker(inst);
		else if (!inst.stayOpen) {
			this._hideDatepicker(null, this._get(inst, 'duration'));
			this._lastInput = inst.input[0];
			if (typeof(inst.input[0]) != 'object')
				inst.input[0].focus(); // restore focus
			this._lastInput = null;
		}
	},

	/* Update any alternate field to synchronise with the main field. */
	_updateAlternate: function(inst) {		
	    var altField = this._get(inst, 'altField');	    
		if (altField) { // update alternate field too
			var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat');
			var date = this._getDate(inst);
			dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));			
			$(altField).each(function() { $(this).html(dateStr); });
		}
	},

	/* Set as beforeShowDay function to prevent selection of weekends.
	   @param  date  Date - the date to customise
	   @return [boolean, string] - is this date selectable?, what is its CSS class? */
	noWeekends: function(date) {
		var day = date.getDay();
		return [(day > 0 && day < 6), ''];
	},

	/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
	   @param  date  Date - the date to get the week for
	   @return  number - the number of the week within the year that contains this date */
	iso8601Week: function(date) {
		var checkDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
		var firstMon = new Date(checkDate.getFullYear(), 1 - 1, 4); // First week always contains 4 Jan
		var firstDay = firstMon.getDay() || 7; // Day of week: Mon = 1, ..., Sun = 7
		firstMon.setDate(firstMon.getDate() + 1 - firstDay); // Preceding Monday
		if (firstDay < 4 && checkDate < firstMon) { // Adjust first three days in year if necessary
			checkDate.setDate(checkDate.getDate() - 3); // Generate for previous year
			return $.datepicker.iso8601Week(checkDate);
		} else if (checkDate > new Date(checkDate.getFullYear(), 12 - 1, 28)) { // Check last three days in year
			firstDay = new Date(checkDate.getFullYear() + 1, 1 - 1, 4).getDay() || 7;
			if (firstDay > 4 && (checkDate.getDay() || 7) < firstDay - 3) { // Adjust if necessary
				return 1;
			}
		}
		return Math.floor(((checkDate - firstMon) / 86400000) / 7) + 1; // Weeks to given date
	},

	/* Parse a string value into a date object.
	   See formatDate below for the possible formats.

	   @param  format    string - the expected format of the date
	   @param  value     string - the date in the above format
	   @param  settings  Object - attributes include:
	                     shortYearCutoff  number - the cutoff year for determining the century (optional)
	                     dayNamesShort    string[7] - abbreviated names of the days from Sunday (optional)
	                     dayNames         string[7] - names of the days from Sunday (optional)
	                     monthNamesShort  string[12] - abbreviated names of the months (optional)
	                     monthNames       string[12] - names of the months (optional)
	   @return  Date - the extracted date value or null if value is blank */
	parseDate: function (format, value, settings) {
		if (format == null || value == null)
			throw 'Invalid arguments';
		value = (typeof value == 'object' ? value.toString() : value + '');
		if (value == '')
			return null;
		var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff;
		var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;		
		var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
		var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
		var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
		var year = -1;
		var month = -1;
		var day = -1;
		var doy = -1;
		var literal = false;
		// Check whether a format character is doubled
		var lookAhead = function(match) {
			var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
			if (matches)
				iFormat++;
			return matches;
		};
		// Extract a number from the string value
		var getNumber = function(match) {
			lookAhead(match);
			var origSize = (match == '@' ? 14 : (match == 'y' ? 4 : (match == 'o' ? 3 : 2)));
			var size = origSize;
			var num = 0;
			while (size > 0 && iValue < value.length &&
					value.charAt(iValue) >= '0' && value.charAt(iValue) <= '9') {
				num = num * 10 + parseInt(value.charAt(iValue++),10);
				size--;
			}
			if (size == origSize)
				throw 'Missing number at position ' + iValue;
			return num;
		};
		// Extract a name from the string value and convert to an index
		var getName = function(match, shortNames, longNames) {
			var names = (lookAhead(match) ? longNames : shortNames);
			var size = 0;
			for (var j = 0; j < names.length; j++)
				size = Math.max(size, names[j].length);
			var name = '';
			var iInit = iValue;
			while (size > 0 && iValue < value.length) {
				name += value.charAt(iValue++);
				for (var i = 0; i < names.length; i++)
					if (name == names[i])
						return i + 1;
				size--;
			}
			throw 'Unknown name at position ' + iInit;
		};
		// Confirm that a literal character matches the string value
		var checkLiteral = function() {
			if (value.charAt(iValue) != format.charAt(iFormat))
				throw 'Unexpected literal at position ' + iValue;
			iValue++;
		};
		var iValue = 0;
		for (var iFormat = 0; iFormat < format.length; iFormat++) {
			if (literal)
				if (format.charAt(iFormat) == "'" && !lookAhead("'"))
					literal = false;
				else
					checkLiteral();
			else
				switch (format.charAt(iFormat)) {
					case 'd':
						day = getNumber('d');
						break;
					case 'D':
						getName('D', dayNamesShort, dayNames);
						break;
					case 'o':
						doy = getNumber('o');
						break;
					case 'm':
						month = getNumber('m');
						break;
					case 'M':
						month = getName('M', monthNamesShort, monthNames);
						break;
					case 'y':
						year = getNumber('y');
						break;
					case '@':
						var date = new Date(getNumber('@'));
						year = date.getFullYear();
						month = date.getMonth() + 1;
						day = date.getDate();
						break;
					case "'":
						if (lookAhead("'"))
							checkLiteral();
						else
							literal = true;
						break;
					default:
						checkLiteral();
				}
		}
		if (year == -1)
			year = new Date().getFullYear();
		else if (year < 100)
			year += new Date().getFullYear() - new Date().getFullYear() % 100 +
				(year <= shortYearCutoff ? 0 : -100);
		if (doy > -1) {
			month = 1;
			day = doy;
			do {
				var dim = this._getDaysInMonth(year, month - 1);
				if (day <= dim)
					break;
				month++;
				day -= dim;
			} while (true);
		}
		var date = this._daylightSavingAdjust(new Date(year, month - 1, day));
		if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day)
			throw 'Invalid date'; // E.g. 31/02/*
		return date;
	},

	/* Standard date formats. */
	ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601)
	COOKIE: 'D, dd M yy',
	ISO_8601: 'yy-mm-dd',
	RFC_822: 'D, d M y',
	RFC_850: 'DD, dd-M-y',
	RFC_1036: 'D, d M y',
	RFC_1123: 'D, d M yy',
	RFC_2822: 'D, d M yy',
	RSS: 'D, d M y', // RFC 822
	TIMESTAMP: '@',
	W3C: 'yy-mm-dd', // ISO 8601

	/* Format a date object into a string value.
	   The format can be combinations of the following:
	   d  - day of month (no leading zero)
	   dd - day of month (two digit)
	   o  - day of year (no leading zeros)
	   oo - day of year (three digit)
	   D  - day name short
	   DD - day name long
	   m  - month of year (no leading zero)
	   mm - month of year (two digit)
	   M  - month name short
	   MM - month name long
	   y  - year (two digit)
	   yy - year (four digit)
	   @ - Unix timestamp (ms since 01/01/1970)
	   '...' - literal text
	   '' - single quote

	   @param  format    string - the desired format of the date
	   @param  date      Date - the date value to format
	   @param  settings  Object - attributes include:
	                     dayNamesShort    string[7] - abbreviated names of the days from Sunday (optional)
	                     dayNames         string[7] - names of the days from Sunday (optional)
	                     monthNamesShort  string[12] - abbreviated names of the months (optional)
	                     monthNames       string[12] - names of the months (optional)
	   @return  string - the date in the above format */
	formatDate: function (format, date, settings) {
		if (!date)
			return '';
		var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
		var dayNamesMin = (settings ? settings.dayNamesMin : null) || this._defaults.dayNamesMin;
		var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
		var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
		var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
		// Check whether a format character is doubled
		var lookAhead = function(match) {
			var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
			if (matches)
				iFormat++;
			return matches;
		};
		// Format a number, with leading zero if necessary
		var formatNumber = function(match, value, len) {
			var num = '' + value;
			if (lookAhead(match))
				while (num.length < len)
					num = '0' + num;
			return num;
		};
		// Format a name, short or long as requested
		var formatName = function(match, value, shortNames, longNames) {
			return (lookAhead(match) ? longNames[value] : shortNames[value]);
		};
		var output = '';
		var literal = false;
		if (date)
			for (var iFormat = 0; iFormat < format.length; iFormat++) {
				if (literal)
					if (format.charAt(iFormat) == "'" && !lookAhead("'"))
						literal = false;
					else
						output += format.charAt(iFormat);
				else
					switch (format.charAt(iFormat)) {
						case 'd':
							output += formatNumber('d', date.getDate(), 2);
							break;
						case 'D':
							//output += formatName('D', date.getDay(), dayNamesShort, dayNames);
							output += formatName('D', date.getDay(), dayNamesMin, dayNames);
							break;
						case 'o':
							var doy = date.getDate();
							for (var m = date.getMonth() - 1; m >= 0; m--)
								doy += this._getDaysInMonth(date.getFullYear(), m);
							output += formatNumber('o', doy, 3);
							break;
						case 'm':
							output += formatNumber('m', date.getMonth() + 1, 2);
							break;
						case 'M':
							output += formatName('M', date.getMonth(), monthNamesShort, monthNames);
							break;
						case 'y':
							output += (lookAhead('y') ? date.getFullYear() :
								(date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100);
							break;
						case '@':
							output += date.getTime();
							break;
						case "'":
							if (lookAhead("'"))
								output += "'";
							else
								literal = true;
							break;
						default:
							output += format.charAt(iFormat);
					}
			}
		return output;
	},

	/* Extract all possible characters from the date format. */
	_possibleChars: function (format) {
		var chars = '';
		var literal = false;
		for (var iFormat = 0; iFormat < format.length; iFormat++)
			if (literal)
				if (format.charAt(iFormat) == "'" && !lookAhead("'"))
					literal = false;
				else
					chars += format.charAt(iFormat);
			else
				switch (format.charAt(iFormat)) {
					case 'd': case 'm': case 'y': case '@':
						chars += '0123456789';
						break;
					case 'D': case 'M':
						return null; // Accept anything
					case "'":
						if (lookAhead("'"))
							chars += "'";
						else
							literal = true;
						break;
					default:
						chars += format.charAt(iFormat);
				}
		return chars;
	},

	/* Get a setting value, defaulting if necessary. */
	_get: function(inst, name) {
		return inst.settings[name] !== undefined ?
			inst.settings[name] : this._defaults[name];
	},

	/* Parse existing date and initialise date picker. */
	_setDateFromField: function(inst) {
		var dateFormat = this._get(inst, 'dateFormat');
		var dates = inst.input ? inst.input.val() : null;
		inst.endDay = inst.endMonth = inst.endYear = null;
		var date = defaultDate = this._getDefaultDate(inst);
		var settings = this._getFormatConfig(inst);
		try {
			date = this.parseDate(dateFormat, dates, settings) || defaultDate;
		} catch (event) {
			this.log(event);
			date = defaultDate;
		}
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		inst.currentDay = (dates ? date.getDate() : 0);
		inst.currentMonth = (dates ? date.getMonth() : 0);
		inst.currentYear = (dates ? date.getFullYear() : 0);
		this._adjustInstDate(inst);
	},

	/* Retrieve the default date shown on opening. */
	_getDefaultDate: function(inst) {
		var date = this._determineDate(this._get(inst, 'defaultDate'), new Date());
		var minDate = this._getMinMaxDate(inst, 'min', true);
		var maxDate = this._getMinMaxDate(inst, 'max');
		date = (minDate && date < minDate ? minDate : date);
		date = (maxDate && date > maxDate ? maxDate : date);
		return date;
	},

	/* A date may be specified as an exact value or a relative one. */
	_determineDate: function(date, defaultDate) {
		var offsetNumeric = function(offset) {
			var date = new Date();
			date.setDate(date.getDate() + offset);
			return date;
		};
		var offsetString = function(offset, getDaysInMonth) {
			var date = new Date();
			var year = date.getFullYear();
			var month = date.getMonth();
			var day = date.getDate();
			var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;
			var matches = pattern.exec(offset);
			while (matches) {
				switch (matches[2] || 'd') {
					case 'd' : case 'D' :
						day += parseInt(matches[1],10); break;
					case 'w' : case 'W' :
						day += parseInt(matches[1],10) * 7; break;
					case 'm' : case 'M' :
						month += parseInt(matches[1],10);
						day = Math.min(day, getDaysInMonth(year, month));
						break;
					case 'y': case 'Y' :
						year += parseInt(matches[1],10);
						day = Math.min(day, getDaysInMonth(year, month));
						break;
				}
				matches = pattern.exec(offset);
			}
			return new Date(year, month, day);
		};
		date = (date == null ? defaultDate :
			(typeof date == 'string' ? offsetString(date, this._getDaysInMonth) :
			(typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : date)));
		date = (date && date.toString() == 'Invalid Date' ? defaultDate : date);
		if (date) {
			date.setHours(0);
			date.setMinutes(0);
			date.setSeconds(0);
			date.setMilliseconds(0);
		}
		return this._daylightSavingAdjust(date);
	},

	/* Handle switch to/from daylight saving.
	   Hours may be non-zero on daylight saving cut-over:
	   > 12 when midnight changeover, but then cannot generate
	   midnight datetime, so jump to 1AM, otherwise reset.
	   @param  date  (Date) the date to check
	   @return  (Date) the corrected date */
	_daylightSavingAdjust: function(date) {
		if (!date) return null;
		date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
		return date;
	},

	/* Set the date(s) directly. */
	_setDate: function(inst, date, endDate) {
		var clear = !(date);
		var origMonth = inst.selectedMonth;
		var origYear = inst.selectedYear;
		date = this._determineDate(date, new Date());
		inst.selectedDay = inst.currentDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = inst.currentMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = inst.currentYear = date.getFullYear();
		if (origMonth != inst.selectedMonth || origYear != inst.selectedYear)
			this._notifyChange(inst);
		this._adjustInstDate(inst);
		if (inst.input) {
			inst.input.val(clear ? '' : this._formatDate(inst));
		}
	},

	/* Retrieve the date(s) directly. */
	_getDate: function(inst) {
		var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null :
			this._daylightSavingAdjust(new Date(
			inst.currentYear, inst.currentMonth, inst.currentDay)));
			return startDate;
	},

	/* Generate the HTML for the current state of the date picker. */
	_generateHTML: function(inst) {
		var today = new Date();
		today = this._daylightSavingAdjust(
			new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time
		var isRTL = this._get(inst, 'isRTL');
		var showButtonPanel = this._get(inst, 'showButtonPanel');
		var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext');
		var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat');
		var numMonths = this._getNumberOfMonths(inst);
		var showCurrentAtPos = this._get(inst, 'showCurrentAtPos');
		var stepMonths = this._get(inst, 'stepMonths');
		var stepBigMonths = this._get(inst, 'stepBigMonths');
		var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1);
		var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
			new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
		var minDate = this._getMinMaxDate(inst, 'min', true);
		var maxDate = this._getMinMaxDate(inst, 'max');
		var drawMonth = inst.drawMonth - showCurrentAtPos;
		var drawYear = inst.drawYear;
		if (drawMonth < 0) {
			drawMonth += 12;
			drawYear--;
		}
		if (maxDate) {
			var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
				maxDate.getMonth() - numMonths[1] + 1, maxDate.getDate()));
			maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
			while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
				drawMonth--;
				if (drawMonth < 0) {
					drawMonth = 11;
					drawYear--;
				}
			}
		}
		inst.drawMonth = drawMonth;
		inst.drawYear = drawYear;
		var prevText = this._get(inst, 'prevText');
		prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
			this._getFormatConfig(inst)));
		var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
			'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#' + inst.id + '\', -' + stepMonths + ', \'M\');"' +
			' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>' :
			(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+ prevText +'"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>'));
		var nextText = this._get(inst, 'nextText');
		nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
			this._getFormatConfig(inst)));
		var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
			'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery.datepicker._adjustDate(\'#' + inst.id + '\', +' + stepMonths + ', \'M\');"' +
			' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>' :
			(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+ nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>'));
		var currentText = this._get(inst, 'currentText');
		var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today);
		currentText = (!navigationAsDateFormat ? currentText :
			this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
		var controls = (!inst.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery.datepicker._hideDatepicker();">' + this._get(inst, 'closeText') + '</button>' : '');
		var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') +
			(this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery.datepicker._gotoToday(\'#' + inst.id + '\');"' +
			'>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '</div>' : '';
		var firstDay = parseInt(this._get(inst, 'firstDay'),10);
		firstDay = (isNaN(firstDay) ? 0 : firstDay);
		var dayNames = this._get(inst, 'dayNames');
		var dayNamesShort = this._get(inst, 'dayNamesShort');
		var dayNamesMin = this._get(inst, 'dayNamesMin');
		var monthNames = this._get(inst, 'monthNames');
		var monthNamesShort = this._get(inst, 'monthNamesShort');
		var beforeShowDay = this._get(inst, 'beforeShowDay');
		var showOtherMonths = this._get(inst, 'showOtherMonths');
		var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week;
		var endDate = inst.endDay ? this._daylightSavingAdjust(
			new Date(inst.endYear, inst.endMonth, inst.endDay)) : currentDate;
		var defaultDate = this._getDefaultDate(inst);
		var html = '';
		for (var row = 0; row < numMonths[0]; row++) {
			var group = '';
			for (var col = 0; col < numMonths[1]; col++) {
				var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
				var cornerClass = ' ui-corner-all';
				var calender = '';
				if (isMultiMonth) {
					calender += '<div class="ui-datepicker-group ui-datepicker-group-';
					switch (col) {
						case 0: calender += 'first'; cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break;
						case numMonths[1]-1: calender += 'last'; cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break;
						default: calender += 'middle'; cornerClass = ''; break;
					}
					calender += '">';
				}
				calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' +
					(/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') +
					(/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') +
					this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
					selectedDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
					(this._get(inst, 'closeIcon') != '' ? '<img src="'+ this._get(inst, 'closeIcon') +'" class="ui-datepicker-closeicon" alt=""/>' : '') + // close-icon
					'</div><table class="ui-datepicker-calendar"><thead>' +
					'<tr>';
				var thead = '';				
				for (var dow = 0; dow < 7; dow++) { // days of the week
					var day = (dow + firstDay) % 7;				   
					thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' +
						'<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>';
				}
				calender += thead + '</tr></thead><tbody>';
				var daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
				if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth)
					inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
				var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
				var numRows = (isMultiMonth ? 6 : Math.ceil((leadDays + daysInMonth) / 7)); // calculate the number of rows to generate
				var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
				for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows
					calender += '<tr>';
					var tbody = '';
					for (var dow = 0; dow < 7; dow++) { // create date picker days
						var daySettings = (beforeShowDay ?
							beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']);
						var otherMonth = (printDate.getMonth() != drawMonth);
						var unselectable = otherMonth || !daySettings[0] ||
							(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
						tbody += '<td class="' +
							((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends
							(otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months
							((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key
							(defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ?
							// or defaultDate is current printedDate and defaultDate is selectedDate
							' ' + this._dayOverClass : '') + // highlight selected day
							(unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') +  // highlight unselectable days
							(otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates
							(printDate.getTime() >= currentDate.getTime() && printDate.getTime() <= endDate.getTime() ? // in current range
							' ' + this._currentClass : '') + // highlight selected day
							(printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different)
							((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title
							(unselectable ? '' : ' onclick="DP_jQuery.datepicker._selectDay(\'#' +
							inst.id + '\',' + drawMonth + ',' + drawYear + ', this);return false;"') + '>' + // actions
							(otherMonth ? (showOtherMonths ? printDate.getDate() : '&#xa0;') : // display for other months
							(unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' +
							(printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') +
							(printDate.getTime() >= currentDate.getTime() && printDate.getTime() <= endDate.getTime() ? // in current range
							' ui-state-active' : '') + // highlight selected day
							'" href="#">' + printDate.getDate() + '</a>')) + '</td>'; // display for this month
						printDate.setDate(printDate.getDate() + 1);
						printDate = this._daylightSavingAdjust(printDate);
					}
					calender += tbody + '</tr>';
				}
				drawMonth++;
				if (drawMonth > 11) {
					drawMonth = 0;
					drawYear++;
				}
				calender += '</tbody></table>' + (isMultiMonth ? '</div>' + 
							((numMonths[0] > 0 && col == numMonths[1]-1) ? '<div class="ui-datepicker-row-break"></div>' : '') : '');
				group += calender;
			}
			html += group;
		}
		html += buttonPanel + ($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ?
			'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : '');
		inst._keyEvent = false;
		return html;
	},

	/* Generate the month and year header. */
	_generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
			selectedDate, secondary, monthNames, monthNamesShort) {
		minDate = (inst.rangeStart && minDate && selectedDate < minDate ? selectedDate : minDate);
		var changeMonth = this._get(inst, 'changeMonth');
		var changeYear = this._get(inst, 'changeYear');
		var showMonthAfterYear = this._get(inst, 'showMonthAfterYear');
		var html = '<div class="ui-datepicker-title">';
		var monthHtml = '';
		// month selection
		if (secondary || !changeMonth)
			monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span> ';
		else {
			var inMinYear = (minDate && minDate.getFullYear() == drawYear);
			var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear);
			monthHtml += '<select class="ui-datepicker-month" ' +
				'onchange="DP_jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'M\');" ' +
				'onclick="DP_jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
			 	'>';
			for (var month = 0; month < 12; month++) {
				if ((!inMinYear || month >= minDate.getMonth()) &&
						(!inMaxYear || month <= maxDate.getMonth()))
					monthHtml += '<option value="' + month + '"' +
						(month == drawMonth ? ' selected="selected"' : '') +
						'>' + monthNamesShort[month] + '</option>';
			}
			monthHtml += '</select>';
		}
		if (!showMonthAfterYear)
			html += monthHtml + ((secondary || changeMonth || changeYear) && (!(changeMonth && changeYear)) ? '&#xa0;' : '');
		// year selection
		if (secondary || !changeYear)
			html += '<span class="ui-datepicker-year">' + drawYear + '</span>';
		else {
			// determine range of years to display
			var years = this._get(inst, 'yearRange').split(':');
			var year = 0;
			var endYear = 0;
			if (years.length != 2) {
				year = drawYear - 10;
				endYear = drawYear + 10;
			} else if (years[0].charAt(0) == '+' || years[0].charAt(0) == '-') {
				year = drawYear + parseInt(years[0], 10);
				endYear = drawYear + parseInt(years[1], 10);
			} else {
				year = parseInt(years[0], 10);
				endYear = parseInt(years[1], 10);
			}
			year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
			endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
			html += '<select class="ui-datepicker-year" ' +
				'onchange="DP_jQuery.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'Y\');" ' +
				'onclick="DP_jQuery.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
				'>';
			for (; year <= endYear; year++) {
				html += '<option value="' + year + '"' +
					(year == drawYear ? ' selected="selected"' : '') +
					'>' + year + '</option>';
			}
			html += '</select>';
		}
		if (showMonthAfterYear)
			html += (secondary || changeMonth || changeYear ? '&#xa0;' : '') + monthHtml;
		html += '</div>'; // Close datepicker_header
		return html;
	},

	/* Adjust one of the date sub-fields. */
	_adjustInstDate: function(inst, offset, period) {
		var year = inst.drawYear + (period == 'Y' ? offset : 0);
		var month = inst.drawMonth + (period == 'M' ? offset : 0);
		var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) +
			(period == 'D' ? offset : 0);
		var date = this._daylightSavingAdjust(new Date(year, month, day));
		// ensure it is within the bounds set
		var minDate = this._getMinMaxDate(inst, 'min', true);
		var maxDate = this._getMinMaxDate(inst, 'max');
		date = (minDate && date < minDate ? minDate : date);
		date = (maxDate && date > maxDate ? maxDate : date);
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		if (period == 'M' || period == 'Y')
			this._notifyChange(inst);
	},

	/* Notify change of month/year. */
	_notifyChange: function(inst) {
		var onChange = this._get(inst, 'onChangeMonthYear');
		if (onChange)
			onChange.apply((inst.input ? inst.input[0] : null),
				[inst.selectedYear, inst.selectedMonth + 1, inst]);
	},

	/* Determine the number of months to show. */
	_getNumberOfMonths: function(inst) {
		var numMonths = this._get(inst, 'numberOfMonths');
		return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths));
	},

	/* Determine the current maximum date - ensure no time components are set - may be overridden for a range. */
	_getMinMaxDate: function(inst, minMax, checkRange) {
		var date = this._determineDate(this._get(inst, minMax + 'Date'), null);
		return (!checkRange || !inst.rangeStart ? date :
			(!date || inst.rangeStart > date ? inst.rangeStart : date));
	},

	/* Find the number of days in a given month. */
	_getDaysInMonth: function(year, month) {
		return 32 - new Date(year, month, 32).getDate();
	},

	/* Find the day of the week of the first of a month. */
	_getFirstDayOfMonth: function(year, month) {
		return new Date(year, month, 1).getDay();
	},

	/* Determines if we should allow a "next/prev" month display change. */
	_canAdjustMonth: function(inst, offset, curYear, curMonth) {
		var numMonths = this._getNumberOfMonths(inst);
		var date = this._daylightSavingAdjust(new Date(
			curYear, curMonth + (offset < 0 ? offset : numMonths[1]), 1));
		if (offset < 0)
			date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
		return this._isInRange(inst, date);
	},

	/* Is the given date in the accepted range? */
	_isInRange: function(inst, date) {
		// during range selection, use minimum of selected date and range start
		var newMinDate = (!inst.rangeStart ? null : this._daylightSavingAdjust(
			new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay)));
		newMinDate = (newMinDate && inst.rangeStart < newMinDate ? inst.rangeStart : newMinDate);
		var minDate = newMinDate || this._getMinMaxDate(inst, 'min');
		var maxDate = this._getMinMaxDate(inst, 'max');
		return ((!minDate || date >= minDate) && (!maxDate || date <= maxDate));
	},

	/* Provide the configuration settings for formatting/parsing. */
	_getFormatConfig: function(inst) {
		var shortYearCutoff = this._get(inst, 'shortYearCutoff');
		shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff :
			new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
		return {shortYearCutoff: shortYearCutoff,
			dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'),
			monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')};
	},

	/* Format the given date for display. */
	_formatDate: function(inst, day, month, year) {
		if (!day) {
			inst.currentDay = inst.selectedDay;
			inst.currentMonth = inst.selectedMonth;
			inst.currentYear = inst.selectedYear;
		}
		var date = (day ? (typeof day == 'object' ? day :
			this._daylightSavingAdjust(new Date(year, month, day))) :
			this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
		return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst));
	}
});

/* jQuery extend now ignores nulls! */
function extendRemove(target, props) {
	$.extend(target, props);
	for (var name in props)
		if (props[name] == null || props[name] == undefined)
			target[name] = props[name];
	return target;
};

/* Determine whether an object is an array. */
function isArray(a) {
	return (a && (($.browser.safari && typeof a == 'object' && a.length) ||
		(a.constructor && a.constructor.toString().match(/\Array\(\)/))));
};

/* Invoke the datepicker functionality.
   @param  options  string - a command, optionally followed by additional parameters or
                    Object - settings for attaching new datepicker functionality
   @return  jQuery object */
$.fn.datepicker = function(options){

	/* Initialise the date picker. */
	if (!$.datepicker.initialized) {
		$(document).mousedown($.datepicker._checkExternalClick).
			find('body').append($.datepicker.dpDiv);
		$.datepicker.initialized = true;
	}

	var otherArgs = Array.prototype.slice.call(arguments, 1);
	if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate'))
		return $.datepicker['_' + options + 'Datepicker'].
			apply($.datepicker, [this[0]].concat(otherArgs));
	return this.each(function() {
		typeof options == 'string' ?
			$.datepicker['_' + options + 'Datepicker'].
				apply($.datepicker, [this].concat(otherArgs)) :
			$.datepicker._attachDatepicker(this, options);
	});
};

$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.7.1";

// Workaround for #4055
// Add another global to avoid noConflict issues with inline event handlers
window.DP_jQuery = $;

})(jQuery);
	
	/**
	 * jQuery BASE64 functions
	 * 
	 * 	<code>
	 * 		Encodes the given data with base64. 
	 * 		String $.base64Encode ( String str )
	 *		<br />
	 * 		Decodes a base64 encoded data.
	 * 		String $.base64Decode ( String str )
	 * 	</code>
	 * 
	 * Encodes and Decodes the given data in base64.
	 * This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies.
	 * Base64-encoded data takes about 33% more space than the original data. 
	 * This javascript code is used to encode / decode data using base64 (this encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean). Script is fully compatible with UTF-8 encoding. You can use base64 encoded data as simple encryption mechanism.
	 * If you plan using UTF-8 encoding in your project don't forget to set the page encoding to UTF-8 (Content-Type meta tag). 
	 * This function orginally get from the WebToolkit and rewrite for using as the jQuery plugin.
	 * 
	 * Example
	 * 	Code
	 * 		<code>
	 * 			$.base64Encode("I'm Persian."); 
	 * 		</code>
	 * 	Result
	 * 		<code>
	 * 			"SSdtIFBlcnNpYW4u"
	 * 		</code>
	 * 	Code
	 * 		<code>
	 * 			$.base64Decode("SSdtIFBlcnNpYW4u");
	 * 		</code>
	 * 	Result
	 * 		<code>
	 * 			"I'm Persian."
	 * 		</code>
	 * 
	 * @alias Muhammad Hussein Fattahizadeh < muhammad [AT] semnanweb [DOT] com >
	 * @link http://www.semnanweb.com/jquery-plugin/base64.html
	 * @see http://www.webtoolkit.info/
	 * @license http://www.gnu.org/licenses/gpl.html [GNU General Public License]
	 * @param {jQuery} {base64Encode:function(input))
	 * @param {jQuery} {base64Decode:function(input))
	 * @return string
	 */
	
	(function($){
		
		var keyString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
		
		var uTF8Encode = function(string) {
			string = string.replace(/\x0d\x0a/g, "\x0a");
			var output = "";
			for (var n = 0; n < string.length; n++) {
				var c = string.charCodeAt(n);
				if (c < 128) {
					output += String.fromCharCode(c);
				} else if ((c > 127) && (c < 2048)) {
					output += String.fromCharCode((c >> 6) | 192);
					output += String.fromCharCode((c & 63) | 128);
				} else {
					output += String.fromCharCode((c >> 12) | 224);
					output += String.fromCharCode(((c >> 6) & 63) | 128);
					output += String.fromCharCode((c & 63) | 128);
				}
			}
			return output;
		};
		
		var uTF8Decode = function(input) {
			var string = "";
			var i = 0;
			var c = c1 = c2 = 0;
			while ( i < input.length ) {
				c = input.charCodeAt(i);
				if (c < 128) {
					string += String.fromCharCode(c);
					i++;
				} else if ((c > 191) && (c < 224)) {
					c2 = input.charCodeAt(i+1);
					string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
					i += 2;
				} else {
					c2 = input.charCodeAt(i+1);
					c3 = input.charCodeAt(i+2);
					string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
					i += 3;
				}
			}
			return string;
		}
		
		$.extend({
			base64Encode: function(input) {
				var output = "";
				var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
				var i = 0;
				input = uTF8Encode(input);
				while (i < input.length) {
					chr1 = input.charCodeAt(i++);
					chr2 = input.charCodeAt(i++);
					chr3 = input.charCodeAt(i++);
					enc1 = chr1 >> 2;
					enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
					enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
					enc4 = chr3 & 63;
					if (isNaN(chr2)) {
						enc3 = enc4 = 64;
					} else if (isNaN(chr3)) {
						enc4 = 64;
					}
					output = output + keyString.charAt(enc1) + keyString.charAt(enc2) + keyString.charAt(enc3) + keyString.charAt(enc4);
				}
				return output;
			},
			base64Decode: function(input) {
				var output = "";
				var chr1, chr2, chr3;
				var enc1, enc2, enc3, enc4;
				var i = 0;
				input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
				while (i < input.length) {
					enc1 = keyString.indexOf(input.charAt(i++));
					enc2 = keyString.indexOf(input.charAt(i++));
					enc3 = keyString.indexOf(input.charAt(i++));
					enc4 = keyString.indexOf(input.charAt(i++));
					chr1 = (enc1 << 2) | (enc2 >> 4);
					chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
					chr3 = ((enc3 & 3) << 6) | enc4;
					output = output + String.fromCharCode(chr1);
					if (enc3 != 64) {
						output = output + String.fromCharCode(chr2);
					}
					if (enc4 != 64) {
						output = output + String.fromCharCode(chr3);
					}
				}
				output = uTF8Decode(output);
				return output;
			}
		});
	})(jQuery);P7 = {
  /**
   * Unique ID (per page) - used for Flash-Modules
   */
  flashConnectionId: Math.ceil(Math.random()*9999),

  /**
   * Minimum required flash-version
   */
  flashRequiredVersion: "9.0.115",

  /**
   * Minimum required flash-version for Header
   */
  flashHeaderRequiredVersion: "10.0.0",

  /** Holds the number of clicks in different modules before the ads should be reloaded. */
  
  globalGalleryClicksBeforeFullbannerReload : '',
  
  globalGalleryClicksBeforeSkyscraperReload : '',
  
  globalGalleryClicksBeforeRectangleReload : '',
  
  globalTabboxClicksBeforeFullbannerReload : '',
  
  globalTabboxClicksBeforeSkyscraperReload : '',
  
  globalTabboxClicksBeforeRectangleReload : '',


  /**
   * Subnavigation Flyouts
   */
  subnavflyouts: {
    activeItem: null,
    init: function() {
      if ($('.videopagedetector').size() > 0) {
        return;
  	  }
  	  $('#nav-sub .hasFlyout').each(function() {
        var flyout = $("#flyout_" + $(this).attr('id'));

        //get max height of content
        var maxFlyoutHeight = 0;
        flyout.find('.page').each(function(){
          if ($(this).height() > maxFlyoutHeight) {
  			maxFlyoutHeight = $(this).height();
  		}
        });
        if (maxFlyoutHeight > 267) {
  	  	maxFlyoutHeight = 267;
  	  }
        // hide & set correct position
        flyout.css({
          'display' : 'none',
          'left' : '6px'
        });

        P7.subnavflyouts.activeItem = $('#nav-sub a.activenavigation');

        // show/hide flyout on click
        $(this).click(function(event){
          if (flyout.css("display") == "none") {
            $('.flyout').hide();
            $('#breadcrumb').hide()
            $('#header').css('margin-bottom', '-21px');

            $('#nav-sub a').removeClass('activenavigation');
            $(this).addClass('activenavigation');

            flyout.show();
            flyout.find('.flyoutpane').jScrollPane({showArrows:true, scrollbarMargin:0, fixedHeight: maxFlyoutHeight, fixedWidth: 812});
            $('#p7_navspace').height(flyout.height()+33);
          } else {
            flyout.hide();
            $('#breadcrumb').show()
            $('#header').css('margin-bottom', '0');
            $('#p7_navspace').height(0);

            $('#nav-sub a').removeClass('activenavigation');
            P7.subnavflyouts.activeItem.addClass('activenavigation');
          }
          return false;
        });

        // add pager
        flyout.pager('.page', {
          navId: 'flyoutpager_' + $(this).attr('id'),
          prevText: '&lsaquo;&lsaquo; ',
          nextText: ' &rsaquo;&rsaquo;',
          counterText: 'Seite ',
          counterSeparatorText: ' von ',
          showPrevNext: true,
          pageSize: 1,
          type: 'counter',
          prevNextPosition: 'inner'
        });

        // recreate scrollpane on pager-navigation
        flyout.find('.pg-nav a').click(function() {
          flyout.find('.flyoutpane').jScrollPane({showArrows:true, scrollbarMargin:0, fixedHeight: maxFlyoutHeight, fixedWidth: 812});
        });
     });
    }
  },

  /**
   * Function for fetching the specified parameter value from the current window url.
   *
   * @param name the name of the parameter to get the value for.
   */
  getParam: function (name) {
    var searchValue = location.search;
	var wrongIndex = searchValue.indexOf("&submit");
	if(wrongIndex != -1) {
	  searchValue = searchValue.substring(0, wrongIndex);
	}
    var match = new RegExp(name + "=(.+)[&]", "i").exec(searchValue);
    if (match == null) {
      match = new RegExp(name + "=(.+)", "i").exec(searchValue);
    }

    if (match == null) {
      return null;
    }

    match = match + "";
    result = match.split(",");
    return result[1];
  },

  /**
   * Popup-Links
   */
  popup: function(url, windowName, x, y) {
    var winProperties = "width=" + x + ",height=" + y + ",status=yes,scrollbars=yes,resizable=yes";
    fenster = window.open(url, windowName, winProperties);
    fenster.focus();
    return false;
  },

  /**
   * Home-Flash-Teaser
   */
  flashheader: function(xmlurl) {
    if (swfobject.hasFlashPlayerVersion(P7.flashHeaderRequiredVersion)) {
      // display Flash Header
      var flashvars = {};
      flashvars.connectionID = P7.flashConnectionId;
      flashvars.data = xmlurl;
      var params = {};
      params.wmode = "transparent";
      var attributes = {};
      /* width for page-width 1196 px is 996px
      *swfobject.embedSWF("/swf/header.swf", "flashContainer", "996", "281", P7.flashHeaderRequiredVersion, false, flashvars, params, attributes);
      */
      /* width for page-width 1024px is: 818px */
      swfobject.embedSWF("/swf/header.swf", "flashContainer", "818", "281", P7.flashHeaderRequiredVersion, false, flashvars, params, attributes);
    } else {
      // display Fallback Header
      $('#flashContainer').show();
    }
  },

  /**
   * Module Slider
   */
  slider: function(id, sliderWidth, sliderHeight, xmlurl) {
    var sliderFlashVars = {
      connectionID: P7.flashConnectionId,
      data: xmlurl
    };
    var sliderParams = { wmode: "transparent" };
    var sliderAttributes = {};
    swfobject.embedSWF("/swf/slider.swf", "slider-" + id,
      sliderWidth, sliderHeight, P7.flashRequiredVersion, false, sliderFlashVars, sliderParams, sliderAttributes);
  },

  /**
   * Module Video-Teaser
   */
  videoteaser: function(id, xmlurl, attributes) {
    var flashvars = {
        connectionID: P7.flashConnectionId,
        data: xmlurl
    };
    var params = { wmode: "transparent" };
    swfobject.embedSWF("/swf/videoTeaser.swf", id,
        "154", "106", P7.flashRequiredVersion, false, flashvars, params, attributes);
  },

  /**
   * Module Video-Overview
   */
  videooverview: function(id) {
    $('#pagingbox' + id).pager('.page', {
      navId: 'paging' + id,
      prevText: '&lsaquo;&lsaquo; ',
      nextText: ' &rsaquo;&rsaquo;',
      counterText: 'Seite ',
      counterSeparatorText: ' von ',
      showPrevNext: true,
      pageSize: 1,
      type: 'counter',
      showIndicator: false,
      prevNextPosition: 'inner'
     });
  },

  /**
   * Module Hotbutton
   */
  hotbutton: {
    init: function(link, image, text, cookiename) {
      // add layer at beginning of body

      var p7_hotbutton = '<div id="hotbuttonlayer" title="'+cookiename+'">';
      p7_hotbutton += '<div class="curtain">&nbsp;</div><div class="content" id="hotbuttonlayer_content">';
      p7_hotbutton += '<div class="close"><a href="#"><img src="/img/module/button_lightbox_close.gif" width="21" height="19" alt="zum Schließen hier klicken" /></a></div>';
      p7_hotbutton += '<div class="layer-content">'
      if (link) {
	  	p7_hotbutton += link;
	  }
      p7_hotbutton += image;
      if (link) {
	  	p7_hotbutton += '</a>';
	  }
      p7_hotbutton += '<div class="text"><p>'+text+'</p></div>';
      p7_hotbutton += '</div></div></div>';
      $('body').prepend(p7_hotbutton);

      P7.hotbutton.isPresentOnPage = true;
      P7.hotbutton.cookieName = cookiename;
      P7.hotbutton.shouldBeDisplayed = jQuery.cookie(P7.hotbutton.cookieName) == null;
      $(document).ready(function() {
        /*  the hot button should be displayed only if the flash info is not displayed. */
        if (P7.flashintro.isPresentOnPage && P7.flashintro.shouldBeDisplayed) {
          return false;
        }
        if(P7.hotbutton.shouldBeDisplayed) {
          jQuery.cookie(cookiename, 'true', {path: '/', secure: false});
          P7.hotbutton.show();
          /*  set the click handler for the button */
          $("#hotbuttonlayer .close a").click(P7.hotbutton.onLayerClick);
        }
        $("#hotbuttonlayer .layer-content a").click(function() {
        	/* close the hot button layer */
        	P7.hotbutton.onLayerClick();
        	return true;
        });
        return false;
      });
    },
    onLayerClick: function() {
        P7.hotbutton.hide();
        P7.ads.show();
    },
    show: function() {
      $("#hotbuttonlayer").show();
      if (/MSIE 6/i.test(navigator.userAgent)) {
        // resize curtain in IE 6
        var h = ($(window).height() > $('body').height()) ? $(window).height() : $('body').height();
        $('#hotbuttonlayer .curtain').height(h);
      }
    },
    hide: function() {
      $("#hotbuttonlayer").hide();
    },
    /** The name of the cookie present if the hotbutton has been displayed. */
    cookieName : "",
    isPresentOnPage : false,
    shouldBeDisplayed : false
  },

  /**
   * Module Chart
   */
  chart: function(id) {
    $('#scrollpane-' + id).jScrollPane({showArrows:true, scrollbarMargin:0});

    $("#charts-" + id + " a.openup").click(function() {
      var tr = $(this).parents('tr');
      $("tr:not(.itemview)").removeClass('viewoff').addClass('viewon');
      tr.removeClass('viewon');
      tr.addClass('viewoff');
      $("tr.itemview").removeClass('viewon').addClass('viewoff');
      tr.next().removeClass('viewoff');
      tr.next().addClass('viewon');

      $('#scrollpane-' + id).jScrollPane({showArrows:true, scrollbarMargin:0});
      return false;
    });
  },

  /**
   * Tabs
   */
  tabs: {
    reloading: false,
    render: function(id, url, index, inContentPage) {
      var container = $("#tabbedbox_tabs-" + id).parent();

  		/* Rewrite the tab links */
  		$("a.tab-link").each(function(i) {
  			var newHref = P7.css.getClassStartingWith(this, "tabbedbox_tab-");
  			$(this).attr("href", "#" + newHref);
  		});
  	  $(window).load(function(){
        P7.tabs.setHeight(container);
      });
      $(".tab-loading", container).ajaxStart(function(){
        if (P7.tabs.reloading) {
          $(this).show();
        }
      });
      $(".tab-loading", container).ajaxStop(function(){
        if (P7.tabs.reloading) {
          $(this).hide();
          P7.tabs.setHeight(container);
          P7.tabs.reloading = false;
        }
      });
      $("#tabbedbox_tabs-" + id).tabs();
      $("#tabbedbox_tabs-" + id).tabs('select', index);
      $("#tabbedbox_tabs-" + id + " ul li a").click(function(){
        P7.tabs.reloading = true;
        var hrefArray = $(this).attr('href').split("-");
        var index = hrefArray[2];
        var tabContent = $("#tabbedbox_tab-" + id + "-" + index);
        if(tabContent && tabContent.children().size() == 0) {
          tabContent.load(url + "?tabItemId=" + $(this).attr('rel') + "&inContentPage=" + inContentPage);
        }
        return false;
      });
    },
    setHeight: function(container) {
      $('.ui-tabs-panel:visible', container).css('height', 'auto');
      $('.ui-tabs-panel:visible', container).addClass('tab-loaded');

      var tabHeight = $('.ui-tabs-panel:visible', container).height();
      var tabWidth = $('.ui-tabs-panel:visible', container).width();
      $('.ui-tabs-panel:hidden', container).not('.tab-loaded').each(function() {
        $(this).css('height', tabHeight + 'px');
      });

      var loadingleft = tabWidth / 2;
      var loadingTop = tabHeight / 2;

      if ($('.tab-loading', container).siblings('.module-tabs').size() == 1) {
        loadingTop = loadingTop + $('.tab-loading', container).siblings('.module-tabs').outerHeight(true);
      }

      $('.tab-loading', container).css({
        'position': 'absolute',
        'left': loadingleft + 'px',
        'top': loadingTop + 'px'
      });
    }
  },

  /**
   * Flash-Intro
   */
  flashintro: {
    init: function(swfurl, cookiename) {
      if (!swfobject.hasFlashPlayerVersion(P7.flashRequiredVersion)) {
        // flash is not installed, so don't display anything
        return;
      }
      P7.flashintro.isPresentOnPage = true;
      P7.flashintro.cookieName = cookiename;
      P7.flashintro.shouldBeDisplayed = jQuery.cookie(P7.flashintro.cookieName) == null;

      if(P7.flashintro.shouldBeDisplayed) {
        jQuery.cookie(cookiename, 'false', {path: '/', secure: false});
        P7.flashintro.show();
      }

      var flashvars = { connectionID: P7.flashConnectionId };
      var params = { wmode: "transparent" };
      var attributes = {};
      swfobject.embedSWF(swfurl, "flashintro-container", "818", "460", P7.flashRequiredVersion, false, flashvars, params, attributes);
    },
    show: function() {
      $("#flashintrolayer").show();
    },
    hide: function() {
      $("#flashintrolayer").hide();
    },
    isPresentOnPage : false,
    cookieName : "",
    shouldBeDisplayed : false
  },

  googleAdSense: {
    /**
     * Displays the retrieved google ads.
     *
     * @param googleAds the google ads to display.
     * @param linksContainerId the id of the div container that encapsulates all search results.
     * @param divContainerId the id of the div container that will contain only the results html.
     * @param resultTemplate the template to use for an ad result.
     * @param resultTopTemplate the template to use for an top ad result.
     */
    displaySearchAds :function (googleAds, linksContainerId ,divContainerId, resultTemplate, resultTopTemplate) {
      /*  todo [sb] differentiate between narrow and wide ads */

      var linksContainerIdTop = linksContainerId + "-top";
      var divContainerIdTop = divContainerId + "-top";

      /* check the number of results */
      var adsNumber = googleAds.length;

      if (adsNumber <= 3) { // hide the links container if no results are present.
        $("#" + linksContainerId).hide();
      } else { // show the container if we have results.
        $("#" + linksContainerId).show();
      }

      if (adsNumber <= 0) { // hide the top container if no results are present.
        $("#" + linksContainerIdTop).hide();
        return;
      } else { // show the container if we have results.
        $("#" + linksContainerIdTop).show();
      }

      // top...
      var adsText = "";
      var topCount = (adsNumber <= 3) ? adsNumber : 3;
      for (i = 0; i < topCount; i++) {
        var adRow = resultTopTemplate;
        var googleAd = googleAds[i];
        /*  replacing the placeholders in the template */
        adRow = adRow.replace(/\{title\}/g, googleAd.line1);
        adRow = adRow.replace(/\{description\}/g, googleAd.line2);
        adRow = adRow.replace(/\{url\}/g, googleAd.url);
        adRow = adRow.replace(/\{visible_url\}/g, googleAd.visible_url);
//      TODO: replace the above 4 lines with the line below
//        P7.template.apply(adRow, { title: googleAd.line1, description: googleAd.line2, url: googleAd.url, visible_url: googleAd.visible_url });
        adsText += adRow;
      }

      document.getElementById(divContainerIdTop).innerHTML = adsText;


      if (adsNumber <= 3) {
        return;
      }

      adsText = "";
      for (i = 3; i < adsNumber; i++) {
        var adRow = resultTemplate;
        var googleAd = googleAds[i];
        /*  replacing the placeholders in the template */
        adRow = adRow.replace(/\{title\}/g, googleAd.line1);
        adRow = adRow.replace(/\{description\}/g, googleAd.line2);
        adRow = adRow.replace(/\{url\}/g, googleAd.url);
        adRow = adRow.replace(/\{visible_url\}/g, googleAd.visible_url);
//		  TODO: replace the above 4 lines with the line below
//        P7.template.apply(adRow, { title: googleAd.line1, description: googleAd.line2, url: googleAd.url, visible_url: googleAd.visible_url });
        adsText += adRow;
      }

      document.getElementById(divContainerId).innerHTML = adsText;
    }
  },

  template: {
	/**
	 * Replaces the place holders in the given template with the values specified in the
	 * parameters map.
	 *
	 * @param template the template to be used
	 * @param parameters the parameters map
	 */
	apply: function(template, parameters) {
	  if (!template) {
		  return template;
	  }
	  for (var key in parameters) {
		var re = new RegExp("{" + key + "}", "g");
		template = template.replace(re, parameters[key]);
	  }

	  return template;
  	}
  },

  ads: {

	/** Overlay presets used for showing & hiding ads. */
	overlay: {

		/**
		 * JSON object for the "image gallery" overlay (light box). It describes which ads
		 * need to be shown / hidden when the light box is opened / closed.
		 */
		IMAGEGALLERY: {
			placeholders: [ "fullbanner", "popup", "rectangle", "fullbanner", "skyscraper",
			                "shoppingtippsno1", "shoppingtippsno2", "shoppingtippsno3",
			                "shoppingtippsno4", "shoppingtippsno5", "shoppingtippsno6",
			                "shoppingtippsno7", "shoppingtippsno8", "shoppingtippsno9"]
		},

		/**
		 * JSON object for the "flyout" overlay (epg flyout, etc.).  It describes which ads
		 * need to be shown / hidden when a flyover is shown / hidden.
		 */
		FLYOUT: {
			placeholders: [ "skyscraper", "rectangle" ]
		},

		/**
		 * JSON object which describes the ads that need to be prepared when the navigation
		 * flyout is rendered.
		 */
		NAVIGATIONFLYOUT: {
			placeholders: [ "rectangle", "skyscraper" ]
		}
	},

    /** Shows the ads. */
    show: function () {
      if (window.SIMAD) {
        window.SIMAD.CmsAdapter.setProperty('globalAdTagsLoading', SIMAD.Loading.INSTREAM);
        window.SIMAD.reloadAds();
      }
    },
    /** Reloads the ads. */
    reload: function (reloadType, adIdArray) {
      if (window.SIMAD) {
    	window.SIMAD.reloadAds(adIdArray);
      }
    },
    /**
     * Render callback function invoked by the AdServer after the shopping tips are received.
     */
    shoppingtipsRenderCallback: function(adTagObj, params) {
    	var content = "";

    	if (params) {
	    	var shoppingTipsTemplates = {
	    		text: '<div class="module pb-shopping"><div class="module-title"><h3>{headline}</h3></div><div class="module-body"><div class="text"><p><b>{teaserHeadline}</b><br />{teaserText}</p><p><a href="{linkHref}" target="_blank">{linkText}</a></p></div></div></div><img src="/img/module/image_text_mirroring.png" width="100%" height="24" border="0" alt="" />',
	    		image: '<div class="module pb-shopping"><div class="module-title"><h3>{headline}</h3></div><div class="module-body"><div class="caption"><h4>{teaserHeadline}</h4><p><a href="{linkHref}" target="_blank">{linkText}</a></p></div><img src="{imageURL}" width="154" height="108" alt="" /></div></div><img src="/img/module/image_text_mirroring.png" width="100%" height="24" border="0" alt="" />'
	    	};

	    	if (params.type === "image") {
	    		content = P7.template.apply(shoppingTipsTemplates.image, { headline: params.headline, linkHref: params.linkHref, imageURL: params.imageURL, teaserHeadline: params.teaserHeadline, linkText: params.linkText, teaserText: params.teaserText });
	    	}
	    	if (params.type === "text") {
	    		content = P7.template.apply(shoppingTipsTemplates.text, { headline: params.headline, linkHref: params.linkHref, imageURL: params.imageURL, teaserHeadline: params.teaserHeadline, linkText: params.linkText, teaserText: params.teaserText });
 	    	}
    	}

    	return content;
    },

    /**
     * Callback function invoked when the image gallery zoom (lightbox) is created. The callback
     * is responsible for preparing the ad content.
     *
     * @param placeholderId the ID of the DOM element that contains the ads
     */
	imagegallery_zoom_init_ads: function (placeholderId) {
		if (window.SIMAD == undefined) {
			/* SIMAD is not present */
			return;
		}

		if (!SIMAD.CmsAdapter.getAd("galleryRectangle")) {
			// open new session
			SIMAD.newSession();
		
			// add galleryZoom into the session
			P7.ads.galleryZoomAd = SIMAD.addAd({
		        id: "galleryRectangle", // Unique ID for the Ad (same as in JSON object for initialisation)
		        loading: SIMAD.Loading.POSTSTREAM,
		        adTag: SIMAD.AdTag.FULLBANNER,
		        placeholder: placeholderId // new: the ID of the HTML element where the ad will be placed
			});

		}

		SIMAD.CmsAdapter.setTaxonomy({"contentType":"gallery_zoom"});
		SIMAD.reloadAds();
	},

	/**
	 * Callback function invoked when the image gallery zoom is closed. It is responsible for
	 * restoring the ads on the page.
	 */
	image_gallery_zoom_close_ads: function() {
		if (window.SIMAD == undefined) {
			/* SIMAD is not present */
			return;
		}
		SIMAD.closeSession();
	},

	/**
     * Callback method invoked when the skyscraper is loaded.
     *
     * @param _AdTagJson Json object that provides additional information about the rendered ad
     */
    skyscraperLoadCallback: function(_AdTagJson) {
    	if ($("#mediacenter").length > 0) {
			var _pageContentType = SIMAD.CmsAdapter.getProperty("contentType");
			SIMAD.debug("log", "_pageContent:" + _pageContentType);
			var skyscraper = $("#ad-right");
			skyscraper.addClass("ad-right-mediacenter-video");
			switch (_pageContentType) {
				case "MCplayer":
				case "MCcontent":
				case "CPplayer":
				case "np.cat.mediatyp.videopage":
				case "np.cat.mediatyp.mediacenter.video":
					if (_AdTagJson.loading == SIMAD.Loading.ONEVENT) {
						skyscraper.hide();
					} else {
						skyscraper.show();
					}
					break;
				default:
					break;
			}
		}
	}
  },

  tracking: {
    trackTeaser : function (id, linkType, linkUrl, isEscaped, event) {
      if (isEscaped == "true") {
    	  linkUrl = window.unescape(linkUrl);
      }

	  var teaserElement = document.getElementById(id);
       if (window.simTracker && teaserElement != null){
         teaserElement.simTrackerMetainfo.linkType = linkType;
         teaserElement.simTrackerMetainfo.linkUrl = linkUrl;
         simTracker.track(teaserElement, event);
       }
    }
  },

  /**
   * Ads reload trigger class.
   *
   * @param clicksBeforeAdReload the number of clicks in an object before reloading the ads.
   * If a negative value is provided then the ads will never be reloaded.
   */
  AdsReloadTrigger : function(globalClicksBeforeFullbannerReload, globalClicksBeforeSkyscraperReload, globalClicksBeforeRectangleReload, reloadType, counterInstance) {
	var globalClicksBeforeFullbannerReload = globalClicksBeforeFullbannerReload;
	var globalClicksBeforeSkyscraperReload = globalClicksBeforeSkyscraperReload;
	var globalClicksBeforeRectangleReload = globalClicksBeforeRectangleReload;
	
	
	
    /** Holds the counter for this trigger.  */
    if (counterInstance) {
      this.counter = counterInstance;
    } else {// if the counter instance is not provided, use a new one.
      this.counter = new P7.Counter();
    }

    /** Registers a click in the image gallery.*/
    this.registerClick = function () {
    	var reloadAds = false;
    	var adIdArray = new Array();
    	this.counter.inc();
      /*  check if the ads should be reloaded */
      if (reloadType == "gallery") {
    	  if ((this.counter.getCount() % globalClicksBeforeFullbannerReload) == 0) {
    		  adIdArray.push("fullbanner");
    		  reloadAds = true;
    	  }
    	  if ((this.counter.getCount() % globalClicksBeforeSkyscraperReload) == 0) {
    		  adIdArray.push("skyscraper");
    		  reloadAds = true;
    	  }
    	  if ((this.counter.getCount() % globalClicksBeforeRectangleReload) == 0) {
    		  adIdArray.push("rectangle");
    		  reloadAds = true;
    	  }
      } else if (reloadType == "tabbox") {
    	  if ((this.counter.getCount() % globalClicksBeforeFullbannerReload) == 0) {
    		  adIdArray.push("fullbanner");
    		  reloadAds = true;
    	  }
    	  if ((this.counter.getCount() % globalClicksBeforeSkyscraperReload) == 0) {
    		  adIdArray.push("skyscraper");
    		  reloadAds = true;
    	  }
    	  if ((this.counter.getCount() % globalClicksBeforeRectangleReload) == 0) {
    		  adIdArray.push("rectangle");
    		  reloadAds = true;
    	  }
      } else if (reloadType == "gallery_zoom") {
    	  if ((this.counter.getCount() % globalClicksBeforeFullbannerReload) == 0) {
    		  P7.ads.galleryZoomAd.reload();
    	  }
      }
      
      if(reloadAds) {
    	  P7.ads.reload(reloadType, adIdArray);
      }
    };
  },

  Counter : function () {
    /** Holds the count in this counter. */
    this.count = 0;

    /** Increases the count in this counter by one. */
    this.inc = function() {
      this.count++;
    };

    /** Gets the count in this counter. */
    this.getCount = function () {
      return this.count;
    };

    /** Resets the count in this counter. */
    this.reset = function () {
      this.count = 0;
    };
  },

  /**
   * Ticker-Module
   */
  ticker: {
    init: function(id, link, isCP) {
      $("#tabs-"+id).tabs();
      if (isCP) {
        $('#ticker-'+id).jScrollPane({showArrows:true, ie6ScrollFix:true, fixedHeight: 417});
      } else {
        $('#ticker-'+id).jScrollPane({showArrows:true, ie6ScrollFix:true});
      }

      P7.ticker.bindClicks(id, isCP);

      $("#tabs-"+id+" a").click(function() {
        var hrefArray = $(this).attr('href').split("-");
        var index = hrefArray[2];
        var tabContent = $("#tab-"+id+"-" + index);
        if(tabContent && tabContent.children().size() == 0) {
          tabContent.load(link + "?tabElementId=" + $(this).attr('rel'), false, function() {
            if (isCP) {
              $('#ticker-'+id).jScrollPane({showArrows:true, fixedHeight: 417});
            } else {
              $('#ticker-'+id).jScrollPane({showArrows:true});
            }
            P7.ticker.bindClicks(id, isCP);
          });
        } else {
          if (isCP) {
            $('#ticker-'+id).jScrollPane({showArrows:true, fixedHeight: 417});
          } else {
            $('#ticker-'+id).jScrollPane({showArrows:true});
          }
        }
      });
    },
    bindClicks: function(id, isCP) {
      $("#ticker-"+id+" .switchable a").click(function() {
        if ($(this).parents('dt').hasClass('itemview')) {
          return true;
        }
        $("#ticker-"+id+" dt").removeClass('itemview');
        $(this).parents('dt').addClass('itemview');
        if (isCP) {
          $('#ticker-'+id).jScrollPane({showArrows:true, fixedHeight: 417});
        } else {
          $('#ticker-'+id).jScrollPane({showArrows:true});
        }
        return false;
      });
    }
  },
  mapEL: function(el){
	  unescapedUrl = unescape(el);
	  return $.base64Decode(unescapedUrl);
  },
  openEL : function(el, blankWindow) {
    if (blankWindow == 'true') {
      var viewportWidth = $(window).width();
      var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();
      window.open(P7.mapEL(el), 'w_'+Math.ceil(Math.random()*9999),
          'width='+viewportWidth+',height='+viewportHeight+',toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes');
    } else {
      window.location = P7.mapEL(el);
    }
  },
  moduleABC: {
      tabs: function(){
          $("#3tabs").tabs();
      }
  },
  moduleAZ : {
	  isLoading: true,
	  isInitialized: false,
      spinner : function(classIdSpinner, classIdTabs) {
	  		var hideThrobberFunction = function(classId) {
				var copyOfClassId = classId;
				return function(event, ui) {
					$(copyOfClassId+" .tab-loading").css("display", "none");
				};
			}(classIdSpinner);

	  		var displayThrobberFunction = function(classId) {
				var copyOfClassId = classId;
				return function(event, ui) {
					$(copyOfClassId+" .tab-loading").css("display", "block");
				};
			}(classIdSpinner);


	  		$(classIdTabs).tabs( {
			  cache: true,
			  cachedLoadEvent: true,
			  select : displayThrobberFunction,
			  load : hideThrobberFunction,
			  spinner : ''
			});

			$(classIdTabs + " a").click(function() {
			  P7.moduleAZ.isLoading = true;
			});
		},
	  paging : function(classId) {
          $(classId).pager('.page', {
              navId: 'paging4711',
              prevText: '&lsaquo; Zurück ',
              nextText: 'Weiter &rsaquo;',
              counterText: '',
              counterSeparatorText: '...',
              showPrevNext: true,
              pageSize: 1,
              type: 'number',
              showIndicator: false,
              prevNextPosition: 'outer',
              alternatePagingClass: ".page"
          });
	  }
  },
  moduleBroadcast: {
      isInitialized: false,
      configSet: false,
      config: {
		    azPath : 'azPath',
		    genrePath : 'genrePath',
	  	  highlightPath : 'highlightPath',
		    recentlyPath : 'recentlyPath'
      },

      displayBroadcastThrobber: function() {
    	  $("#broadcast-flyout-loading").css("display", "block");
      },

      hideBroadcastThrobber: function() {
    	  $("#broadcast-flyout-loading").css("display", "none");
      },

      init: function(){
          if (P7.moduleBroadcast.isInitialized) {
		  	return;
		  }
          jQuery.get(P7.moduleBroadcast.config.genrePath, function(data){
              $("#alleformate-broadcast").append(data);
              redrawSelectBoxesByParent($("#alleformate_epg"));
              var comboContainerDivs = $("#div_alleformate-broadcast_Container").children();
              if (comboContainerDivs) {
                  comboContainerDivs.each(function(i){
                      $(this).click(function(){
                          P7.moduleBroadcast.updateContentHighlights();
                          P7.moduleBroadcast.updateContentRecently(P7.moduleBroadcast.createFilterExpressionRecently());
                          P7.moduleBroadcast.updateContentAtoZ(P7.moduleBroadcast.createFilterExpressionAtoZ());
                      });
                  });
              }
          });

          $("#flyout-nav-horizontal .filter. a").click(function(){
              $("a.highlight").removeClass('highlight');
              $(this).addClass('highlight');
              P7.moduleBroadcast.updateContentAtoZ(P7.moduleBroadcast.createFilterExpressionAtoZ());
          });

          $("#flyout-nav-horizontal-recently .filter. a").click(function(){
              $("a.highlight").removeClass('highlight');
              $(this).addClass('highlight');
              P7.moduleBroadcast.updateContentRecently(P7.moduleBroadcast.createFilterExpressionRecently());
          });

          this.initNavigation();

          P7.moduleBroadcast.isInitialized = true;
      },
      createFilterExpressionRecently: function(){
          var filterExpression = "";
          var selectedAlphaFilter = $(".filter .item.recently a.highlight");
          if (selectedAlphaFilter != null && selectedAlphaFilter.size() == 1) {
              filterExpression = filterExpression + "&filter=" + selectedAlphaFilter.attr('id');
          }
          var genre = $("#alleformate-broadcast").val();
          if (genre != null) {
              filterExpression = filterExpression + "&filter2=" + genre;
          }
          return filterExpression;
      },
      createFilterExpressionAtoZ: function(){
          var filterExpression = "";
          var selectedAlphaFilter = $(".filter .item.a-z a.highlight");
          if (selectedAlphaFilter != null && selectedAlphaFilter.size() == 1) {
              filterExpression = filterExpression + "&filter=" + selectedAlphaFilter.attr('id');
          }
          var genre = $("#alleformate-broadcast").val();
          if (genre != null) {
              filterExpression = filterExpression + "&filter2=" + genre;
          }
          return filterExpression;
      },
      updateContentRecently: function(filterExpression){
    	  P7.moduleBroadcast.displayBroadcastThrobber();
          var listDisplayed = $(".contentrecently .list").css("display");
          var rasterDisplayed = $(".contentrecently .raster").css("display");
          $("#contentrecently").empty();
          jQuery.get(P7.moduleBroadcast.config.recentlyPath + filterExpression, function(data){
              $("#contentrecently").html(data);
              $(".contentrecently .list").css("display", listDisplayed);
              $(".contentrecently .raster").css("display", rasterDisplayed);

              doBoadcastFlyoutRecentlyPaging();
              P7.moduleBroadcast.hideBroadcastThrobber();
          });
      },
      updateContentAtoZ: function(filterExpression){
    	  P7.moduleBroadcast.displayBroadcastThrobber();
          var listDisplayed = $(".contenta-z .list").css("display");
          var rasterDisplayed = $(".contenta-z .raster").css("display");
          $("#contentHighlightsAtoZ").empty();
          jQuery.get(P7.moduleBroadcast.config.azPath + filterExpression, function(data){
              $("#contentHighlightsAtoZ").html(data);
              $(".contenta-z .list").css("display", listDisplayed);
              $(".contenta-z .raster").css("display", rasterDisplayed);

              doBoadcastFlyoutAtoZPaging();
              P7.moduleBroadcast.hideBroadcastThrobber();
          });
      },
      updateContentHighlights: function(){
    	  P7.moduleBroadcast.displayBroadcastThrobber();
          var genre = $('#alleformate-broadcast').val();
          var listDisplayed = $(".contenthighlights .list").css("display");
          var rasterDisplayed = $(".contenthighlights .raster").css("display");
          $("#contentHighlights").empty();

          var action = function(data){
              $("#contentHighlights").html(data);
              $(".contenthighlights .raster").css("display", rasterDisplayed);
              $(".contenthighlights .list").css("display", listDisplayed);
              doBoadcastFlyoutHighlightsPaging();
              P7.moduleBroadcast.hideBroadcastThrobber();
          };

          jQuery.get(P7.moduleBroadcast.config.highlightPath + genre, action);
      },
      initNavigation: function(){
          $("#flyout-nav a.highlights").click(function(){
              $("a.active").removeClass('active');
              $("a.highlights").addClass('active');
          });
          $("#flyout-nav a.a-z").click(function(){
              $("a.active").removeClass('active');
              $("a.a-z").addClass('active');
          });
          $("#flyout-nav a.recently").click(function(){
              $("a.active").removeClass('active');
              $("a.recently").addClass('active');
          });
      }
  },
  // hardcoded year 2004 to handle leap-years!
  moduleCalendar: {
      datePicker: function(timeStamp, uri){
          var currentTimeStamp = new Date(timeStamp);
          $("#calendar-datepicker").datepicker({
              defaultDate: new Date(timeStamp),
              firstDay: 1,
              dayNamesMin: ['','','','','','',''],
              prevText: '&lsaquo;',
              nextText: '&rsaquo;',
              showAnim: 'slideDown',
              monthNames: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'],
              additionalTop: 2,
              closeIcon: '/img/epg/datepicker_close.gif',
              dateFormat: 'dd.mm',
              minDate: new Date(2004, 0, 1),
              maxDate: new Date(2004, 11, 31),
              onSelect: function(dateText, inst){
                  var currentDate = jQuery.datepicker._getDate(inst);
                  var timestamp = jQuery.datepicker.formatDate("@", currentDate);
                  window.location.href = "" + uri + "?t=" + ((timestamp / 1000) + 43200);
              }
          });
      }
  },
  moduleGallery: {
      pagerOverview: function(id, navigationId, additions){
          $(id).pager('.page', {
              navId: navigationId,
              prevText: '&lsaquo;&lsaquo; ',
              nextText: ' &rsaquo;&rsaquo;',
              counterText: 'Bild ',
              counterSeparatorText: ' von ',
              showPrevNext: true,
              pageSize: 1,
              type: 'counter',
              showIndicator: false,
              prevNextPosition: 'inner',
              alternateCounterText: 'Seite ',
              galleryAdditions:additions
          });
      }
  },
  moduleImagebar: {
      isAccordionAnimationRunning: false,
      newInstance: function(){
          $('#accordion2 div').height(111);
          var protoInstance = {
              changeImg: function(image_folder, label){
                  if (!P7.moduleImagebar.isAccordionAnimationRunning) {
                      $('#fullimage').attr({
                          src: image_folder,
                          title: label,
                          alt: label
                      });
                  }
              },
              init: function(){
                  $("#accordion2").accordion({
                      header: "h4"
                  });
                  $("#accordion2").bind('accordionchangestart', function(event, ui){
                      P7.moduleImagebar.isAccordionAnimationRunning = true;
                  });
                  $("#accordion2").bind('accordionchange', function(event, ui){
                      P7.moduleImagebar.isAccordionAnimationRunning = false;
                  });
              }
          };
          var F = function(){
          };
          F.prototype = protoInstance;
          return new F();
      }
  },
  moduleList: {
      scrollPane: function(id){
          $(function(){
              $(id).jScrollPane({
                  showArrows: true,
                  scrollbarMargin: 0
              });
          });
      }
  },
  moduleMediaCenter : {
      embedMoviePlayer: function(flashVersion, contentId, umtsAccess){
          var flashvars = {
              embedid: 'mn_movie',
              playerEmbeds: 'mn-embeds',
              language: 'de',
              language_src: '/mediaplayer/config/languages/de_DE.resource',
              publisher: 'pro7',
              topoffset: '48',
              feedtype: 'vod',
              playertype: 'mediaplayer',
              config: '/mediaplayer/config/playerConfig.json'
          };

          var params = {
              allowScriptAccess: "always",
              wmode: "transparent",
              menu: "false",
              allowFullScreen: "true"
          };

          if (contentId && contentId != null) {
              flashvars.clip_id = contentId;
          }

          if (umtsAccess) {
        	  flashvars.maxbandwidth = '180';
        	  flashvars.moveonly = 'true';
          }

          var mn_player = new SWFObject('/mediaplayer/swf/HybridPlayer.swf', 'mn_movie', '786', '572', flashVersion);
          P7.moduleMediaCenter.embedFlash(mn_player, 'mediaplayer-container', flashvars, params);
      },
      embedFlash: function(swfObj, divId, flashVars, params){
          swfObj.useExpressInstall('/mediaplayer/swf/expressInstall.swf');

          for (var key in flashVars) {
              swfObj.addVariable(key, escape(flashVars[key]));
          }

          for (var key in params) {
              swfObj.addParam(key, params[key]);
          }

          swfObj.write(divId);
      },
      embedMediaCenter: function(flashVersion, clipId, channelId, categoryId){
          var flashvars = {
              embedid: 'mediacenter',
              playerEmbeds: 'mn-embeds',
              language: 'de',
              language_src: '/mediaplayer/config/languages/de_DE.resource',
              publisher: 'pro7',
              clip_id: clipId,
              category_id: categoryId,
              channel_id: channelId,
              feedtype: 'vod',
              configURL: '/mediaplayer/config/mcConfig.json'
          };

          var params = {
              wmode: "opaque",
              menu: "false",
              bgcolor: "#a5a5a5",
              scale: "noScale"
          };

          var mn_player = new SWFObject('/mediaplayer/swf/MediaCenter.swf', 'mediacenter', '996', '637', flashVersion);
          P7.moduleMediaCenter.embedFlash(mn_player, 'mediacenter-container', flashvars, params);
      },
      embedPagePlayer: function(args){
          var flashvars = {
              embedid: 'mn_movie',
              playerEmbeds: 'mn-embeds',
              language: 'de',
              language_src: '/mediaplayer/config/languages/de_DE.resource',
              publisher: 'pro7',
              feedtype: 'vod',
              playertype: 'pageplayer',
              config: '/mediaplayer/config/playerConfig.json'
          };

          flashvars.clip_id = args.clip_id;
          flashvars.category_id = args.category_id;
          flashvars.channel_id = args.channel_id;
          flashvars.playerarea = args.playerarea;
          flashvars.skins = args.skins;

          if(args.maxbandwidth){
        	  flashvars.maxbandwidth = args.maxbandwidth;
          }
          if(args.moveonly){
        	  flashvars.moveonly = args.moveonly;
          }

          var params = {
              allowScriptAccess: "always",
              wmode: "transparent",
              menu: "false",
              allowFullScreen: "true"
          };

          var width = $(args.widthId).width();
          var height = 1; // Is there a way to control the height of the player?
          // Set width of pageplayer-container. Videoplayer won't render correctly if it isn't set...
          $(args.containerId).width(width);

          var mn_player = new SWFObject('/mediaplayer/swf/HybridPlayer.swf', 'mn_movie', width, height, args.flashVersion);
          P7.moduleMediaCenter.embedFlash(mn_player, 'mediaplayer-container', flashvars, params);
      }
  },
  moduleMovieFinder: {
	  init : function(id) {
	  	redrawSelectBoxesByParent(id);
	  }
  },
  moduleNowOnCinema: {
      init: function(id){
          redrawSelectBoxesByParent2($(id));
      }
  },
  moduleSubTab: {
      tabs: function(){
          $("#2tabs").tabs();
      }
  },
  /**
   * EPG-Flyout
   */
  epgFlyout: {
    epgFlyoutInitialized: false,
    flyoutActive: false,
    init: function() {
      // attach to nav-item
      $("#tvprogramm").click(function() {
        if (!P7.epgFlyout.flyoutActive) {
         P7.epgFlyout.flyoutActive = true;

         if (P7.epgFlyout.epgFlyoutInitialized == false) {
           // horizontal scrollbar
           $('.flyout-programm').jScrollHorizontalPane({showArrows:true, scrollbarHeight:19, scrollbarMargin:0, arrowSize:17});

           //scroll to the current time
           var now = new Date();
           var hour = now.getHours()-6;
           var pos = hour * 180;
           $('.flyout-programm')[0].scrollTo(pos);

            //fill flyout with data
            $('.flyout-programm').epgflyout();

            P7.epgFlyout.epgFlyoutInitialized = true;
          }
        } else {
         $('#flyout-rollover-info').hide();
         P7.epgFlyout.flyoutActive = false;
        }

        return false;
      });

      //attach template div for rollover info
      $(document).ready(function() {
        var rolloverinfo = '<div id="flyout-rollover-info"></div>';
        $('body').append(rolloverinfo);

        $('#flyout-rollover-info').mouseenter(function() {
          $('#flyout-rollover-info').hide();
        });
      });

      //hide epg flyout
      $("a.close").click(function() {
        $('#flyout-rollover-info').hide();
        $(".epg-flyout").hide();
        var show = $("#menu").find('a#tvprogramm');
        $(show).removeClass('aktiv');
        return false;
      });

      //set position for epg flyout
      $('.epg-flyout').css({
        'display' : 'none',
        'left' : '16px'
      });
    }
  },
  /**
   * #p7_bglayer
   */
  pageP7BgLayerHandleResize: function() {
	$(document).ready(function(){
	  // set layer width on window load
	  $("#p7_bglayer").width($(window).width()-10);

	  // reset layer width on window resize
	  $(window).resize(function(){
	    if ($(window).width()>1042) {
	      $("#p7_bglayer").width($(window).width()-10);
	    } else {
    	  $("#p7_bglayer").width(1006);
      	}
	  });

	});
  },

  getHexColor: function(color) {
    var result;

    // Look for #a0b1c2
    if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color)) {
      return color;
    }

    // Look for #fff
    if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color)) {
      return color;
    }

    // Look for rgb(num,num,num)
    if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color)) {
      var r = parseInt(result[1], 10).toString(16);
      if (r.length == 1) r = "0" + r;
      var g = parseInt(result[2], 10).toString(16);
      if (g.length == 1) g = "0" + g;
      var b = parseInt(result[3], 10).toString(16);
      if (b.length == 1) b = "0" + b;
      return "#" + r + g + b;
    }

    return "";
  },

  /**
   * Community "Neueste Fans"
   */
  communityRecentFans: {
    widgetMode: 'allshows',
    formatWidgetId: '260964',
    homeWidgetId: '278345',
    widgetId: null,
    siteId: null,
    groupName: null,
    groupId: null,
    header: null,
    footer: null,
    imageURL: null,
    init: function(siteId, groupName, groupId, header, footer, imageURL) {
      this.siteId = siteId;
      this.groupName = groupName;
      this.groupId = groupId;
      this.header = header;
      this.footer = footer;
      this.imageURL = imageURL;

      if (groupId && groupName) {
        // Formatwelt
        this.widgetMode = 'format';
        this.widgetId = this.formatWidgetId;
      } else {
        // Home
        this.widgetId = this.homeWidgetId;
      }

      var kickapps_widgetName = 'kickWidget_' + this.siteId + '_' + this.widgetId;
      var flashvars = {
          affiliateSiteId: this.siteId,
          widgetId: this.widgetId,
          width: "154",
          height: "123",
          revision: "30",
          loadedJSCallback: "P7.communityRecentFans.widgetLoad"
      };
      if (this.widgetMode == 'format' && this.groupId) {
        flashvars.mediaURL = 'http%3A//serve.a-feed.com/service/getFeed.kickAction%3Fas%3D' + this.siteId + '%26sortType%3Drecent%26mediaType%3Duser%26groupIds%3D' + this.groupId + '%26quantity%3D6';
      }
      var params = {menu:"false", allowfullscreen:"true", allowscriptaccess:"always", wmode:"transparent"};
      var attributes = {id: kickapps_widgetName, name: kickapps_widgetName};
      var expressInstallURL = "http://serve.a-widget.com/kickFlash/scripts/expressInstall2.swf";
      var swfURL = "http://serve.a-widget.com/service/getWidgetSwf.kickAction";
      swfobject.embedSWF(swfURL, "newestMemberDiv", "154", "123", P7.flashRequiredVersion, expressInstallURL, flashvars, params, attributes);
    },
    widgetLoad: function() {
      var widget = document.getElementById('kickWidget_' + this.siteId + '_' + this.widgetId);

      var headline_property = this.widgetMode == 'format' ? 'heading' : 'title';
      var footer_property = this.widgetMode == 'format' ? 'footer' : 'Text Area 2';
      var arrow_property = 'arrow.gif';
      var background_property = this.widgetMode == 'format' ? 'background' : 'bg';

      // set font-colors based on other teasers
      var hc = undefined;
      if ($('.module-title h3 a').size() > 0) {
        hc = P7.getHexColor($('.module-title h3 a').eq(0).css('color'));
      } else if ($('.module-title h3').size() > 0) {
        hc = P7.getHexColor($('.module-title h3').eq(0).css('color'));
      }
      if (hc) {
        widget.setComponentProperty(headline_property,'fontColor',hc);
      }
      var fc = P7.getHexColor($('.module-footer a').eq(0).css('color'));
      if (fc) {
        widget.setComponentProperty(footer_property,'fontColor',fc);
      }
      // set footer arrow img
      var arrow = /url\((.*)\)/.exec($('.module-footer a.arrow').eq(0).css('background-image'));
      if (arrow && arrow[1]) {
        widget.setComponentProperty(arrow_property,'contentURL',arrow[1].replace(/\"/g,''));
        widget.setComponentProperty(arrow_property,'width','4');
        widget.setComponentProperty(arrow_property,'height','8');
        widget.setComponentProperty(arrow_property,'x','5');
        widget.setComponentProperty(arrow_property,'y','109');
      }

      if (this.header) {
        widget.setComponentProperty(headline_property,'text',this.header);
      }
      widget.setComponentProperty(headline_property,'x','3');
      widget.setComponentProperty(headline_property,'y','0');

      if (this.footer) {
        widget.setComponentProperty(footer_property,'text',this.footer);
      }
      widget.setComponentProperty(footer_property,'x','11');
      if (this.widgetMode == 'format') {
        widget.setComponentProperty(footer_property,'y','105');
      } else {
        widget.setComponentProperty(footer_property,'y','102');
      }

      if (this.imageURL) {
        if (this.groupId) {
          widget.setComponentProperty(background_property,'contentURL',this.imageURL + '/' + this.groupId + '.gif');
        } else {
          widget.setComponentProperty(background_property,'contentURL',this.imageURL + '/101390.gif');
        }
      }
    }
  },

  /**
   * Community "Neueste Postings"
   */
  communityRecentPostings: {
    widgetMode: 'allshows',
    formatWidgetId: '261021',
    homeWidgetId: '279972',
    widgetId: null,
    siteId: null,
    groupName: null,
    groupId: null,
    header: null,
    footer: null,
    imageURL: null,
    init: function(siteId, groupName, groupId, header, footer, imageURL) {
      this.siteId = siteId;
      this.groupName = groupName;
      this.groupId = groupId;
      this.header = header;
      this.footer = footer;
      this.imageURL = imageURL;

      if (groupId && groupName) {
        // Formatwelt
        this.widgetMode = 'format';
        this.widgetId = this.formatWidgetId;
      } else {
        // Home
        this.widgetId = this.homeWidgetId;
      }

      var kickapps_widgetName = 'kickWidget_' + this.siteId + '_' + this.widgetId;
      var flashvars = {
          affiliateSiteId: this.siteId,
          widgetId: this.widgetId,
          width: "154",
          height: "123",
          revision: "28",
          loadedJSCallback: "P7.communityRecentPostings.widgetLoad"
      };
      if (this.widgetMode == 'format' && this.groupId) {
        flashvars.mediaURL = 'http%3A//dev.kickapps.com/prosieben/commentFeedByGroup.php%3Fas%3D' + this.siteId + '%26clubId%3D' + this.groupId;
      }
      var params = {menu:"false", allowfullscreen:"true", allowscriptaccess:"always", wmode:"transparent"};
      var attributes = {id: kickapps_widgetName, name: kickapps_widgetName};
      var expressInstallURL = "http://serve.a-widget.com/kickFlash/scripts/expressInstall2.swf";
      var swfURL = "http://serve.a-widget.com/service/getWidgetSwf.kickAction";
      swfobject.embedSWF(swfURL, "newestPostsDiv", "154", "123", P7.flashRequiredVersion, expressInstallURL, flashvars, params, attributes);
    },
    widgetLoad: function() {
      var widget = document.getElementById('kickWidget_' + this.siteId + '_' + this.widgetId);

      // set font-colors based on other teasers
      var hc = undefined;
      if ($('.module-title h3 a').size() > 0) {
        hc = P7.getHexColor($('.module-title h3 a').eq(0).css('color'));
      } else if ($('.module-title h3').size() > 0) {
        hc = P7.getHexColor($('.module-title h3').eq(0).css('color'));
      }
      if (hc) {
        widget.setComponentProperty('heading','fontColor',hc);
      }
      var fc = P7.getHexColor($('.module-footer a').eq(0).css('color'));
      if (fc) {
        widget.setComponentProperty('footer','fontColor',fc);
      }
      // set footer arrow img
      var arrow = /url\((.*)\)/.exec($('.module-footer a.arrow').eq(0).css('background-image'));
      if (arrow && arrow[1]) {
        widget.setComponentProperty('arrow.png','contentURL',arrow[1].replace(/\"/g,''));
        widget.setComponentProperty('arrow.png','width','4');
        widget.setComponentProperty('arrow.png','height','8');
        widget.setComponentProperty('arrow.png','x','5');
        widget.setComponentProperty('arrow.png','y','109');
      }

      if (this.header) {
        widget.setComponentProperty('heading','text',this.header);
      }
      widget.setComponentProperty('heading','x','3');
      widget.setComponentProperty('heading','y','0');

      if (this.footer) {
        widget.setComponentProperty('footer','text',this.footer);
      }
      widget.setComponentProperty('footer','x','9');
      widget.setComponentProperty('footer','y','102');

      if (this.imageURL) {
        if (this.groupId) {
          widget.setComponentProperty('background','contentURL',this.imageURL + '/' + this.groupId + '.gif');
        } else {
          widget.setComponentProperty('background','contentURL',this.imageURL + '/101390.gif');
        }
        widget.setComponentProperty('background','height','123');
      }
    }
  },

  css: {
	/**
	 * Gets the CSS class of the specified element that starts with the given name.
	 *
	 * @param the element to be checked
	 * @param startingWith the beginning of the class name
	 */
	getClassStartingWith: function(element, startingWith) {
	  	var classes = $(element).attr("class");
		if (classes) {
			var classesArray = classes.split(" ");
			for ( var i = 0; i < classes.length; i++) {
				if (classesArray[i].substring(startingWith.length, 0) === startingWith) {
					return classesArray[i];
				}
			}
		}

		return undefined;
  	}
  },

  /**
   * IE6 PNG-Fix
   */
  iePngFix: function() {
    if (/MSIE 6/i.test(navigator.userAgent)) {
      var clear="/img/blank.gif";
      document.write('<script type="text/javascript" id="ct" defer="defer" src="javascript:void(0)"><\/script>');var ct=document.getElementById("ct");ct.onreadystatechange=function(){pngfix()};pngfix=function(){var els=document.getElementsByTagName('*'),ip=/\.png/i,al="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='",i=els.length,uels=new Array(),c=0;while(i-->0){if(els[i].className.match(/unitPng/)){uels[c]=els[i];c++;}}if(uels.length==0)pfx(els);else pfx(uels);function pfx(els){i=els.length;while(i-->0){var el=els[i],es=el.style,elc=el.currentStyle,elb=elc.backgroundImage;if(el.src&&el.src.match(ip)&&!es.filter){es.height=el.height;es.width=el.width;es.filter=al+el.src+"',sizingMethod='crop')";el.src=clear;}else{if(elb.match(ip)){var path=elb.split('"'),rep=(elc.backgroundRepeat=='no-repeat')?'crop':'scale',elkids=el.getElementsByTagName('*'),j=elkids.length;es.filter=al+path[1]+"',sizingMethod='"+rep+"')";es.height=el.clientHeight+'px';es.backgroundImage='none';if(j!=0){if(elc.position!="absolute")es.position='static';while(j-->0)if(!elkids[j].style.position)elkids[j].style.position="relative";}}}}}}
    }
  },

  /**
   * Style semibold links only if javascript is enabled
   */
  styleSemiboldLinks: function() {
	$(document).ready(function(){
	  $("a.semibold").css("cursor","pointer");
	});
  },
  
  /**
   * Video 2x2 Module
   */
  moduleVideo2x2: function (elementId) {
    $("#module-video2x2-"+elementId+" .video2x2-thumbimg a").click(function() {
      return false;
    });
    $("#module-video2x2-"+elementId+" .video2x2-thumbimg a").mouseover(function() {
      $("#module-video2x2-"+elementId+" .video2x2-fullimg").hide();
      $("#video2x2-"+elementId+"-" + $(this).attr("rel")).show();
      $("#module-video2x2-"+elementId+" .video2x2-thumbimg a").removeClass("active");
      $(this).addClass("active");    
      return false;    
    });
  }  
  
};

/**
 * jCarousel - Riding carousels with jQuery
 *   http://sorgalla.com/jcarousel/
 *
 * Copyright (c) 2006 Jan Sorgalla (http://sorgalla.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Built on top of the jQuery library
 *   http://jquery.com
 *
 * Inspired by the "Carousel Component" by Bill Scott
 *   http://billwscott.com/carousel/
 */

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        var self = this;

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

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

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

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

        this.funcNext   = function() { self.next(); };
        this.funcPrev   = function() { self.prev(); };
        this.funcResize = function() { self.reload(); };
        
        if (this.options.initCallback != null)            
            this.options.initCallback(this, 'init');

/* this seems to be broken with current version 4.0.3 of safari        
        if ($.browser.safari) {
            this.buttons(false, false);
            $(window).bind('load', function() { self.setup(); });
        } else
            this.setup();
*/        
        this.setup();
    };

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

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

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

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

            if (this.locked)
                return;

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

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

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

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

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

            this.setup();
        },

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

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

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

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

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

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

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

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

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

            return this.options.size;
        },

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

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

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

            return true;
        },

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

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

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

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

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

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

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

            return e;
        },

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

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

            var d = this.dimension(e);

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

            e.remove();

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

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

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

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

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

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

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

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

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

            this.animate(pos);
        },

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

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

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

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

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

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

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

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

                if (p)
                    l += d;

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

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

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

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

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

                v += d;

                if (v >= clipping)
                    break;

                j++;
            }

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

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

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

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

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

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

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

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

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

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

            return pos;
        },

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

            this.animating = true;

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

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

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

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

            this.notify('onBeforeAnimation');

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

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

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

            if (this.timer != null)
                return;

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

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

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

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

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

            var self = this;

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

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

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

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

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

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

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

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

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

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

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

            var self = this;

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

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

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

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

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

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

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

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

            return this.dimension(el);
        },

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

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

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

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

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

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

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

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

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

                return oWidth2 - oWidth;
            }

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

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

})(jQuery);
/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-09-29 01:08:25 +0100 (Sat, 29 Sep 2007) $
 * $Rev: 3493 $
 *
 * Version: @VERSION
 *
 * Requires: jQuery 1.2+
 */

(function($){
	
$.dimensions = {
	version: '@VERSION'
};

// Create innerHeight, innerWidth, outerHeight and outerWidth methods
$.each( [ 'Height', 'Width' ], function(i, name){
	
	// innerHeight and innerWidth
	$.fn[ 'inner' + name ] = function() {
		if (!this[0]) return;
		
		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right

		return num(this, name.toLowerCase()) + num(this, 'padding' + torl) + num(this, 'padding' + borr);
	};
	
	// outerHeight and outerWidth
	$.fn[ 'outer' + name ] = function(options) {
		if (!this[0]) return;
		
		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
		
		options = $.extend({ margin: false }, options || {});
		
		return num(this, name.toLowerCase())
				+ num(this, 'border' + torl + 'Width') + num(this, 'border' + borr + 'Width')
				+ num(this, 'padding' + torl) + num(this, 'padding' + borr)
				+ (options.margin ? (num(this, 'margin' + torl) + num(this, 'margin' + borr)) : 0);
	};
});

// Create scrollLeft and scrollTop methods
$.each( ['Left', 'Top'], function(i, name) {
	$.fn[ 'scroll' + name ] = function(val) {
		if (!this[0]) return;
		
		return val != undefined ?
		
			// Set the scroll offset
			this.each(function() {
				this == window || this == document ?
					window.scrollTo( 
						name == 'Left' ? val : $(window)[ 'scrollLeft' ](),
						name == 'Top'  ? val : $(window)[ 'scrollTop'  ]()
					) :
					this[ 'scroll' + name ] = val;
			}) :
			
			// Return the scroll offset
			this[0] == window || this[0] == document ?
				self[ (name == 'Left' ? 'pageXOffset' : 'pageYOffset') ] ||
					$.boxModel && document.documentElement[ 'scroll' + name ] ||
					document.body[ 'scroll' + name ] :
				this[0][ 'scroll' + name ];
	};
});

$.fn.extend({
	position: function() {
		var left = 0, top = 0, elem = this[0], offset, parentOffset, offsetParent, results;
		
		if (elem) {
			// Get *real* offsetParent
			offsetParent = this.offsetParent();
			
			// Get correct offsets
			offset       = this.offset();
			parentOffset = offsetParent.offset();
			
			// Subtract element margins
			offset.top  -= num(elem, 'marginTop');
			offset.left -= num(elem, 'marginLeft');
			
			// Add offsetParent borders
			parentOffset.top  += num(offsetParent, 'borderTopWidth');
			parentOffset.left += num(offsetParent, 'borderLeftWidth');
			
			// Subtract the two offsets
			results = {
				top:  offset.top  - parentOffset.top,
				left: offset.left - parentOffset.left
			};
		}
		
		return results;
	},
	
	offsetParent: function() {
		var offsetParent = this[0].offsetParent;
		while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && $.css(offsetParent, 'position') == 'static') )
			offsetParent = offsetParent.offsetParent;
		return $(offsetParent);
	}
});

function num(el, prop) {
	return parseInt($.css(el.jquery?el[0]:el,prop))||0;
};

})(jQuery);/*
 * Copyright (c) 2008 Threeformed Media (http://www.threeformed.com)
 * This is licensed under GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * 
 * *******
 * 
 * This plugin is derived in part from JScrollPane created by Kevin Luck(http://www.kelvinluck.com)
 * 
 * Copyright (c) 2006 Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * See http://kelvinluck.com/assets/jquery/jScrollPane/
 * $Id: jScrollPane.js 3125 2007-09-06 20:39:42Z kelvin.luck $
 */

/**
 * Replace the default horizontal scroll bars on matched 
 * elements with a CSS styled veresion.  Very similar to the JScrollPane 
 * which does vertical scrolling, 2 features in particular have been added. 
 * 
 * 1) Intervals
 * 2) Resizing
 * 
 * 1) Intervals can be added by attaching a class type of "scroll-interval" to any 
 * element wrapped within the jscrollhorizontalpane context.  This provides
 * the following abilitiies: 
 * 			a) When dragging, it will snap to the closest element on release of dragger.
 * 			b) Mousewheel motions jump between intervals
 * 			c) Notches appear by default on the scrollbar, but can be overriden by css.
 * 
 * 2) Resizing Also occurs. When turned on, all widths are dealt in percentages, so on a 
 * screen refresh, the scroller will resize itself based on it's initial percentage.
 * There are a ton of different circumstances that need to be accounted for, and i'm sure 
 * it's not meeting some people's expected behaviour so let mek now about any problems or 
 * feature requests for that!  The resizing is done through the WResize plugin.
 * 
 *
 * @example jQuery(".scroll-pane").jScrollHorizontalPane();
 *
 * @name jScrollHorizontalPane
 * @type jQuery
 * @param Object	settings	hash with options, described below.
 *								scrollbarHeight	-	The height of the generated scrollbar in pixels
 *								scrollbarMargin	-	The amount of space to leave on the side of the scrollbar in pixels
 *								wheelSpeed		-	The speed the pane will scroll in response to the mouse wheel in pixels
 *								showArrows		-	Whether to display arrows for the user to scroll with
 *								arrowSize		-	The height of the arrow buttons if showArrows=true
 *								animateTo		-	Whether to animate when calling scrollTo and scrollBy
 *								dragMinWidth	-	The minimum width to allow the drag bar to be
 *								dragMaxWidth	-	The maximum width to allow the drag bar to be
 *								animateInterval	-	The interval in milliseconds to update an animating scrollHorizontalPane (default 100)
 *								animateStep		-	The amount to divide the remaining scroll distance by when animating (default 3)
 *								maintainPosition-	Whether you want the contents of the scroll pane to maintain it's position when you re-initialise it - so it doesn't scroll as you add more content (default true)
 *								resize			- 	Whether or not to have resizing turned on or not.
 * 								minimumWidth    - 	The minimum width to allow the jScrollHorizontalPane to be resized to.  Only effective when resize is on.
 * 								reset			-	When set to 'true' all the global properties will be reset.  This is useful for dynamic refreshes on the page.
 * @return jQuery
 * @cat Plugins/jScrollHorizontalPane
 * @author Threeformed Media ( www.threeformed.com, info@threeformed.com )
 * @version 1.0.0
 */

var _jscr_originalSizes = new Array();
var _jscr_differenceSizes = new Array();
var _jscr_previousWindowSize = new Array();
var _jscr_originalPercentages = new Array();
var _jscr_intervals = new Array();
var _jscr_trackInt = new Array();
var _jscr_originalPos = new Array();
var _jscr_globalProperties = new Array();

jQuery.jScrollHorizontalPane = {
	active : []
};

jQuery.fn.jScrollHorizontalPane = function(settings)
{
	settings = jQuery.extend(
		{
			scrollbarHeight : 10,
			scrollbarMargin : 5,
			wheelSpeed : 18,
			showArrows : false,
			arrowSize : 10,
			animateTo : false,
			dragMinWidth : 1,
			dragMaxWidth : 99999,
			animateInterval : 100,
			animateStep: 3,
			maintainPosition: true, 
			resize: true,
			minimumWidth: 200,
			reset: false
		}, settings
	);
	
	return this.each(
		function()
		{
			this.testProperty = 'blast';
			 
			if(settings.reset == true) {
				jQuery.fn.jScrollHorizontalPane.reset();
			}
			
			//This holds each one of the intervals, defaulting with one at the beginning.
			var $this = jQuery(this);			
			var mouseWheelNext = 0;
			var mouseWheelMove = false;
			var currentId = $this.attr('id');
			var previousWindow = _jscr_previousWindowSize[currentId];
			_jscr_originalPos[currentId] = -1;
			_jscr_globalProperties[currentId] = settings;
			_jscr_previousWindowSize[currentId] = $(window).width();
			
			//On initial load, set values needed for percentage resizing.
			if(_jscr_originalSizes[currentId] == undefined) {		

				//ie6 hack, since jquery width doesnt get the right value on an inproper refresh
				if((jQuery.browser.msie) && (parseInt(jQuery.browser.version) == 6)) {
					var outerWidth = parseInt($this.outerWidth()) - parseInt($this.offset().left);
					_jscr_differenceSizes[currentId] = $this.offset().left / $(window).width();
				} else {
					var outerWidth = $this.outerWidth();
					_jscr_differenceSizes[currentId] = $this.position().left / $(window).width();
				}

				percentageWidth = (outerWidth / $(window).width());			
				_jscr_originalPercentages[currentId] = percentageWidth;
				_jscr_originalSizes[currentId] = $(window).width();
			} else { 
				percentageWidth = _jscr_originalPercentages[currentId];
				diff = _jscr_differenceSizes[currentId] - (($this.offset().left + _jscr_originalPos[currentId])/ $(window).width());
				percentageWidth = percentageWidth + diff;
			}

			var halfIntervals = new Array();
			_jscr_intervals = new Array();
			halfIntervals[0] = 0;
			_jscr_intervals[0] = 0;
			margin = $this.position().left;
			offset = 1;
			
			if(margin < 0) {
				margin = 0;
			}
			
			//Handles interval code
			$(".scroll-interval", $this).each(
				function(i, elem) {
					pos = $(elem).position().left - margin;
					if(pos != 0) {
						_jscr_intervals[i+offset] = pos;
					} else { 
						offset--;
					}
				}
			);
				
			if(_jscr_intervals.length <= 1) { 
				_jscr_intervals = new Array();
			}

			if (jQuery(this).parent().is('.jScrollPaneContainer')) {
				var currentScrollPosition = settings.maintainPosition ? $this.offset({relativeTo:jQuery(this).parent()[0]}).left : 0;
				var $c = jQuery(this).parent();
				var paneWidth = $c.outerWidth();
				var paneHeight = $c.innerHeight();
				var rightPos = $this.offset().left + _jscr_originalPos[currentId] + paneWidth;
				
				if((previousWindow != $(window).width()) && ((rightPos > $(window).width()) || (previousWindow < $(window).width())) && (settings.resize == true)) {

					if($(window).width() >= _jscr_originalSizes[currentId]) {
						paneWidth = ($(window).width() *  percentageWidth);
					} else {
						//Give the outside edge a 10 px buffer margin
						paneWidth = $(window).width() - ($this.offset().left + _jscr_originalPos[currentId]) - 10;
					}

					if(paneWidth < settings.minimumWidth){
						paneWidth = settings.minimumWidth;
					}

					jQuery(this).parent().css(
									{ 
										'height':paneHeight+'px', 
										'width': paneWidth + 'px'
									}
								);
				}
				
				var trackWidth = paneWidth;

				if($c.unmousewheel) {
						
					if($.browser.opera) {
						$c.unbind("mousewheel", fn = function() { });	
					} else {
						$c.unmousewheel();
					}				
				}

				jQuery('>.jScrollPaneTrack, >.jScrollArrowLeft, >.jScrollArrowRight', $c).remove();
				$this.css({'left':0});
				_jscr_originalPos[currentId] = -1;
			} else {
				var currentScrollPosition = 0;
				this.originalPadding = $this.css('paddingTop') + ' ' + $this.css('paddingRight') + ' ' + $this.css('paddingBottom') + ' ' + $this.css('paddingLeft');
				this.originalSidePaddingTotal = (parseInt($this.css('paddingLeft')) || 0) + (parseInt($this.css('paddingRight')) || 0);
				var paneWidth = $this.outerWidth();
				var rightPos = $this.offset().left + _jscr_originalPos[currentId] + paneWidth;

				if((rightPos) > $(window).width()) { 
					paneWidth = $(window).width() *  percentageWidth; 
				}
				
				if(paneWidth < settings.minimumWidth){
					paneWidth = settings.minimumWidth;
				}
					
				var paneHeight = $this.innerHeight();
				var trackWidth = paneWidth;
				
				$this.wrap(
					jQuery('<div></div>').attr(
						{'className':'jScrollPaneContainer'}
					).css(
						{
							'height':paneHeight+'px', 
							'width':paneWidth+'px'
						}
					)
				);
				// deal with text size changes (if the jquery.em plugin is included)
				// and re-initialise the scrollPane so the track maintains the
				// correct size
				jQuery(document).bind(
					'emchange', 
					function(e, cur, prev)
					{
						$this.jScrollHorizontalPane(settings);
					}
				);
			}
			var p = this.originalSidePaddingTotal;
			
			$this.css(
				{
					'height': paneHeight - settings.scrollbarHeight - p + 'px',
					'width': 'auto',
					'paddingRight':settings.scrollbarMargin + 'px'
				}
			);

			var contentWidth = $this.outerWidth();

			//ie6 and 7, outside width does not always guarantee the full size of the div
			//is returned for outerWidth
			if($.browser.msie || $.browser.opera || $.browser.safari) {
				var ieWidth = 0;
				$this.children().each(function(i, elem) { if($(elem).outerWidth() > ieWidth) { ieWidth = $(elem).outerWidth();}});
				if(ieWidth > contentWidth) {
					contentWidth = ieWidth;
				}				
			}

			var percentInView = paneWidth / contentWidth;
			var trackIntervals = new Array();

			if (percentInView < 0.99) {
				var $container = $this.parent();

				$container.append(
					jQuery('<div></div>').attr({'className':'jScrollPaneTrack'}).css({'height':settings.scrollbarHeight+'px'}).append(
						jQuery('<div></div>').attr({'className':'jScrollPaneDrag'}).css({'height':settings.scrollbarHeight+'px'}).append(
							jQuery('<div></div>').attr({'className':'jScrollPaneDragLeft'}).css({'height':settings.scrollbarHeight+'px'}),
							jQuery('<div></div>').attr({'className':'jScrollPaneDragRight'}).css({'height':settings.scrollbarHeight+'px'})
						)
					)
				);
				
				var $track = jQuery('>.jScrollPaneTrack', $container);
			
				//Attach the intervals to the track
				for(inter in _jscr_intervals) { 
					
					if(settings.showArrows == true) { 
						scrollOffset = settings.arrowSize;
					} else { 
						scrollOffset = 0;
					}

					intervalTrackPos = _jscr_intervals[inter] / contentWidth * $track.width() - (scrollOffset);
					trackIntervals[inter] = intervalTrackPos;
					
					if(trackIntervals[inter - 1] != undefined) {
						halfIntervals[inter-1] = (trackIntervals[inter] + trackIntervals[inter-1]) / 2;
					}
				
					if(inter != 0) { 
						interObj = jQuery('<div>|</div>').attr({'className':'jScrollIntervalTrack'}).css({'left':intervalTrackPos + 'px'})
						$track.append(interObj);
					}
				}

				var $drag = jQuery('>.jScrollPaneTrack .jScrollPaneDrag', $container);
				
				if (settings.showArrows) {
			
					var currentArrowButton;
					var currentArrowDirection;
					var currentArrowInterval;
					var currentArrowInc;
					var whileArrowButtonDown = function()
					{
						if (currentArrowInc > 4 || currentArrowInc%4==0) {
							positionDrag(dragPosition + currentArrowDirection * mouseWheelMultiplier);
						}
						currentArrowInc ++;
					};
					var onArrowMouseUp = function(event)
					{
						jQuery('body').unbind('mouseup', onArrowMouseUp);
						currentArrowButton.removeClass('jScrollActiveArrowButton');
						clearInterval(currentArrowInterval);
						arrowUp = true;
						moveIntervals();
					};
					var onArrowMouseDown = function() {
						jQuery('body').bind('mouseup', onArrowMouseUp);
						currentArrowButton.addClass('jScrollActiveArrowButton');
						currentArrowInc = 0;
						whileArrowButtonDown();
						currentArrowInterval = setInterval(whileArrowButtonDown, 100);
					};
					$container
						.append(
							jQuery('<a></a>')
								.attr({'href':'javascript:;', 'className':'jScrollArrowLeft'})
								.css({'width':settings.arrowSize+'px'})
								.html('Scroll Left')
								.bind('mousedown', function()
								{
									currentArrowButton = jQuery(this);
									currentArrowDirection = -1;
									onArrowMouseDown();
									this.blur();
									return false;
								}),
							jQuery('<a></a>')
								.attr({'href':'javascript:;', 'className':'jScrollArrowRight'})
								.css({'width':settings.arrowSize+'px'})
								.html('Scroll Right')
								.bind('mousedown', function()
								{
									currentArrowButton = jQuery(this);
									currentArrowDirection = 1;
									onArrowMouseDown();
									this.blur();
									return false;
								})
						);
					if (settings.arrowSize) {
						trackWidth = paneWidth - settings.arrowSize - settings.arrowSize;
						$track
							.css({'width': trackWidth+'px', left:settings.arrowSize+'px'})
					} else {
						var leftArrowWidth = jQuery('>.jScrollArrowLeft', $container).width();
						settings.arrowSize = leftArrowWidth;
						trackWidth = paneWidth - leftArrowWidth - jQuery('>.jScrollArrowRight', $container).width();
						$track
							.css({'width': trackWidth +'px', left: leftArrowWidth+'px'})
					}
				}
				
				var $pane = jQuery(this).css({'position':'absolute', 'overflow':'visible'});
				
				var currentOffset;
				var maxX;
				var mouseWheelMultiplier;
				
				// store this in a seperate variable so we can keep track more accurately than just updating the css property..
				var dragPosition = 0;
				var dragMiddle = percentInView*paneWidth/2;
				
				// pos function borrowed from tooltip plugin and adapted...
				var getPos = function (event, c) {
					var p = c == 'X' ? 'Left' : 'Bottom';
					return event['page' + c] || (event['client' + c] + (document.documentElement['scroll' + p] || document.body['scroll' + p])) || 0;
				};
				
				var ignoreNativeDrag = function() {	return false; };
				var currentInterval = 0;
				var direction = 1;
				var arrowUp = false;
				var intervalMove = false;
				_jscr_trackInt[currentId] = -1;;
						
				var initDrag = function()
				{
					ceaseAnimation();
					currentOffset = $drag.offset(false);
					currentOffset.left -= dragPosition;
					maxX = trackWidth - $drag[0].offsetWidth;
					mouseWheelMultiplier = 2 * settings.wheelSpeed * maxX / contentWidth;
				};
				
				var onStartDrag = function(event)
				{
					initDrag();
					dragMiddle = getPos(event, 'X') - dragPosition - currentOffset.left;
					jQuery('body').bind('mouseup', onStopDrag).bind('mousemove', updateScroll);
					if (jQuery.browser.msie) {
						jQuery('body').bind('dragstart', ignoreNativeDrag).bind('selectstart', ignoreNativeDrag);
					}
					return false;
				};
				var onStopDrag = function()
				{
					jQuery('body').unbind('mouseup', onStopDrag).unbind('mousemove', updateScroll);
					dragMiddle = percentInView*paneWidth/2;
					moveIntervals();
					
					if (jQuery.browser.msie) {
						jQuery('body').unbind('dragstart', ignoreNativeDrag).unbind('selectstart', ignoreNativeDrag);
					}
				};
				var positionDrag = function(destX)
				{
					//Figure out if we need to adjust because of intervals.
					evaluateIntervals(dragPosition, destX);
					destX = destX < 0 ? 0 : (destX > maxX ? maxX : destX);
					dragPosition = destX;

					$drag.css({'left':destX +'px'});
					var p = destX / maxX;
					_jscr_originalPos[currentId] = (paneWidth-contentWidth) * p * -1;
					$pane.css({'left':((paneWidth-contentWidth)*p) + 'px'});
					$this.trigger('scroll');
				};
				
				var updateScroll = function(e)
				{
					positionDrag(getPos(e, 'X') - currentOffset.left - dragMiddle);
				};
				
				var evaluateIntervals = function(position, destX) { 
	
					if((intervalMove == false) && (mouseWheelMove != true)) { 
							_jscr_trackInt[currentId] = -1;
							halfInter = -1;
							
							smallInter = -1;
							bigInter = -1;
							
							endDragPos = destX + $drag.width();
							fullTrackWidth = $('.jScrollPaneTrack').width();

							for(inter in trackIntervals) { 
								if((endDragPos >= fullTrackWidth) && (endDragPos >= trackIntervals[inter])) {
									_jscr_trackInt[currentId] = inter;
								} else if(destX >= trackIntervals[inter]) {
									smallInter = inter;
								}	else { 
									bigInter = inter;
									break;
								}
								
							}

							if(_jscr_trackInt[currentId] == -1) {
								smallDistance = destX - trackIntervals[smallInter];
								largeDistance = trackIntervals[bigInter] - destX;
								
								if(smallDistance <= largeDistance) {
									_jscr_trackInt[currentId] = smallInter;
								} else { 
									_jscr_trackInt[currentId] = bigInter;
								}
							}
					} else { 
						intervalMove = false;
					}
	
				}
				
				var moveIntervals = function() { 
					if(_jscr_trackInt[currentId] != -1) { 
						//Catching arrow clicks
						if(arrowUp == true) { 
							if((direction == -1) && (_jscr_trackInt[currentId] != 0)) { 
								_jscr_trackInt[currentId] = currentInterval - 1;
							} else if((direction == 1) && (_jscr_trackInt[currentId] != (_jscr_intervals.length -1))) {
								_jscr_trackInt[currentId] = parseInt(currentInterval) + 1;
							}
							arrowUp = false;
						} 
						
						intervalMove = true;
						positionDrag(trackIntervals[_jscr_trackInt[currentId]]);
						currentInterval = _jscr_trackInt[currentId];
					}
				}
				
				var arrowSize = 0;
				
				if(settings.showArrows == true) {
					arrowSize = settings.arrowSize;
				} 
				
				var dragH = Math.max(Math.min(percentInView*(paneWidth-arrowSize*2), settings.dragMaxWidth), settings.dragMinWidth);
				
				$drag.css(
					{'width':dragH+'px'}
				).bind('mousedown', onStartDrag);
				
				var trackScrollInterval;
				var trackScrollInc;
				var trackScrollMousePos;
				var doTrackScroll = function()
				{
					if (trackScrollInc > 8 || trackScrollInc%4==0) {
						positionDrag((dragPosition - ((dragPosition - trackScrollMousePos) / 2)));
					}
					trackScrollInc ++;
				};
				var onStopTrackClick = function()
				{
					clearInterval(trackScrollInterval);
					moveIntervals();
					jQuery('body').unbind('mouseup', onStopTrackClick).unbind('mousemove', onTrackMouseMove);
				};
				var onTrackMouseMove = function(event)
				{
					trackScrollMousePos = getPos(event, 'X') - currentOffset.left - dragMiddle;
				};
				var onTrackClick = function(event)
				{
					initDrag();
					onTrackMouseMove(event);
					trackScrollInc = 0;
					jQuery('body').bind('mouseup', onStopTrackClick).bind('mousemove', onTrackMouseMove);
					trackScrollInterval = setInterval(doTrackScroll, 100);
					doTrackScroll();
				};
				
				$track.bind('mousedown', onTrackClick);
				
				// if the mousewheel plugin has been included then also react to the mousewheel
				if ($container.mousewheel) {

					$container.mousewheel (
						function (event, delta) {
							var movePos = -1;
							
							if($.browser.opera) {
								delta = event.wheelDelta / 120;	
							}

							//The following handles intervals with the mouse wheel
							if(trackIntervals.length > 1) {
								mouseWheelMove = true;
										
								//increase or decrease the interval we are currently on, depending
								//on the direction of the mouse wheel
								if(delta < 0) {
									_jscr_trackInt[currentId] = parseInt(_jscr_trackInt[currentId]) + 1;

									if((_jscr_trackInt[currentId]) >= trackIntervals.length - 1) {
										_jscr_trackInt[currentId] = trackIntervals.length - 1;
									}
									
									//If the next interval is beyond the dragWidth then recalculate.
									if((parseInt($drag.width())+ parseInt(trackIntervals[_jscr_trackInt[currentId]])) > parseInt($('.jScrollPaneTrack').width())) {
										movePos = parseInt($('.jScrollPaneTrack').width()) - $drag.width();
									}
									
								} else { 
									_jscr_trackInt[currentId] = parseInt(_jscr_trackInt[currentId]) - 1;
									if(_jscr_trackInt[currentId] < 0) {
										_jscr_trackInt[currentId] = 0;
									}
								}
							}

							initDrag();
							ceaseAnimation();
							var d = dragPosition;
							
							//when intervals are in use, mouseWheelMove is set to true
							if(mouseWheelMove == true) {
								if(movePos == -1) {
									positionDrag(trackIntervals[_jscr_trackInt[currentId]]);
								} else {
									positionDrag(movePos);
								}
							} else {
								positionDrag(dragPosition - delta * mouseWheelMultiplier);
							}
							
							moveIntervals();
							var dragOccured = d != dragPosition;
							mouseWheelMove = false;
							return !dragOccured;
						},
						false
					);					
				}
				var _animateToPosition;
				var _animateToInterval;
				function animateToPosition()
				{

					var diff = (_animateToPosition - dragPosition) / settings.animateStep;
					
					if ((diff > 1 || diff < -1) && ((dragPosition + diff + $drag.width()) < (paneWidth))) {
						positionDrag(dragPosition + diff);
					} else {
						positionDrag(_animateToPosition);
						ceaseAnimation();
					}
				}
				var ceaseAnimation = function()
				{
					if (_animateToInterval) {
						clearInterval(_animateToInterval);
						delete _animateToPosition;
					}
				};
				var scrollTo = function(pos, preventAni)
				{
					if (typeof pos == "string") {
						$e = jQuery(pos, this);

						if (!$e.length) return;
						pos = $e.position().left;
					}

					ceaseAnimation();
					var destDragPosition = -pos/(paneWidth-contentWidth) * maxX;
					if (!preventAni || settings.animateTo) {
						_animateToPosition = destDragPosition;
						_animateToInterval = setInterval(animateToPosition, settings.animateInterval);
		
					} else {
						positionDrag(destDragPosition);
					}	
				};
				$this[0].scrollTo = scrollTo;
				
				$this[0].scrollBy = function(delta)
				{
					var currentPos = -parseInt($pane.css('left')) || 0;
					scrollTo(currentPos + delta);
				};
				
				initDrag();
				
				scrollTo(-currentScrollPosition, true);
				
				jQuery.jScrollHorizontalPane.active.push($this[0]);

			} else {
				var scrollTo = function(pos, preventAni) {}
				$this[0].scrollTo = scrollTo;
				
				$this.css(
					{
						'height':paneHeight-this.originalSidePaddingTotal+'px',
						'width': paneWidth+'px',
						'padding':this.originalPadding
					}
				);
				// remove from active list?
			}
			
		}
	)
};

jQuery.fn.jScrollHorizontalPane.reset = function() {
	_jscr_originalSizes = new Array();
	_jscr_differenceSizes = new Array();
	_jscr_previousWindowSize = new Array();
	_jscr_originalPercentages = new Array();
	_jscr_intervals = new Array();
	_jscr_trackInt = new Array();
	_jscr_originalPos = new Array();
	_jscr_globalProperties = new Array();
}

// clean up the scrollTo expandos
jQuery(window)
	.bind('unload', function() {
		var els = jQuery.jScrollHorizontalPane.active; 
		for (var i=0; i<els.length; i++) {
			els[i].scrollTo = els[i].scrollBy = null;
		}
	}
);
	
	
/*   
=============================================================================== 
WResize is the jQuery plugin for fixing the IE window resize bug 
............................................................................... 
                                               Copyright 2007 / Andrea Ercolino 
------------------------------------------------------------------------------- 
LICENSE: http://www.opensource.org/licenses/mit-license.php 
WEBSITE: http://noteslog.com/ 

------------------------------------------------------------------------------- 
USAGE: (div is automatically resized when the window is resized)
------------------------------------------------------------------------------- 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" style="overflow:hidden;"> 
<head> 
<title> test window resize </title> 
 
<script type="text/javascript" src="http://jquery.com/src/jquery-latest.pack.js"></script> 
<script type="text/javascript" src="jquery.wresize.js"></script> 
 
 
<script type="text/javascript"> 
jQuery( function( $ )  
{ 
    function content_resize()  
    { 
        var w = $( window ); 
        var H = w.height(); 
        var W = w.width(); 
        $( '#content' ).css( {width: W-20, height: H-20} ); 
    } 
 
    $( window ).wresize( content_resize ); 
 
    content_resize(); 
} ); 
</script> 
 
</head> 

<body> 
  
<div id="content" style="border: 1px dashed silver; position:absolute; overflow:auto;"> 
test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test  
</div> 
 
</body> 
</html>

=============================================================================== 
*/ 
 
( function( $ )  
{ 
 
	jQuery(function($) {
		$( window ).wresize(resizeScroller);
		
		function resizeScroller() {
		$('.scroll-pane').each(function(i, elem) { 	
			$(elem).jScrollHorizontalPane(_jscr_globalProperties[$(elem).attr('id')] );
		});
		}	
	});


    $.fn.wresize = function( f )  
    { 
        version = '1.1'; 
        wresize = {fired: false, width: 0}; 
 
        function resizeOnce()  
        { 
            if ( $.browser.msie ) 
            { 
                if ( ! wresize.fired ) 
                { 
                    wresize.fired = true; 
                } 
                else  
                { 
                    var version = parseInt( $.browser.version, 10 ); 
                    wresize.fired = false; 
                    if ( version < 7 ) 
                    { 
                        return false; 
                    } 
                    else if ( version == 7 ) 
                    { 
                        //a vertical resize is fired once, an horizontal resize twice 
                        var width = $( window ).width(); 
                        if ( width != wresize.width ) 
                        { 
                            wresize.width = width; 
                            return false; 
                        } 
                    } 
                } 
            }
 
            return true; 
        } 
 
        function handleWResize( e )  
        { 
			if ( resizeOnce() ) 
            { 
                return f.apply(this, [e]); 
            } 
        } 
 
        this.each( function()  
        { 
            if ( this == window ) 
            { 
                $( this ).resize( handleWResize ); 
            } 
            else 
            { 
                $( this ).resize( f ); 
            } 
        } ); 
 
        return this; 
    }; 
 
} ) ( jQuery );

(function($) {

	$.fn.epgflyout = function(settings) {
		// set default settings (if no settings given as param)
		var defaults = {
			// set the name of the channel we want to display as default
			p7ChannelId: 'p7',
			// set how many rows will be displayed
			shownDays: 7,
			// set the position of the default row of the current day
			positionOfCurrentDay: 2,
			// set how many days from the current day in the future are to be shown in the left day list (6 weeks)
			shownDaysInFuture: (6*7)
		};

		settings = $.extend({}, defaults, settings);

		return this.each( function () {
			var $this = $(this);

			// Instance of Carousel-Widget
			var epgflyoutDayCarouselInstance;    

      // flag is set when EPG-Flyout initializes an AJAX-Call
      var reloading = false;			
			
			/**
			 * Initialize EPG-Flyout
			 */
			function init() {
			  reloading = true;
			  				                       
				$this.ajaxStart(function(){                                           
				  if (reloading) {
				    $('#epg-flyout-loading').show();				    				     
				  }                
				});

				$this.ajaxStop(function(){                                           
				  if (reloading) {
				    $('#epg-flyout-loading').hide();
				    reloading = false;				    
				  }         
				});

				this.currentDate = new Date();
				//this.currentDate = new Date("10/01/2009"); // for debugging purposes

				this.firstDate = new Date(currentDate);
				this.firstDate.setDate(currentDate.getDate()-(settings.positionOfCurrentDay-1));

				//debug("currentDate: '"+getEPGDateString(currentDate)+"', firstDate: '"+getEPGDateString(firstDate)+"'");

				fillDateCarousel(this.currentDate);
				// create jCarousel widget for displaying days
				// see http://sorgalla.com/projects/jcarousel/ for details
				$('#dayFlyoutCarousel').jcarousel({
					vertical: true,
					scroll: (settings.shownDays-1),
					initCallback: dayCarouselInit,                  
					itemFirstInCallback: dayCarouselFirstIn
				});

				addEvents();
			}

			/**
			 * fill the dayCarousel with all dates, as set in the settings
			 * 
			 * @param currentDate the day to take as the current date
			 */
			function fillDateCarousel(currentDate) {
				/**
				 * creates something like this:
				 *  
				 * <li><span>Gestern Mi., 25.03.2009</span></li>
				 * <li><span class="now">Heute Do., 26.03.2009</span></li>
				 * <li><span>Morgen Fr., 27.03.2009</span></li>
				 * <li><span>Sa., 28.03.2009</span></li>
				 * <li><span>So., 29.03.2009</span></li>
				 */
				var html = "";
				// the schedule starts depending of which position the current day should have

				var startingDate = new Date(this.firstDate);

				// iterate through all days we want to see in the list (See settings for more explanation)
				var tempDate = new Date(startingDate);
				for (var i=0; i < (settings.shownDaysInFuture + settings.positionOfCurrentDay); i++) {
					html += "<li><span";
					if (i == settings.positionOfCurrentDay-2) {
						html += ">Gestern ";
					} else if (i == settings.positionOfCurrentDay-1 ) {
						html += ' class="now">Heute ';
					} else if (i == settings.positionOfCurrentDay) {
						html += ">Morgen ";
					} else {
						html += ">";
					}
					html += getGermanDateString(tempDate);
					html += "</span></li>\n";
					tempDate.setDate(tempDate.getDate()+1);
				}
				$('#dayFlyoutCarousel').html(html);
			}        

			/**
			 * retrieve the channelDays by ajax-request and from its XML and return it
			 * @param channel the channelId of the channel to get the data for
			 * @param date the starting date of the channelDays
			 * @param days the number of days for which to get the data
			 */
			function getAndRenderChannelDays(date, days) {
				var epgDate = getEPGDateString(date);
				var extid = "np.ct.import.day." + settings.p7ChannelId + "." + epgDate; 
				jQuery.get('/epg?days='+days+'&extId=' + extid, {}, function(xml) {        	 
					var channelDays = createEPGChannelDaysFromXml(xml);
					renderChannelDays(channelDays, date, days);
					addEvents();
				});
//				jQuery.get('/epg?days='+days+'&extId=' + extid, {}, function(channelDays) {        	 
//				renderChannelDays(channelDays, epgDate, days);
//				}, "json");
			}


			/**
			 * renders the given channelDays starting from date, till date + days
			 */
			function renderChannelDays(channelDays, date, days) {
				var tempDate = new Date(date);
				var epgDate = getEPGDateString(tempDate);
				//debug("rendering channelDays from '"+epgDate+"' + '"+days+"' days");
				var highlightclass = "";
				for (var i = 0; i < days; i++) {
					if (i % 2 == 0) {
						highlightclass = "grey";
					} else {
						highlightclass = "darkgrey";
					}
					if (datesHaveSameDay(tempDate, this.currentDate) == true) {
						highlightclass = "highlight";
					}
					renderChannelDay(channelDays[i], 'row_' + getEPGDateString(tempDate), highlightclass);

					tempDate.setDate(tempDate.getDate() + 1);
				}
			}

			/** 
			 * render the day and channel given
			 * 
			 * @param channelday the object containing all the channel data
			 * @param id the id the div will get in the DOM
			 * @param highlightclass the class to use for its style
			 */
			function renderChannelDay(channelday, id, highlightclass) {
				var html = '<div id="'+id+'" class="programm-col '+highlightclass+'">';
				if (channelday != undefined) {
				  var firstItemRendered = false;
				  for (var i=0; i<channelday.scheduleItems.length; i++) {				    
					  if (!firstItemRendered) {
	            var datesplit = channelday.scheduleItems[i].startDate.split(' ');  
	            var date = datesplit[0].split('-');                       
	            var time = datesplit[1].split(':');           
	            if (parseInt(time[0], 10) < 6) {              
	              var end = (parseInt(time[0], 10) * 60) + parseInt(time[1], 10) + parseInt(channelday.scheduleItems[i].realDuration, 10);                                          
	              if (end <= 360) {
	                // Sendungsende vor 6h => nicht anzeigen
	                continue;                
	              } else {
	                // Sendungsende nach 6h => teilweise anzeigen                               
	                var newDuration = (parseInt(end,10) - 360);                
	                channelday.scheduleItems[i].realDuration = newDuration;                
	              }
	            } else {                           
	              // Sendungsbeginn nach 6h => nach rechts schieben	              
	              var offset = 3.4 * ((time[0] * 60) + parseInt(time[1], 10) - 360);                                           
	              var offsetDiv = '<div class="epg-filler" style=" width: '+ offset +'px;"></div>';
	              html += offsetDiv;                                        
	            }           
	          }						
					  
					  html += renderScheduleItem(channelday.scheduleItems[i], firstItemRendered);     
					  firstItemRendered = true;
					}
				}
				html += '</div>';
				$('#flyout-programview').append(html);
			}

			/**
			 * Render ScheduleItem
			 * 
			 * @param item
			 * @param checkItemEnding
			 * @return
			 */
			function renderScheduleItem(item, checkItemEnding) {             			
				// startdate has the format: 'dd-mm-yy hh:mm:ss'
				// Check if program is currently running
				var datesplit = item.startDate.split(' ');  
				var date = datesplit[0].split('-');
				var time = datesplit[1].split(':');

				// yyyy, mm, dd, hh, mm, ss
				var startDate = new Date(date[0], date[1]-1, date[2], time[0], time[1], 0);
        var start = startDate.getTime();                            
				var end = start + (parseInt(item.realDuration, 10) * 60 * 1000);

        // Items nur bis 6h Folgetag anzeigen
        if (checkItemEnding) {
          var endDate = new Date(end);          
          if (startDate.getHours() < 6 && endDate.getHours() >= 6) {                        
            endDate.setHours(6);
            endDate.setMinutes(0);
            end = endDate.getTime();
            // set new Duration
            item.realDuration = (end - start) / (60 * 1000);            
          }         
        } 				
				
				var now = new Date().getTime();
				var running = (start <= now && now <= end);

				var title = item.programTitle;
				var hovertitle = datesplit[1] + " - " + item.programTitle;

				/* Breitenberechnung:
				 * 1h = 204px => 1min = 3.4px
				 * jedes Item hat 1px Border links u. rechts + 3px Margin rechts => 5px Rand                            
				 */
				
				var width = (item.realDuration * 3.4) - 5; 
				if (width < 0) {
					width = 0;
				}

				// Tooltip über komplettes Element, Text nur bei Items breiter als 26px
				var html = '<div id="'+item.externalId+'" class="flyout-programm-block" style="width:'+width+'px;">';
				if (!running) {
				  html += '<span>';
				} else {
				  html += '<span class="now">';
				}				
				if (width < 26) {
					html += '&nbsp;';    
				} else {
					html += title;
				}
				html += '</span>';
				html += '</div>';
				return html;
			}

			/**
			 * Register events for all items in a already rendered page
			 */
			function addEvents() {            
				// rollover fill and show
				$('.flyout-programm-block').mouseenter(function() {
					$(this).addClass('active');
					// fill and show info
					showFlyoutRolloverInfo($(this).attr('id'));
				});

				// move rollover info with mouse
				$('.flyout-programm-block').mousemove(function(e) {					
				  if (e.pageX < 420) {
            $('#flyout-rollover-info').css({ left: (e.pageX + 10)+'px' });
          } else {
            $('#flyout-rollover-info').css({ left: (e.pageX - 420)+'px' });
          }
					if (e.pageY < 290) {
						$('#flyout-rollover-info').css({ top: (e.pageY + 20)+'px' });
					} else {
						$('#flyout-rollover-info').css({ top: (e.pageY - 105)+'px' });
					}
				});

				// hide rollover on mouse out
				//$('.flyout-programm-block').mouseout(function() {
			  $('.flyout-programm-block').mouseleave(function() {			    
			    $(this).removeClass('active');
					$('#flyout-rollover-info').hide();    
				});			  				
			  
				// click links to TV-Programm
        var tvPageHref = $('.epg-flyout .flyout-footer a').attr('href');					
        $('.flyout-programm-block').click(function() {
          var date = $(this).parent().attr('id').replace(/row_/, "");
          var externalId = $(this).attr('id');        
          if (tvPageHref && date && externalId) {
            var url = tvPageHref + "?pdate=" + date + "&pitem=" + externalId; 
            window.location.href = url;
          }
        });
			}

			/**
			 * Callback-Function Carousel-Plugin init, will be called once widget is initialized
			 * 
			 * @param carousel
			 * @param state
			 * @return
			 */
			function dayCarouselInit(carousel, state) {
				epgflyoutDayCarouselInstance = carousel;
			}

			/**
			 * new function to be called, when the carousel is navigated
			 * 
			 */
			function dayCarouselFirstIn(carousel, item, idx, state) {
				//debug("callback called with params [carousel: '"+carousel+"' item: '"+item+"' idx: '"+idx+"' state: '"+state+"']");
				if (idx == null) {
					idx = 0;
				}
				// calculate the day to render by starting by the day given by the carousel
				var startingDate = new Date(this.firstDate);
				startingDate.setDate(this.firstDate.getDate() + idx - 1);
				// empty programview so we can fill it with fresh data 
				$('#flyout-programview').html('');
				reloading = true;
				getAndRenderChannelDays(startingDate, settings.shownDays);
			}

			/**
			 * refreshes the div containing the rollover info before displaying it to the user
			 */
			function showFlyoutRolloverInfo(externalId) {
				$('#flyout-rollover-info').html('').show();
				jQuery.get('/epg?extId=' + externalId, {}, function(xml) {        	 									  
				  var scheduleItem = createEPGScheduleItemFromXml(xml);
				  renderProgram(scheduleItem);
				});
			}

			/**
			 * renders a program for the rollover info 
			 */
			function renderProgram(scheduleItem)  {
			  if (scheduleItem != undefined) { 				
					var program = scheduleItem.program;
			    var title = (program.title != undefined)?program.title:"";
					var synopsis = (program.synopsis != undefined)?program.synopsis:"";
					var html = "";
					
	        //var imgurl = "/img/blank.gif";
					var imgurl = "";
	        if (program.image && program.image.url && program.image.contentId) {
	          imgurl = "/polopoly_fs/" + program.image.contentId + "!" + program.image.url;
	        }
					
	        if (imgurl != "") {
				//html += '<img src="' + imgurl + '" width="147" height="83" alt="" />';
	        	// the images are delivered in 148xflexible format
	        	html += '<img src="' + imgurl + '" width="148" alt="" />';
			}
			html += '<h4>'+title+'</h4><br/>';
					
	        var datesplit = scheduleItem.startDate.split(' ');  
	        html += '<h5>' + datesplit[1] + ' Uhr</h5>';															
					//html += '<h5>24.05 2009 von 20:15 - 22:25 Uhr</h5>';
					html += '<p>'+synopsis+'<br/><br/>';
					//html += '<a href="#" title="">Mehr Informationen</a>';
					html += '</p>';
					$('#flyout-rollover-info').html(html);
					//$('#flyout-rollover-info').show();
				} else {
					debug("program info not found");
				}
			}		

			init();
		}); 
	};

})(jQuery);

/**
 * Display EPG-Object details and debug-messages in Firebug Console
 */
function debug(obj) {
	if (window.console && window.console.log) {
		if (obj != undefined && obj.display) {
			window.console.log(obj.display());
		} else {
			window.console.log(obj);
		}
	}
}

function EPGGenre(contentId, name) {
	this.contentId = contentId;
	this.name = name;
	this.display = displayEPGGenre;
}

function createGenreFromElement(element) {
	if (!element) {
		return null;
	}

	return new EPGGenre(element.attr('contentid'), element.attr('name'));
}

function displayEPGGenre() {    
	return "Content id: " + this.contentId + "\nName: " + this.name + "\n";
}

function EPGImage(contentId, name, url) {
	this.contentId = contentId;
	this.name = name;
	this.url = url;
	this.display = displayEPGImage;
}

function createImageFromElement(element) {
	if (!element) {
		return null;
	}
	return new EPGImage(element.attr('contentid'), element.attr('name'), element.attr('url'));
}

function displayEPGImage() {    
	return "Content id: " + this.contentId + "\n" +
    "Name: " + this.name + "\n" +
	"Url: " + this.url + "\n";
}

function EPGVideo(contentId, name, headline, url, description, fullEpisode, previewImage) {
	this.contentId = contentId;
	this.name = name;
	this.headline = headline;
	this.url = url;
	this.description = description;
	this.fullEpisode = fullEpisode;
	this.previewImage = previewImage;
	this.display = displayEPGVideo;
}

function createVideoFromElement(element) {
	if (!element) {
		return null;
	}
	
	var image = element.find('image');

	return new EPGVideo(element.attr('contentid'), element.attr('name'), element.attr('headline'), element.attr('url'), 
			element.attr('description'), element.attr('fullepisode'),
			image ? createImageFromElement(image.eq(0)) : null);
}

function displayEPGVideo() {    
	var output = "Content id: " + this.contentId + "\n" +
	"Name: " + this.name + "\n" +
	"Headline: " + this.headline + "\n" +
	"Url: " + this.url + "\n" +
	"Description: " + this.description + "\n" +
	"Full episode: " + this.fullEpisode + "\n";

	if(this.previewImage) {
		output = output + "Preview image:\n" + this.previewImage.display();
	}

	return output;
}


function EPGIcon(linkUrl, iconSrc) {
  this.linkUrl = linkUrl;
  this.iconSrc = iconSrc;
  this.display = displayEPGIcon;
}

function displayEPGIcon() {
  return "Link URL: " + this.linkUrl + "\nIcon Src: " + this.iconSrc + "\n";
  //this.display
}

function createEPGIconFromElement(element) {
  if (!element) {
    return null;
  }  
  return new EPGIcon(element.attr('href'), element.attr('iconsrc'));   
}


function EPGProgram(contentId, externalId, name, title, originalTitle, synopsis, episodeTitle, episodeNumber, yearFrom, yearTo, moreLink, image, video, genres, icons) {
	this.contentId = contentId;
	this.externalId = externalId;
	this.name = name;    
	this.title = title;
	this.originalTitle = originalTitle;
	this.synopsis = synopsis;
	this.episodeTitle = episodeTitle;
	this.episodeNumber = episodeNumber;
	this.yearFrom = yearFrom;
	this.yearTo = yearTo;
	this.moreLink = moreLink;
	this.image = image;
	this.video = video;
	this.genres = genres;	
	this.icons = icons;	
	this.display = displayEPGProgram;	
}

function displayEPGProgram() {

	var output = "Content id: " + this.contentId + "\n" +
	"External id: " + this.externalId + "\n" +
	"Name: " + this.name + "\n" +
	"Title: " + this.title + "\n" +
	"Original title: " + this.originalTitle + "\n" +
	"Synopsis: " + this.synopsis + "\n" +
	"Episode title: " + this.episodeTitle + "\n" +
	"Episode number: " + this.episodeNumber + "\n" +
	"Production year from: " + this.yearFrom + "\n" +
	"production year to: " + this.yearTo + "\n" + 
	"More Link: " + this.moreLink + "\n";
	
	if (this.image) {
		output = output + "Image:\n" + this.image.display();
	}

	if (this.video) {
		output = output + "Video:\n" + this.video.display();
	}

	if (this.genres && this.genres.length > 0) {
		output = output + "Genres:\n";
		for (var i = 0; i < this.genres.length; i++) {        	
			output = output + "Genre:\n" + this.genres[i].display();
		}
	}
	
	if (this.icons && this.icons.length > 0) {
    output = output + "Icons:\n";
    for (var j = 0; j < this.icons.length; j++) {          
      output = output + "Icon:\n" + this.icons[j].display();
    }
  }	

	return output;
}

function createEPGProgramFromElement(element) {
	if (!element) {
		return null;
	}

	var images = element.find("images");
	var image = null;
	if (images) {
		image = images.find("image");
	}
	
	var videos = element.find("videos");
	var video = null;
	if (videos) {
		video = videos.find("video");
	}
  var arrayOfIcons = null;
  var icons = element.find("icons");
  if (icons) {
    var iconElements = icons.eq(0).find("icon");     
    if (iconElements && iconElements.size() > 0) {
      arrayOfIcons = new Array(iconElements.size());
      iconElements.each(function(i) {
        arrayOfIcons[i] = createEPGIconFromElement($(this));
      });
    }
  }		
	
	var arrayOfGenres = null;
	var genres = element.find("genres");
	if (genres) {
		var genreElements = genres.eq(0).find("genre");    	
		if (genreElements && genreElements.size() > 0) {
			arrayOfGenres = new Array(genreElements.size());
			genreElements.each(function(i) {
				arrayOfGenres[i] = createGenreFromElement($(this));
			});
		}
	}

	return new EPGProgram(element.attr('contentid'), element.attr('externalid'), element.attr('name'), 
			element.attr('title'), element.attr('original-title'), 
			element.attr('synopsis'), element.attr('episode-title'), element.attr('episode-number'),
			element.attr('production-year-from'), element.attr('production-year-to'),
			element.find("morelink").attr('href'),
			image ? createImageFromElement(image.eq(image.size()-1)) : null, 
		  video ? createVideoFromElement(video.eq(0)) : null,
		  arrayOfGenres,		  
		  arrayOfIcons);
}


function EPGScheduleItem(contentId, externalId, name, startDate, duration, realDuration, programExternalId, programTitle, program) {
	this.contentId = contentId;
	this.externalId = externalId;
	this.name = name;
	this.startDate = startDate;
	this.duration = duration;     
	this.realDuration = realDuration;
	this.programTitle = programTitle;
	this.programExternalId = programExternalId;	
	this.program = program;
	this.display = displayEPGScheduleItem;	
}

function displayEPGScheduleItem() {
	return "Content id: " + this.contentId + "\n" +
	"External id: " + this.externalId + "\n" +
	"Name: " + this.name + "\n" +
	"Start date: " + this.startDate + "\n" +
	"Duration: " + this.duration + "\n" +
	"Real duration: " + this.realDuration + "\n" +
	"Program Title: " + this.programTitle + "\n" +
	"Program External id: " + this.programExternalId + "\n" +
	"Program: " + this.program.display() + "\n";
}

function createEPGScheduleItemFromElement(element) {
	if (!element) {
		return null;
	}
	return new EPGScheduleItem(element.attr('contentid'), element.attr('externalid'), element.attr('name'), element.attr('start-date'), 
			element.attr('duration'), element.attr('realduration'), element.attr('program-externalid'), element.attr('program-title'),
	    createEPGProgramFromElement($('program', element)));
}

/**
* creates an EPGScheduleItem object from xml element
*/
function createEPGScheduleItemFromXml(xml) {
  if (!xml) {
  	return null;
  }
  var scheduleItem = $("schedule-item", xml);
  if (!scheduleItem) {
  	return null;
  }
  return createEPGScheduleItemFromElement(scheduleItem);
}

function EPGChannel(contentId, externalId, channelId, name, image) {
	this.contentId = contentId;
	this.externalId = externalId;
	this.channelId = channelId;
	this.name = name;
	this.image = image;
	this.display = displayEPGChannel;
}

function displayEPGChannel() {  
	var output = "Content id: " + this.contentId + "\n" +
	"External id: " + this.externalId + "\n" +
	"Channel id: " + this.channelId + "\n" +
	"Name: " + this.name + "\n";

	if (this.image) {
		output = output + "Image:\n" + this.image.display();
	}   

	return output;
}

function createEPGChannelsFromDepartmentXml(xml) {
	if (!xml) {
		return null;
	}
	
	var channels = $('channel', xml);
	if (!channels) {
		return null;
	}

	var channelsArray = new Array();
	channels.each( function(i) {
		channelsArray[$(this).attr('channelid')] = createChannelFromElement($(this));        
	});

	return channelsArray;
}

function createChannelFromElement(element) {
	if (!element) {
		return null;
	}
	
	var images = element.find('image');

	return new EPGChannel(element.attr('contentid'), element.attr('externalid'), element.attr('channelid'), 
			element.attr('name'), images ? createImageFromElement(images.eq(0)) : null);
}

function EPGChannelDay(contentId, date, externalId, name, channel, scheduleItems) {
	this.contentId = contentId;
	this.date = date;
	this.externalId = externalId;
	this.name = name;
	this.channel = channel;
	this.scheduleItems = scheduleItems;
	this.display = displayEPGChannelDay;
}

function displayEPGChannelDay() {

	var output = "Content id: " + this.contentId + "\n" +
    "Date: " + this.date + "\n" +
	"External id: " + this.externalId + "\n" +
	"Name: " + this.name + "\n";
	if (this.channel) {
		output = output + "Channel\n" + this.channel.display();
	}

	if (this.scheduleItems) {
		output = output + "Schedule items\n";
		for (i = 0; i < this.scheduleItems.length; i++) {
			output = output + "Schedule item\n";
			output = output + this.scheduleItems[i].display();
		}
	}

	return output;
}

function createEPGChannelDay(root) {
	var scheduleItems = $('schedule-item', root);
	var scheduleItemArray = null;
	if (scheduleItems) {
		scheduleItemArray = new Array(scheduleItems.size());
		scheduleItems.each( function(i) {
			scheduleItemArray[i] = createEPGScheduleItemFromElement($(this));               
		});
	} 

	return new EPGChannelDay(root.attr('contentid'), root.attr('date'), root.attr('externalid'), root.attr('name'),
			createChannelFromElement($('channel', root)), scheduleItemArray);	
}

function createEPGChannelDayFromXml(xml) {
	if (!xml) {
		return null;
	}

	var root = $("channelday", xml);

	if (!root) {
		return null;
	}

	return createEPGChannelDay(root);
}

function createEPGChannelDaysFromXml(xml) {
	if (!xml) {
		return null;
	}
	
	var root = $("channeldays", xml);

	if (!root) {
		return null;
	}

	var channeldays = $('channelday', root);
	var channeldayArray = null;
	if (channeldays) {
		channeldayArray = new Array(channeldays.size());
		channeldays.each( function(i) {
			channeldayArray[i] = createEPGChannelDay($(this));               
		});
	} 
	return channeldayArray;
}

/**
 * creates an EPGProgram object from xml element
 */
function createEPGProgramFromXml(xml) {
	if (!xml) {
		return null;
	}
	var programNode = $("program", xml);
	if (!programNode) {
		return null;
	}
	return createEPGProgramFromElement(programNode);
}

/**
 * returns the given date as german formatted string, e.g. "Do., 06.07.2009"
 * 
 * @param date
 */
function getGermanDateString(date) {
	// see http://docs.jquery.com/UI/Datepicker/formatDate for details 
	return $.datepicker.formatDate('D., dd.mm.yy', date);
}

/**
 * returns a string representation of the date given, e.g. "20090706"
 * 
 * @param date the date to transform
 */
function getEPGDateString(date) {
	// see http://docs.jquery.com/UI/Datepicker/formatDate for details
	return $.datepicker.formatDate('yymmdd', date);
}

/**
 * returns true if 2 dates are equal, <b>resoluting to DAY</b>.
 * 
 * @param date1
 * @param date2
 */
function datesHaveSameDay(date1, date2) {
	return (date1.getYear() == date2.getYear() &&
			date1.getMonth() == date2.getMonth() &&
			date1.getDate() == date2.getDate());
}
