var Sijax = {};

Sijax.PARAM_REQUEST = 'sijax_rq';
Sijax.PARAM_ARGS = 'sijax_args';

Sijax.requestUri = null;

Sijax.setRequestUri = function (uri) {
	Sijax.requestUri = uri;
};

Sijax.getRequestUri = function () {
	return Sijax.requestUri;
};

Sijax.setJsonUri = function (uri) {
	if (uri === null || typeof(JSON) !== "undefined") {
		return;
	}

	$.getScript(uri);
};

Sijax.processCommands = function (commandsArray) {
	$.each(commandsArray, function (idx, command) {
		var callback = Sijax.getCommandProcessor(command.type);
		callback(command);
	});
};

Sijax.getCommandProcessor = function (commandType) {
	return Sijax["process_" + commandType];
};

Sijax.process_alert = function (params) {
	window.alert(params.alert);
};

Sijax.process_html = function (params) {
	var selectorResult = $(params.selector);
	
	if (params.setType == 'replace') {
		selectorResult.html(params.html);
	} else if (params.setType == 'append') {
		selectorResult.append(params.html);
	} else {
		selectorResult.prepend(params.html);
	}
};

Sijax.process_attr = function (params) {
	var selectorResult = $(params.selector);
	
	if (params.setType === 'replace') {
		selectorResult.attr(params.key, params.value);
	} else if (params.setType === 'append') {
		selectorResult.attr(params.key, selectorResult.attr(params.key) + params.value);
	} else {
		selectorResult.attr(params.key, params.value + selectorResult.attr(params.key));
	}
};

Sijax.process_css = function (params) {
	$(params.selector).css(params.key, params.value);
};

Sijax.process_script = function (params) {
	eval(params.script);
};

Sijax.process_remove = function (params) {
	$(params.remove).remove();
};

Sijax.process_call = function (params) {
	var callbackString = params.call,
		callback = eval(callbackString);
	
	callback.apply(null, params.params);
};

Sijax.request = function (functionName, callArgs, requestParams) {
	if (callArgs === undefined) {
		callArgs = [];
	}
	
	if (requestParams === undefined) {
		requestParams = {};
	}
	
	var data = {},
		defaultRequestParams;

	data[Sijax.PARAM_REQUEST] = functionName;
	data[Sijax.PARAM_ARGS] = JSON.stringify(callArgs);
	
	defaultRequestParams = {
		"url": Sijax.requestUri,
		"type": "POST",
		"data": data,
		"cache": false,
		"dataType": "json",
		"success": Sijax.processCommands
	};
	
	$.ajax($.extend(defaultRequestParams, requestParams));
};

Sijax.getFormValues = function (formSelector) {
	var values = {},
		regexNested = /^(\w+)\[(\w+)\]$/, //<input type="text" name="name[key]" />
		regexList = /^(\w+)\[\]$/, //<input type="checkbox" name="name[]" />
		elementsSelector = formSelector + ' input, ' + formSelector + ' textarea, ' + formSelector + ' select';

	$.each($(elementsSelector), function (idx, object) {
		var attrName = $(this).attr('name'),
			attrValue = $(this).attr('value'),
			attrDisabled = $(this).attr('disabled'),
			tagName = this.tagName,
			type = $(this).attr('type'),
			nestedMatches,
			listMatches;

		if (attrName === '' || attrDisabled === true) {
			return;
		}
		
		if (tagName === 'INPUT') {
			if ((type === 'checkbox' || type === 'radio') && ! $(this).attr('checked')) {
				return;
			}
		}

		if (attrValue === "") {
			//IE's JSON.stringify doesn't like empty bare strings
			//It replaces "" with "null", unless we wrap them in a String() object
			attrValue = new String(attrValue);
		}

		//0: wholeMatch, 1: outerObjectKey, 2: innerKey
		nestedMatches = regexNested.exec(attrName);
		if (nestedMatches !== null) {
			if (values[nestedMatches[1]] === undefined) {
				values[nestedMatches[1]] = {};
			}
			values[nestedMatches[1]][nestedMatches[2]] = attrValue;
			return;
		}

		//0: wholeMatch, 1: attrNameReal
		listMatches = regexList.exec(attrName);
		if (listMatches !== null) {
			//Multiple fields with the same `name[]`..
			//The result needs to be an array of values
			var attrNameReal = listMatches[1];
			if (values[attrNameReal] === undefined || ! (values[attrNameReal] instanceof Array)) {
				values[attrNameReal] = [];
			}
			values[attrNameReal].push(attrValue);
			return;
		}

		//Regular field name, single value
		values[attrName] = attrValue;
	});

	return values;
};;

/*
 * jQuery Address Plugin v1.4
 * http://www.asual.com/jquery/address/
 *
 * Copyright (c) 2009-2010 Rostislav Hristov
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * Date: 2011-05-04 14:22:12 +0300 (Wed, 04 May 2011)
 */
(function(c){c.address=function(){var v=function(a){c(c.address).trigger(c.extend(c.Event(a),function(){for(var b={},e=c.address.parameterNames(),f=0,p=e.length;f<p;f++)b[e[f]]=c.address.parameter(e[f]);return{value:c.address.value(),path:c.address.path(),pathNames:c.address.pathNames(),parameterNames:e,parameters:b,queryString:c.address.queryString()}}.call(c.address)))},w=function(){c().bind.apply(c(c.address),Array.prototype.slice.call(arguments));return c.address},r=function(){return M.pushState&&
d.state!==k},s=function(){return("/"+g.pathname.replace(new RegExp(d.state),"")+g.search+(D()?"#"+D():"")).replace(U,"/")},D=function(){var a=g.href.indexOf("#");return a!=-1?B(g.href.substr(a+1),l):""},u=function(){return r()?s():D()},ha=function(){return"javascript"},N=function(a){a=a.toString();return(d.strict&&a.substr(0,1)!="/"?"/":"")+a},B=function(a,b){if(d.crawlable&&b)return(a!==""?"!":"")+a;return a.replace(/^\!/,"")},x=function(a,b){return parseInt(a.css(b),10)},V=function(a){for(var b,
e,f=0,p=a.childNodes.length;f<p;f++){try{if("src"in a.childNodes[f]&&a.childNodes[f].src)b=String(a.childNodes[f].src)}catch(J){}if(e=V(a.childNodes[f]))b=e}return b},F=function(){if(!K){var a=u();if(h!=a)if(y&&q<7)g.reload();else{y&&q<8&&d.history&&t(O,50);h=a;E(l)}}},E=function(a){v(W);v(a?X:Y);t(Z,10)},Z=function(){if(d.tracker!=="null"&&d.tracker!==null){var a=c.isFunction(d.tracker)?d.tracker:j[d.tracker],b=(g.pathname+g.search+(c.address&&!r()?c.address.value():"")).replace(/\/\//,"/").replace(/^\/$/,
"");if(c.isFunction(a))a(b);else if(c.isFunction(j.urchinTracker))j.urchinTracker(b);else if(j.pageTracker!==k&&c.isFunction(j.pageTracker._trackPageview))j.pageTracker._trackPageview(b);else j._gaq!==k&&c.isFunction(j._gaq.push)&&j._gaq.push(["_trackPageview",decodeURI(b)])}},O=function(){var a=ha()+":"+l+";document.open();document.writeln('<html><head><title>"+n.title.replace("'","\\'")+"</title><script>var "+C+' = "'+encodeURIComponent(u())+(n.domain!=g.hostname?'";document.domain="'+n.domain:
"")+"\";<\/script></head></html>');document.close();";if(q<7)m.src=a;else m.contentWindow.location.replace(a)},aa=function(){if(G&&$!=-1){var a,b=G.substr($+1).split("&");for(i=0;i<b.length;i++){a=b[i].split("=");if(/^(autoUpdate|crawlable|history|strict|wrap)$/.test(a[0]))d[a[0]]=isNaN(a[1])?/^(true|yes)$/i.test(a[1]):parseInt(a[1],10)!==0;if(/^(state|tracker)$/.test(a[0]))d[a[0]]=a[1]}G=null}h=u()},ca=function(){if(!ba){ba=o;aa();var a=function(){ia.call(this);ja.call(this)},b=c("body").ajaxComplete(a);
a();if(d.wrap){c("body > *").wrapAll('<div style="padding:'+(x(b,"marginTop")+x(b,"paddingTop"))+"px "+(x(b,"marginRight")+x(b,"paddingRight"))+"px "+(x(b,"marginBottom")+x(b,"paddingBottom"))+"px "+(x(b,"marginLeft")+x(b,"paddingLeft"))+'px;" />').parent().wrap('<div id="'+C+'" style="height:100%;overflow:auto;position:relative;'+(H&&!window.statusbar.visible?"resize:both;":"")+'" />');c("html, body").css({height:"100%",margin:0,padding:0,overflow:"hidden"});H&&c('<style type="text/css" />').appendTo("head").text("#"+
C+"::-webkit-resizer { background-color: #fff; }")}if(y&&q<8){a=n.getElementsByTagName("frameset")[0];m=n.createElement((a?"":"i")+"frame");if(a){a.insertAdjacentElement("beforeEnd",m);a[a.cols?"cols":"rows"]+=",0";m.noResize=o;m.frameBorder=m.frameSpacing=0}else{m.style.display="none";m.style.width=m.style.height=0;m.tabIndex=-1;n.body.insertAdjacentElement("afterBegin",m)}t(function(){c(m).bind("load",function(){var e=m.contentWindow;h=e[C]!==k?e[C]:"";if(h!=u()){E(l);g.hash=B(h,o)}});m.contentWindow[C]===
k&&O()},50)}t(function(){v("init");E(l)},1);if(!r())if(y&&q>7||!y&&"on"+I in j)if(j.addEventListener)j.addEventListener(I,F,l);else j.attachEvent&&j.attachEvent("on"+I,F);else ka(F,50)}},ia=function(){var a,b=c("a"),e=b.size(),f=-1,p=function(){if(++f!=e){a=c(b.get(f));a.is('[rel*="address:"]')&&a.address();t(p,1)}};t(p,1)},la=function(){if(h!=u()){h=u();E(l)}},ma=function(){if(j.removeEventListener)j.removeEventListener(I,F,l);else j.detachEvent&&j.detachEvent("on"+I,F)},ja=function(){if(d.crawlable){var a=
g.pathname.replace(/\/$/,"");c("body").html().indexOf("_escaped_fragment_")!=-1&&c('a[href]:not([href^=http]), a[href*="'+document.domain+'"]').each(function(){var b=c(this).attr("href").replace(/^http:/,"").replace(new RegExp(a+"/?$"),"");if(b===""||b.indexOf("_escaped_fragment_")!=-1)c(this).attr("href","#"+b.replace(/\/(.*)\?_escaped_fragment_=(.*)$/,"!$2"))})}},k,C="jQueryAddress",I="hashchange",W="change",X="internalChange",Y="externalChange",o=true,l=false,d={autoUpdate:o,crawlable:l,history:o,
strict:o,wrap:l},z=c.browser,q=parseFloat(c.browser.version),da=z.mozilla,y=z.msie,ea=z.opera,H=z.webkit||z.safari,P=l,j=function(){try{return top.document!==k?top:window}catch(a){return window}}(),n=j.document,M=j.history,g=j.location,ka=setInterval,t=setTimeout,U=/\/{2,9}/g;z=navigator.userAgent;var m,G=V(document),$=G?G.indexOf("?"):-1,Q=n.title,K=l,ba=l,R=o,fa=o,L=l,h=u();if(y){q=parseFloat(z.substr(z.indexOf("MSIE")+4));if(n.documentMode&&n.documentMode!=q)q=n.documentMode!=8?7:8;var ga=n.onpropertychange;
n.onpropertychange=function(){ga&&ga.call(n);if(n.title!=Q&&n.title.indexOf("#"+u())!=-1)n.title=Q}}if(P=da&&q>=1||y&&q>=6||ea&&q>=9.5||H&&q>=523){if(ea)history.navigationMode="compatible";if(document.readyState=="complete")var na=setInterval(function(){if(c.address){ca();clearInterval(na)}},50);else{aa();c(ca)}c(window).bind("popstate",la).bind("unload",ma)}else!P&&D()!==""?g.replace(g.href.substr(0,g.href.indexOf("#"))):Z();return{bind:function(a,b,e){return w(a,b,e)},init:function(a){return w("init",
a)},change:function(a){return w(W,a)},internalChange:function(a){return w(X,a)},externalChange:function(a){return w(Y,a)},baseURL:function(){var a=g.href;if(a.indexOf("#")!=-1)a=a.substr(0,a.indexOf("#"));if(/\/$/.test(a))a=a.substr(0,a.length-1);return a},autoUpdate:function(a){if(a!==k){d.autoUpdate=a;return this}return d.autoUpdate},crawlable:function(a){if(a!==k){d.crawlable=a;return this}return d.crawlable},history:function(a){if(a!==k){d.history=a;return this}return d.history},state:function(a){if(a!==
k){d.state=a;var b=s();if(d.state!==k)if(M.pushState)b.substr(0,3)=="/#/"&&g.replace(d.state.replace(/^\/$/,"")+b.substr(2));else b!="/"&&b.replace(/^\/#/,"")!=D()&&t(function(){g.replace(d.state.replace(/^\/$/,"")+"/#"+b)},1);return this}return d.state},strict:function(a){if(a!==k){d.strict=a;return this}return d.strict},tracker:function(a){if(a!==k){d.tracker=a;return this}return d.tracker},wrap:function(a){if(a!==k){d.wrap=a;return this}return d.wrap},update:function(){L=o;this.value(h);L=l;return this},
title:function(a){if(a!==k){t(function(){Q=n.title=a;if(fa&&m&&m.contentWindow&&m.contentWindow.document){m.contentWindow.document.title=a;fa=l}if(!R&&da)g.replace(g.href.indexOf("#")!=-1?g.href:g.href+"#");R=l},50);return this}return n.title},value:function(a){if(a!==k){a=N(a);if(a=="/")a="";if(h==a&&!L)return;R=o;h=a;if(d.autoUpdate||L){E(o);if(r())M[d.history?"pushState":"replaceState"]({},"",d.state.replace(/\/$/,"")+(h===""?"/":h));else{K=o;if(H)if(d.history)g.hash="#"+B(h,o);else g.replace("#"+
B(h,o));else if(h!=u())if(d.history)g.hash="#"+B(h,o);else g.replace("#"+B(h,o));y&&q<8&&d.history&&t(O,50);if(H)t(function(){K=l},1);else K=l}}return this}if(!P)return null;return N(h)},path:function(a){if(a!==k){var b=this.queryString(),e=this.hash();this.value(a+(b?"?"+b:"")+(e?"#"+e:""));return this}return N(h).split("#")[0].split("?")[0]},pathNames:function(){var a=this.path(),b=a.replace(U,"/").split("/");if(a.substr(0,1)=="/"||a.length===0)b.splice(0,1);a.substr(a.length-1,1)=="/"&&b.splice(b.length-
1,1);return b},queryString:function(a){if(a!==k){var b=this.hash();this.value(this.path()+(a?"?"+a:"")+(b?"#"+b:""));return this}a=h.split("?");return a.slice(1,a.length).join("?").split("#")[0]},parameter:function(a,b,e){var f,p;if(b!==k){var J=this.parameterNames();p=[];b=b?b.toString():"";for(f=0;f<J.length;f++){var S=J[f],A=this.parameter(S);if(typeof A=="string")A=[A];if(S==a)A=b===null||b===""?[]:e?A.concat([b]):[b];for(var T=0;T<A.length;T++)p.push(S+"="+A[T])}c.inArray(a,J)==-1&&b!==null&&
b!==""&&p.push(a+"="+b);this.queryString(p.join("&"));return this}if(b=this.queryString()){e=[];p=b.split("&");for(f=0;f<p.length;f++){b=p[f].split("=");b[0]==a&&e.push(b.slice(1).join("="))}if(e.length!==0)return e.length!=1?e:e[0]}},parameterNames:function(){var a=this.queryString(),b=[];if(a&&a.indexOf("=")!=-1){a=a.split("&");for(var e=0;e<a.length;e++){var f=a[e].split("=")[0];c.inArray(f,b)==-1&&b.push(f)}}return b},hash:function(a){if(a!==k){this.value(h.split("#")[0]+(a?"#"+a:""));return this}a=
h.split("#");return a.slice(1,a.length).join("#")}}}();c.fn.address=function(v){if(!c(this).attr("address")){var w=function(r){if(r.shiftKey||r.ctrlKey||r.metaKey)return true;if(c(this).is("a")){var s=v?v.call(this):/address:/.test(c(this).attr("rel"))?c(this).attr("rel").split("address:")[1].split(" ")[0]:c.address.state()!==undefined&&c.address.state()!="/"?c(this).attr("href").replace(new RegExp("^(.*"+c.address.state()+"|\\.)"),""):c(this).attr("href").replace(/^(#\!?|\.)/,"");c.address.value(s);
r.preventDefault()}};c(this).click(w).live("click",w).live("submit",function(r){if(c(this).is("form")){var s=c(this).attr("action");s=v?v.call(this):(s.indexOf("?")!=-1?s.replace(/&$/,""):s+"?")+c(this).serialize();c.address.value(s);r.preventDefault()}}).attr("address",true)}return this}})(jQuery);
;

$(function() {
    $('a.button').live({
        mousedown: function() {
          $(this).addClass('active');
        },
        blur: function() {
          $(this).removeClass('active');
        },
        mouseup: function() {
          $(this).removeClass('active');
        }
    });
});;

/**
 *
 * Date picker
 * Author: Stefan Petre www.eyecon.ro
 * 
 * Dual licensed under the MIT and GPL licenses
 * 
 */
(function ($) {
    var DatePicker = function () {
        var	ids = {},
        views = {
            years: 'datepickerViewYears',
            moths: 'datepickerViewMonths',
            days: 'datepickerViewDays'
        },
        tpl = {
            wrapper: '<div class="datepicker"><div class="datepickerBorderT" /><div class="datepickerBorderB" /><div class="datepickerBorderL" /><div class="datepickerBorderR" /><div class="datepickerBorderTL" /><div class="datepickerBorderTR" /><div class="datepickerBorderBL" /><div class="datepickerBorderBR" /><div class="datepickerContainer"><table cellspacing="0" cellpadding="0"><tbody><tr></tr></tbody></table></div></div>',
            head: [
            '<td>',
            '<table cellspacing="0" cellpadding="0">',
            '<thead>',
            '<tr>',
            '<th class="datepickerGoPrev"><a href="#"><span><%=prev%></span></a></th>',
            '<th colspan="6" class="datepickerMonth"><a href="#"><span></span></a></th>',
            '<th class="datepickerGoNext"><a href="#"><span><%=next%></span></a></th>',
            '</tr>',
            '<tr class="datepickerDoW">',
            '<th><span><%=week%></span></th>',
            '<th><span><%=day1%></span></th>',
            '<th><span><%=day2%></span></th>',
            '<th><span><%=day3%></span></th>',
            '<th><span><%=day4%></span></th>',
            '<th><span><%=day5%></span></th>',
            '<th><span><%=day6%></span></th>',
            '<th><span><%=day7%></span></th>',
            '</tr>',
            '</thead>',
            '</table></td>'
            ],
            space : '<td class="datepickerSpace"><div></div></td>',
            days: [
            '<tbody class="datepickerDays">',
            '<tr>',
            '<th class="datepickerWeek"><a href="#"><span><%=weeks[0].week%></span></a></th>',
            '<td class="<%=weeks[0].days[0].classname%>"><a href="#"><span><%=weeks[0].days[0].text%></span></a></td>',
            '<td class="<%=weeks[0].days[1].classname%>"><a href="#"><span><%=weeks[0].days[1].text%></span></a></td>',
            '<td class="<%=weeks[0].days[2].classname%>"><a href="#"><span><%=weeks[0].days[2].text%></span></a></td>',
            '<td class="<%=weeks[0].days[3].classname%>"><a href="#"><span><%=weeks[0].days[3].text%></span></a></td>',
            '<td class="<%=weeks[0].days[4].classname%>"><a href="#"><span><%=weeks[0].days[4].text%></span></a></td>',
            '<td class="<%=weeks[0].days[5].classname%>"><a href="#"><span><%=weeks[0].days[5].text%></span></a></td>',
            '<td class="<%=weeks[0].days[6].classname%>"><a href="#"><span><%=weeks[0].days[6].text%></span></a></td>',
            '</tr>',
            '<tr>',
            '<th class="datepickerWeek"><a href="#"><span><%=weeks[1].week%></span></a></th>',
            '<td class="<%=weeks[1].days[0].classname%>"><a href="#"><span><%=weeks[1].days[0].text%></span></a></td>',
            '<td class="<%=weeks[1].days[1].classname%>"><a href="#"><span><%=weeks[1].days[1].text%></span></a></td>',
            '<td class="<%=weeks[1].days[2].classname%>"><a href="#"><span><%=weeks[1].days[2].text%></span></a></td>',
            '<td class="<%=weeks[1].days[3].classname%>"><a href="#"><span><%=weeks[1].days[3].text%></span></a></td>',
            '<td class="<%=weeks[1].days[4].classname%>"><a href="#"><span><%=weeks[1].days[4].text%></span></a></td>',
            '<td class="<%=weeks[1].days[5].classname%>"><a href="#"><span><%=weeks[1].days[5].text%></span></a></td>',
            '<td class="<%=weeks[1].days[6].classname%>"><a href="#"><span><%=weeks[1].days[6].text%></span></a></td>',
            '</tr>',
            '<tr>',
            '<th class="datepickerWeek"><a href="#"><span><%=weeks[2].week%></span></a></th>',
            '<td class="<%=weeks[2].days[0].classname%>"><a href="#"><span><%=weeks[2].days[0].text%></span></a></td>',
            '<td class="<%=weeks[2].days[1].classname%>"><a href="#"><span><%=weeks[2].days[1].text%></span></a></td>',
            '<td class="<%=weeks[2].days[2].classname%>"><a href="#"><span><%=weeks[2].days[2].text%></span></a></td>',
            '<td class="<%=weeks[2].days[3].classname%>"><a href="#"><span><%=weeks[2].days[3].text%></span></a></td>',
            '<td class="<%=weeks[2].days[4].classname%>"><a href="#"><span><%=weeks[2].days[4].text%></span></a></td>',
            '<td class="<%=weeks[2].days[5].classname%>"><a href="#"><span><%=weeks[2].days[5].text%></span></a></td>',
            '<td class="<%=weeks[2].days[6].classname%>"><a href="#"><span><%=weeks[2].days[6].text%></span></a></td>',
            '</tr>',
            '<tr>',
            '<th class="datepickerWeek"><a href="#"><span><%=weeks[3].week%></span></a></th>',
            '<td class="<%=weeks[3].days[0].classname%>"><a href="#"><span><%=weeks[3].days[0].text%></span></a></td>',
            '<td class="<%=weeks[3].days[1].classname%>"><a href="#"><span><%=weeks[3].days[1].text%></span></a></td>',
            '<td class="<%=weeks[3].days[2].classname%>"><a href="#"><span><%=weeks[3].days[2].text%></span></a></td>',
            '<td class="<%=weeks[3].days[3].classname%>"><a href="#"><span><%=weeks[3].days[3].text%></span></a></td>',
            '<td class="<%=weeks[3].days[4].classname%>"><a href="#"><span><%=weeks[3].days[4].text%></span></a></td>',
            '<td class="<%=weeks[3].days[5].classname%>"><a href="#"><span><%=weeks[3].days[5].text%></span></a></td>',
            '<td class="<%=weeks[3].days[6].classname%>"><a href="#"><span><%=weeks[3].days[6].text%></span></a></td>',
            '</tr>',
            '<tr>',
            '<th class="datepickerWeek"><a href="#"><span><%=weeks[4].week%></span></a></th>',
            '<td class="<%=weeks[4].days[0].classname%>"><a href="#"><span><%=weeks[4].days[0].text%></span></a></td>',
            '<td class="<%=weeks[4].days[1].classname%>"><a href="#"><span><%=weeks[4].days[1].text%></span></a></td>',
            '<td class="<%=weeks[4].days[2].classname%>"><a href="#"><span><%=weeks[4].days[2].text%></span></a></td>',
            '<td class="<%=weeks[4].days[3].classname%>"><a href="#"><span><%=weeks[4].days[3].text%></span></a></td>',
            '<td class="<%=weeks[4].days[4].classname%>"><a href="#"><span><%=weeks[4].days[4].text%></span></a></td>',
            '<td class="<%=weeks[4].days[5].classname%>"><a href="#"><span><%=weeks[4].days[5].text%></span></a></td>',
            '<td class="<%=weeks[4].days[6].classname%>"><a href="#"><span><%=weeks[4].days[6].text%></span></a></td>',
            '</tr>',
            '<tr>',
            '<th class="datepickerWeek"><a href="#"><span><%=weeks[5].week%></span></a></th>',
            '<td class="<%=weeks[5].days[0].classname%>"><a href="#"><span><%=weeks[5].days[0].text%></span></a></td>',
            '<td class="<%=weeks[5].days[1].classname%>"><a href="#"><span><%=weeks[5].days[1].text%></span></a></td>',
            '<td class="<%=weeks[5].days[2].classname%>"><a href="#"><span><%=weeks[5].days[2].text%></span></a></td>',
            '<td class="<%=weeks[5].days[3].classname%>"><a href="#"><span><%=weeks[5].days[3].text%></span></a></td>',
            '<td class="<%=weeks[5].days[4].classname%>"><a href="#"><span><%=weeks[5].days[4].text%></span></a></td>',
            '<td class="<%=weeks[5].days[5].classname%>"><a href="#"><span><%=weeks[5].days[5].text%></span></a></td>',
            '<td class="<%=weeks[5].days[6].classname%>"><a href="#"><span><%=weeks[5].days[6].text%></span></a></td>',
            '</tr>',
            '</tbody>'
            ],
            months: [
            '<tbody class="<%=className%>">',
            '<tr>',
            '<td colspan="2"><a href="#"><span><%=data[0]%></span></a></td>',
            '<td colspan="2"><a href="#"><span><%=data[1]%></span></a></td>',
            '<td colspan="2"><a href="#"><span><%=data[2]%></span></a></td>',
            '<td colspan="2"><a href="#"><span><%=data[3]%></span></a></td>',
            '</tr>',
            '<tr>',
            '<td colspan="2"><a href="#"><span><%=data[4]%></span></a></td>',
            '<td colspan="2"><a href="#"><span><%=data[5]%></span></a></td>',
            '<td colspan="2"><a href="#"><span><%=data[6]%></span></a></td>',
            '<td colspan="2"><a href="#"><span><%=data[7]%></span></a></td>',
            '</tr>',
            '<tr>',
            '<td colspan="2"><a href="#"><span><%=data[8]%></span></a></td>',
            '<td colspan="2"><a href="#"><span><%=data[9]%></span></a></td>',
            '<td colspan="2"><a href="#"><span><%=data[10]%></span></a></td>',
            '<td colspan="2"><a href="#"><span><%=data[11]%></span></a></td>',
            '</tr>',
            '</tbody>'
            ]
        },
        defaults = {
            flat: false,
            starts: 1,
            prev: '&#9664;',
            next: '&#9654;',
            lastSel: false,
            mode: 'single',
            view: 'days',
            calendars: 1,
            format: 'Y-m-d',
            position: 'bottom',
            eventName: 'click',
            onRender: function(){
                return {};

        },
        onChange: function(){
            return true;
        },
        onShow: function(){
            return true;
        },
        onBeforeShow: function(){
            return true;
        },
        onHide: function(){
            return true;
        },
        locale: {
            days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
            daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
            daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
            months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
            monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
            weekMin: 'wk'
        }
    },
    fill = function(el) {
        var options = $(el).data('datepicker');
        var cal = $(el);
        var currentCal = Math.floor(options.calendars/2), date, data, dow, month, cnt = 0, week, days, indic, indic2, html, tblCal;
        cal.find('td>table tbody').remove();
        for (var i = 0; i < options.calendars; i++) {
            date = new Date(options.current);
            date.addMonths(-currentCal + i);
            tblCal = cal.find('table').eq(i+1);
            switch (tblCal[0].className) {
                case 'datepickerViewDays':
                    dow = formatDate(date, 'B, Y');
                    break;
                case 'datepickerViewMonths':
                    dow = date.getFullYear();
                    break;
                case 'datepickerViewYears':
                    dow = (date.getFullYear()-6) + ' - ' + (date.getFullYear()+5);
                    break;
            }
            tblCal.find('thead tr:first th:eq(1) span').text(dow);
            dow = date.getFullYear()-6;
            data = {
                data: [],
                className: 'datepickerYears'
            }
            for ( var j = 0; j < 12; j++) {
                data.data.push(dow + j);
            }
            html = tmpl(tpl.months.join(''), data);
            date.setDate(1);
            data = {
                weeks:[],
                test: 10
            };
            month = date.getMonth();
            var dow = (date.getDay() - options.starts) % 7;
            date.addDays(-(dow + (dow < 0 ? 7 : 0)));
            week = -1;
            cnt = 0;
            while (cnt < 42) {
                indic = parseInt(cnt/7,10);
                indic2 = cnt%7;
                if (!data.weeks[indic]) {
                    week = date.getWeekNumber();
                    data.weeks[indic] = {
                        week: week,
                        days: []
                    };
                }
                data.weeks[indic].days[indic2] = {
                    text: date.getDate(),
                    classname: []
                };
                if (month != date.getMonth()) {
                    data.weeks[indic].days[indic2].classname.push('datepickerNotInMonth');
                }
                if (date.getDay() == 0) {
                    data.weeks[indic].days[indic2].classname.push('datepickerSunday');
                }
                if (date.getDay() == 6) {
                    data.weeks[indic].days[indic2].classname.push('datepickerSaturday');
                }
                var fromUser = options.onRender(date);
                var val = date.valueOf();
                if (fromUser.selected || options.date == val || $.inArray(val, options.date) > -1 || (options.mode == 'range' && val >= options.date[0] && val <= options.date[1])) {
                    data.weeks[indic].days[indic2].classname.push('datepickerSelected');
                }
                if (fromUser.disabled) {
                    data.weeks[indic].days[indic2].classname.push('datepickerDisabled');
                }
                if (fromUser.className) {
                    data.weeks[indic].days[indic2].classname.push(fromUser.className);
                }
                data.weeks[indic].days[indic2].classname = data.weeks[indic].days[indic2].classname.join(' ');
                cnt++;
                date.addDays(1);
            }
            html = tmpl(tpl.days.join(''), data) + html;
            data = {
                data: options.locale.monthsShort,
                className: 'datepickerMonths'
            };
            html = tmpl(tpl.months.join(''), data) + html;
            tblCal.append(html);
        }
    },
    parseDate = function (date, format) {
        if (date.constructor == Date) {
            return new Date(date);
        }
        var parts = date.split(/\W+/);
        var against = format.split(/\W+/), d, m, y, h, min, now = new Date();
        for (var i = 0; i < parts.length; i++) {
            switch (against[i]) {
                case 'd':
                case 'e':
                    d = parseInt(parts[i],10);
                    break;
                case 'm':
                    m = parseInt(parts[i], 10)-1;
                    break;
                case 'Y':
                case 'y':
                    y = parseInt(parts[i], 10);
                    y += y > 100 ? 0 : (y < 29 ? 2000 : 1900);
                    break;
                case 'H':
                case 'I':
                case 'k':
                case 'l':
                    h = parseInt(parts[i], 10);
                    break;
                case 'P':
                case 'p':
                    if (/pm/i.test(parts[i]) && h < 12) {
                        h += 12;
                    } else if (/am/i.test(parts[i]) && h >= 12) {
                        h -= 12;
                    }
                    break;
                case 'M':
                    min = parseInt(parts[i], 10);
                    break;
            }
        }
        return new Date(
            y === undefined ? now.getFullYear() : y,
            m === undefined ? now.getMonth() : m,
            d === undefined ? now.getDate() : d,
            h === undefined ? now.getHours() : h,
            min === undefined ? now.getMinutes() : min,
            0
            );
    },
    formatDate = function(date, format) {
        var m = date.getMonth();
        var d = date.getDate();
        var y = date.getFullYear();
        var wn = date.getWeekNumber();
        var w = date.getDay();
        var s = {};
        var hr = date.getHours();
        var pm = (hr >= 12);
        var ir = (pm) ? (hr - 12) : hr;
        var dy = date.getDayOfYear();
        if (ir == 0) {
            ir = 12;
        }
        var min = date.getMinutes();
        var sec = date.getSeconds();
        var parts = format.split(''), part;
        for ( var i = 0; i < parts.length; i++ ) {
            part = parts[i];
            switch (parts[i]) {
                case 'a':
                    part = date.getDayName();
                    break;
                case 'A':
                    part = date.getDayName(true);
                    break;
                case 'b':
                    part = date.getMonthName();
                    break;
                case 'B':
                    part = date.getMonthName(true);
                    break;
                case 'C':
                    part = 1 + Math.floor(y / 100);
                    break;
                case 'd':
                    part = (d < 10) ? ("0" + d) : d;
                    break;
                case 'e':
                    part = d;
                    break;
                case 'H':
                    part = (hr < 10) ? ("0" + hr) : hr;
                    break;
                case 'I':
                    part = (ir < 10) ? ("0" + ir) : ir;
                    break;
                case 'j':
                    part = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy;
                    break;
                case 'k':
                    part = hr;
                    break;
                case 'l':
                    part = ir;
                    break;
                case 'm':
                    part = (m < 9) ? ("0" + (1+m)) : (1+m);
                    break;
                case 'M':
                    part = (min < 10) ? ("0" + min) : min;
                    break;
                case 'p':
                case 'P':
                    part = pm ? "PM" : "AM";
                    break;
                case 's':
                    part = Math.floor(date.getTime() / 1000);
                    break;
                case 'S':
                    part = (sec < 10) ? ("0" + sec) : sec;
                    break;
                case 'u':
                    part = w + 1;
                    break;
                case 'w':
                    part = w;
                    break;
                case 'y':
                    part = ('' + y).substr(2, 2);
                    break;
                case 'Y':
                    part = y;
                    break;
            }
            parts[i] = part;
        }
        return parts.join('');
    },
    extendDate = function(options) {
        if (Date.prototype.tempDate) {
            return;
        }
        Date.prototype.tempDate = null;
        Date.prototype.months = options.months;
        Date.prototype.monthsShort = options.monthsShort;
        Date.prototype.days = options.days;
        Date.prototype.daysShort = options.daysShort;
        Date.prototype.getMonthName = function(fullName) {
            return this[fullName ? 'months' : 'monthsShort'][this.getMonth()];
        };
        Date.prototype.getDayName = function(fullName) {
            return this[fullName ? 'days' : 'daysShort'][this.getDay()];
        };
        Date.prototype.addDays = function (n) {
            this.setDate(this.getDate() + n);
            this.tempDate = this.getDate();
        };
        Date.prototype.addMonths = function (n) {
            if (this.tempDate == null) {
                this.tempDate = this.getDate();
            }
            this.setDate(1);
            this.setMonth(this.getMonth() + n);
            this.setDate(Math.min(this.tempDate, this.getMaxDays()));
        };
        Date.prototype.addYears = function (n) {
            if (this.tempDate == null) {
                this.tempDate = this.getDate();
            }
            this.setDate(1);
            this.setFullYear(this.getFullYear() + n);
            this.setDate(Math.min(this.tempDate, this.getMaxDays()));
        };
        Date.prototype.getMaxDays = function() {
            var tmpDate = new Date(Date.parse(this)),
            d = 28, m;
            m = tmpDate.getMonth();
            d = 28;
            while (tmpDate.getMonth() == m) {
                d ++;
                tmpDate.setDate(d);
            }
            return d - 1;
        };
        Date.prototype.getFirstDay = function() {
            var tmpDate = new Date(Date.parse(this));
            tmpDate.setDate(1);
            return tmpDate.getDay();
        };
        Date.prototype.getWeekNumber = function() {
            var tempDate = new Date(this);
            tempDate.setDate(tempDate.getDate() - (tempDate.getDay() + 6) % 7 + 3);
            var dms = tempDate.valueOf();
            tempDate.setMonth(0);
            tempDate.setDate(4);
            return Math.round((dms - tempDate.valueOf()) / (604800000)) + 1;
        };
        Date.prototype.getDayOfYear = function() {
            var now = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
            var then = new Date(this.getFullYear(), 0, 0, 0, 0, 0);
            var time = now - then;
            return Math.floor(time / 24*60*60*1000);
        };
    },
    layout = function (el) {
        var options = $(el).data('datepicker');
        var cal = $('#' + options.id);
        if (!options.extraHeight) {
            var divs = $(el).find('div');
            options.extraHeight = divs.get(0).offsetHeight + divs.get(1).offsetHeight;
            options.extraWidth = divs.get(2).offsetWidth + divs.get(3).offsetWidth;
        }
        var tbl = cal.find('table:first').get(0);
        var width = tbl.offsetWidth;
        var height = tbl.offsetHeight;
        cal.css({
            width: width + options.extraWidth + 'px',
            height: height + options.extraHeight + 'px'
        }).find('div.datepickerContainer').css({
            width: width + 'px',
            height: height + 'px'
        });
    },
    click = function(ev) {
        if ($(ev.target).is('span')) {
            ev.target = ev.target.parentNode;
        }
        var el = $(ev.target);
        if (el.is('a')) {
            ev.target.blur();
            if (el.hasClass('datepickerDisabled')) {
                return false;
            }
            var options = $(this).data('datepicker');
            var parentEl = el.parent();
            var tblEl = parentEl.parent().parent().parent();
            var tblIndex = $('table', this).index(tblEl.get(0)) - 1;
            var tmp = new Date(options.current);
            var changed = false;
            var fillIt = false;
            if (parentEl.is('th')) {
                if (parentEl.hasClass('datepickerWeek') && options.mode == 'range' && !parentEl.next().hasClass('datepickerDisabled')) {
                    var val = parseInt(parentEl.next().text(), 10);
                    tmp.addMonths(tblIndex - Math.floor(options.calendars/2));
                    if (parentEl.next().hasClass('datepickerNotInMonth')) {
                        tmp.addMonths(val > 15 ? -1 : 1);
                    }
                    tmp.setDate(val);
                    options.date[0] = (tmp.setHours(0,0,0,0)).valueOf();
                    tmp.setHours(23,59,59,0);
                    tmp.addDays(6);
                    options.date[1] = tmp.valueOf();
                    fillIt = true;
                    changed = true;
                    options.lastSel = false;
                } else if (parentEl.hasClass('datepickerMonth')) {
                    tmp.addMonths(tblIndex - Math.floor(options.calendars/2));
                    switch (tblEl.get(0).className) {
                        case 'datepickerViewDays':
                            tblEl.get(0).className = 'datepickerViewMonths';
                            el.find('span').text(tmp.getFullYear());
                            break;
                        case 'datepickerViewMonths':
                            tblEl.get(0).className = 'datepickerViewYears';
                            el.find('span').text((tmp.getFullYear()-6) + ' - ' + (tmp.getFullYear()+5));
                            break;
                        case 'datepickerViewYears':
                            tblEl.get(0).className = 'datepickerViewDays';
                            el.find('span').text(formatDate(tmp, 'B, Y'));
                            break;
                    }
                } else if (parentEl.parent().parent().is('thead')) {
                    switch (tblEl.get(0).className) {
                        case 'datepickerViewDays':
                            options.current.addMonths(parentEl.hasClass('datepickerGoPrev') ? -1 : 1);
                            break;
                        case 'datepickerViewMonths':
                            options.current.addYears(parentEl.hasClass('datepickerGoPrev') ? -1 : 1);
                            break;
                        case 'datepickerViewYears':
                            options.current.addYears(parentEl.hasClass('datepickerGoPrev') ? -12 : 12);
                            break;
                    }
                    fillIt = true;
                }
            } else if (parentEl.is('td') && !parentEl.hasClass('datepickerDisabled')) {
                switch (tblEl.get(0).className) {
                    case 'datepickerViewMonths':
                        options.current.setMonth(tblEl.find('tbody.datepickerMonths td').index(parentEl));
                        options.current.setFullYear(parseInt(tblEl.find('thead th.datepickerMonth span').text(), 10));
                        options.current.addMonths(Math.floor(options.calendars/2) - tblIndex);
                        tblEl.get(0).className = 'datepickerViewDays';
                        break;
                    case 'datepickerViewYears':
                        options.current.setFullYear(parseInt(el.text(), 10));
                        tblEl.get(0).className = 'datepickerViewMonths';
                        break;
                    default:
                        var val = parseInt(el.text(), 10);
                        tmp.addMonths(tblIndex - Math.floor(options.calendars/2));
                        if (parentEl.hasClass('datepickerNotInMonth')) {
                            tmp.addMonths(val > 15 ? -1 : 1);
                        }
                        tmp.setDate(val);
                        switch (options.mode) {
                            case 'multiple':
                                val = (tmp.setHours(0,0,0,0)).valueOf();
                                if ($.inArray(val, options.date) > -1) {
                                    $.each(options.date, function(nr, dat){
                                        if (dat == val) {
                                            options.date.splice(nr,1);
                                            return false;
                                        }
                                    });
                                } else {
                                    options.date.push(val);
                                }
                                break;
                            case 'range':
                                if (!options.lastSel) {
                                    options.date[0] = (tmp.setHours(0,0,0,0)).valueOf();
                                }
                                val = (tmp.setHours(23,59,59,0)).valueOf();
                                if (val < options.date[0]) {
                                    options.date[1] = options.date[0] + 86399000;
                                    options.date[0] = val - 86399000;
                                } else {
                                    options.date[1] = val;
                                }
                                options.lastSel = !options.lastSel;
                                break;
                            default:
                                options.date = tmp.valueOf();
                                break;
                        }
                        break;
                }
                fillIt = true;
                changed = true;
            }
            if (fillIt) {
                fill(this);
            }
            if (changed) {
                options.onChange.apply(this, prepareDate(options));
            }
        }
        return false;
    },
    prepareDate = function (options) {
        var tmp;
        if (options.mode == 'single') {
            tmp = new Date(options.date);
            return [formatDate(tmp, options.format), tmp, options.el];
        } else {
            tmp = [[],[], options.el];
            $.each(options.date, function(nr, val){
                var date = new Date(val);
                tmp[0].push(formatDate(date, options.format));
                tmp[1].push(date);
            });
            return tmp;
        }
    },
    getViewport = function () {
        var m = document.compatMode == 'CSS1Compat';
        return {
            l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
            t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
            w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
            h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
        };
    },
    isChildOf = function(parentEl, el, container) {
        if (parentEl == el) {
            return true;
        }
        if (parentEl.contains) {
            return parentEl.contains(el);
        }
        if ( parentEl.compareDocumentPosition ) {
            return !!(parentEl.compareDocumentPosition(el) & 16);
        }
        var prEl = el.parentNode;
        while(prEl && prEl != container) {
            if (prEl == parentEl)
                return true;
            prEl = prEl.parentNode;
        }
        return false;
    },
    show = function (ev) {
        var cal = $('#' + $(this).data('datepickerId'));
        if (!cal.is(':visible')) {
            var calEl = cal.get(0);
            fill(calEl);
            var options = cal.data('datepicker');
            options.onBeforeShow.apply(this, [cal.get(0)]);
            var pos = $(this).offset();
            var viewPort = getViewport();
            var top = pos.top;
            var left = pos.left;
            var oldDisplay = $.curCSS(calEl, 'display');
            cal.css({
                visibility: 'hidden',
                display: 'block'
            });
            layout(calEl);
            switch (options.position){
                case 'top':
                    top -= calEl.offsetHeight;
                    break;
                case 'left':
                    left -= calEl.offsetWidth;
                    break;
                case 'right':
                    left += this.offsetWidth;
                    break;
                case 'bottom':
                    top += this.offsetHeight;
                    break;
            }
            if (top + calEl.offsetHeight > viewPort.t + viewPort.h) {
                top = pos.top  - calEl.offsetHeight;
            }
            if (top < viewPort.t) {
                top = pos.top + this.offsetHeight + calEl.offsetHeight;
            }
            if (left + calEl.offsetWidth > viewPort.l + viewPort.w) {
                left = pos.left - calEl.offsetWidth;
            }
            if (left < viewPort.l) {
                left = pos.left + this.offsetWidth
            }
            cal.css({
                visibility: 'visible',
                display: 'block',
                top: top + 'px',
                left: left + 'px'
            });
            if (options.onShow.apply(this, [cal.get(0)]) != false) {
                cal.show();
            }
            $(document).bind('mousedown', {
                cal: cal,
                trigger: this
            }, hide);
        }
        return false;
    },
    hide = function (ev) {
        if (ev.target != ev.data.trigger && !isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) {
            if (ev.data.cal.data('datepicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) {
                ev.data.cal.hide();
            }
            $(document).unbind('mousedown', hide);
        }
    };
    return {
        init: function(options){
            options = $.extend({}, defaults, options||{});
            extendDate(options.locale);
            options.calendars = Math.max(1, parseInt(options.calendars,10)||1);
            options.mode = /single|multiple|range/.test(options.mode) ? options.mode : 'single';
            return this.each(function(){
                if (!$(this).data('datepicker')) {
                    options.el = this;
                    if (options.date.constructor == String) {
                        options.date = parseDate(options.date, options.format);
                        options.date.setHours(0,0,0,0);
                    }
                    if (options.mode != 'single') {
                        if (options.date.constructor != Array) {
                            options.date = [options.date.valueOf()];
                            if (options.mode == 'range') {
                                options.date.push(((new Date(options.date[0])).setHours(23,59,59,0)).valueOf());
                            }
                        } else {
                            for (var i = 0; i < options.date.length; i++) {
                                options.date[i] = (parseDate(options.date[i], options.format).setHours(0,0,0,0)).valueOf();
                            }
                            if (options.mode == 'range') {
                                options.date[1] = ((new Date(options.date[1])).setHours(23,59,59,0)).valueOf();
                            }
                        }
                    } else {
                        options.date = options.date.valueOf();
                    }
                    if (!options.current) {
                        options.current = new Date();
                    } else {
                        options.current = parseDate(options.current, options.format);
                    }
                    options.current.setDate(1);
                    options.current.setHours(0,0,0,0);
                    var id = 'datepicker_' + parseInt(Math.random() * 1000), cnt;
                    options.id = id;
                    $(this).data('datepickerId', options.id);
                    var cal = $(tpl.wrapper).attr('id', id).bind('click', click).data('datepicker', options);
                    if (options.className) {
                        cal.addClass(options.className);
                    }
                    var html = '';
                    for (var i = 0; i < options.calendars; i++) {
                        cnt = options.starts;
                        if (i > 0) {
                            html += tpl.space;
                        }
                        html += tmpl(tpl.head.join(''), {
                            week: options.locale.weekMin,
                            prev: options.prev,
                            next: options.next,
                            day1: options.locale.daysMin[(cnt++)%7],
                            day2: options.locale.daysMin[(cnt++)%7],
                            day3: options.locale.daysMin[(cnt++)%7],
                            day4: options.locale.daysMin[(cnt++)%7],
                            day5: options.locale.daysMin[(cnt++)%7],
                            day6: options.locale.daysMin[(cnt++)%7],
                            day7: options.locale.daysMin[(cnt++)%7]
                        });
                    }
                    cal
                    .find('tr:first').append(html)
                    .find('table').addClass(views[options.view]);
                    fill(cal.get(0));
                    if (options.flat) {
                        cal.appendTo(this).show().css('position', 'relative');
                        layout(cal.get(0));
                    } else {
                        cal.appendTo(document.body);
                        $(this).bind(options.eventName, show);
                    }
                }
            });
        },
        showPicker: function() {
            return this.each( function () {
                if ($(this).data('datepickerId')) {
                    show.apply(this);
                }
            });
        },
        hidePicker: function() {
            return this.each( function () {
                if ($(this).data('datepickerId')) {
                    $('#' + $(this).data('datepickerId')).hide();
                }
            });
        },
        setDate: function(date, shiftTo){
            return this.each(function(){
                if ($(this).data('datepickerId')) {
                    var cal = $('#' + $(this).data('datepickerId'));
                    var options = cal.data('datepicker');
                    options.date = date;
                    if (options.date.constructor == String) {
                        options.date = parseDate(options.date, options.format);
                        options.date.setHours(0,0,0,0);
                    }
                    if (options.mode != 'single') {
                        if (options.date.constructor != Array) {
                            options.date = [options.date.valueOf()];
                            if (options.mode == 'range') {
                                options.date.push(((new Date(options.date[0])).setHours(23,59,59,0)).valueOf());
                            }
                        } else {
                            for (var i = 0; i < options.date.length; i++) {
                                options.date[i] = (parseDate(options.date[i], options.format).setHours(0,0,0,0)).valueOf();
                            }
                            if (options.mode == 'range') {
                                options.date[1] = ((new Date(options.date[1])).setHours(23,59,59,0)).valueOf();
                            }
                        }
                    } else {
                        options.date = options.date.valueOf();
                    }
                    if (shiftTo) {
                        options.current = new Date (options.mode != 'single' ? options.date[0] : options.date);
                    }
                    fill(cal.get(0));
                }
            });
        },
        getDate: function(formated) {
            if (this.size() > 0) {
                return prepareDate($('#' + $(this).data('datepickerId')).data('datepicker'))[formated ? 0 : 1];
            }
        },
        clear: function(){
            return this.each(function(){
                if ($(this).data('datepickerId')) {
                    var cal = $('#' + $(this).data('datepickerId'));
                    var options = cal.data('datepicker');
                    if (options.mode != 'single') {
                        options.date = [];
                        fill(cal.get(0));
                    }
                }
            });
        },
        fixLayout: function(){
            return this.each(function(){
                if ($(this).data('datepickerId')) {
                    var cal = $('#' + $(this).data('datepickerId'));
                    var options = cal.data('datepicker');
                    if (options.flat) {
                        layout(cal.get(0));
                    }
                }
            });
        }
    };
}();
    $.fn.extend({
        DatePicker: DatePicker.init,
        DatePickerHide: DatePicker.hidePicker,
        DatePickerShow: DatePicker.showPicker,
        DatePickerSetDate: DatePicker.setDate,
        DatePickerGetDate: DatePicker.getDate,
        DatePickerClear: DatePicker.clear,
        DatePickerLayout: DatePicker.fixLayout
    });
})(jQuery);

(function(){
    var cache = {};
 
    this.tmpl = function tmpl(str, data){
        // Figure out if we're getting a template, or if we need to
        // load the template - and be sure to cache the result.
        var fn = !/\W/.test(str) ?
        cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :
     
        // Generate a reusable function that will serve as a template
        // generator (and which will be cached).
        new Function("obj",
            "var p=[],print=function(){p.push.apply(p,arguments);};" +
       
            // Introduce the data as local variables using with(){}
            "with(obj){p.push('" +
       
            // Convert the template into pure JavaScript
            str
            .replace(/[\r\t\n]/g, " ")
            .split("<%").join("\t")
            .replace(/((^|%>)[^\t]*)'/g, "$1\r")
            .replace(/\t=(.*?)%>/g, "',$1,'")
            .split("\t").join("');")
            .split("%>").join("p.push('")
            .split("\r").join("\\'")
            + "');}return p.join('');");
   
        // Provide some basic currying to the user
        return data ? fn( data ) : fn;
    };
})();;

/*!
 * jQuery UI 1.8.1
 *
 * Copyright (c) 2010 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(c){c.ui={version:"1.8.1",plugin:{add:function(a,b,d){a=c.ui[a].prototype;for(var e in d){a.plugins[e]=a.plugins[e]||[];a.plugins[e].push([b,d[e]])}},call:function(a,b,d){if((b=a.plugins[b])&&a.element[0].parentNode)for(var e=0;e<b.length;e++)a.options[b[e][0]]&&b[e][1].apply(a.element,d)}},contains:function(a,b){return document.compareDocumentPosition?a.compareDocumentPosition(b)&16:a!==b&&a.contains(b)},hasScroll:function(a,b){if(c(a).css("overflow")=="hidden")return false;
b=b&&b=="left"?"scrollLeft":"scrollTop";var d=false;if(a[b]>0)return true;a[b]=1;d=a[b]>0;a[b]=0;return d},isOverAxis:function(a,b,d){return a>b&&a<b+d},isOver:function(a,b,d,e,f,g){return c.ui.isOverAxis(a,d,f)&&c.ui.isOverAxis(b,e,g)},keyCode:{ALT:18,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}};c.fn.extend({_focus:c.fn.focus,focus:function(a,b){return typeof a==="number"?this.each(function(){var d=this;setTimeout(function(){c(d).focus();b&&b.call(d)},a)}):this._focus.apply(this,arguments)},enableSelection:function(){return this.attr("unselectable","off").css("MozUserSelect","")},disableSelection:function(){return this.attr("unselectable","on").css("MozUserSelect","none")},scrollParent:function(){var a;a=c.browser.msie&&/(static|relative)/.test(this.css("position"))||
/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(c.curCSS(this,"position",1))&&/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0);return/fixed/.test(this.css("position"))||!a.length?c(document):a},zIndex:function(a){if(a!==
undefined)return this.css("zIndex",a);if(this.length){a=c(this[0]);for(var b;a.length&&a[0]!==document;){b=a.css("position");if(b=="absolute"||b=="relative"||b=="fixed"){b=parseInt(a.css("zIndex"));if(!isNaN(b)&&b!=0)return b}a=a.parent()}}return 0}});c.extend(c.expr[":"],{data:function(a,b,d){return!!c.data(a,d[3])},focusable:function(a){var b=a.nodeName.toLowerCase(),d=c.attr(a,"tabindex");return(/input|select|textarea|button|object/.test(b)?!a.disabled:"a"==b||"area"==b?a.href||!isNaN(d):!isNaN(d))&&
!c(a)["area"==b?"parents":"closest"](":hidden").length},tabbable:function(a){var b=c.attr(a,"tabindex");return(isNaN(b)||b>=0)&&c(a).is(":focusable")}})}(jQuery);
;/*!
 * jQuery UI Widget 1.8.1
 *
 * Copyright (c) 2010 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/Widget
 */
(function(b){var j=b.fn.remove;b.fn.remove=function(a,c){return this.each(function(){if(!c)if(!a||b.filter(a,[this]).length)b("*",this).add(this).each(function(){b(this).triggerHandler("remove")});return j.call(b(this),a,c)})};b.widget=function(a,c,d){var e=a.split(".")[0],f;a=a.split(".")[1];f=e+"-"+a;if(!d){d=c;c=b.Widget}b.expr[":"][f]=function(h){return!!b.data(h,a)};b[e]=b[e]||{};b[e][a]=function(h,g){arguments.length&&this._createWidget(h,g)};c=new c;c.options=b.extend({},c.options);b[e][a].prototype=
b.extend(true,c,{namespace:e,widgetName:a,widgetEventPrefix:b[e][a].prototype.widgetEventPrefix||a,widgetBaseClass:f},d);b.widget.bridge(a,b[e][a])};b.widget.bridge=function(a,c){b.fn[a]=function(d){var e=typeof d==="string",f=Array.prototype.slice.call(arguments,1),h=this;d=!e&&f.length?b.extend.apply(null,[true,d].concat(f)):d;if(e&&d.substring(0,1)==="_")return h;e?this.each(function(){var g=b.data(this,a),i=g&&b.isFunction(g[d])?g[d].apply(g,f):g;if(i!==g&&i!==undefined){h=i;return false}}):this.each(function(){var g=
b.data(this,a);if(g){d&&g.option(d);g._init()}else b.data(this,a,new c(d,this))});return h}};b.Widget=function(a,c){arguments.length&&this._createWidget(a,c)};b.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:false},_createWidget:function(a,c){this.element=b(c).data(this.widgetName,this);this.options=b.extend(true,{},this.options,b.metadata&&b.metadata.get(c)[this.widgetName],a);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()});this._create();
this._init()},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},widget:function(){return this.element},option:function(a,c){var d=a,e=this;if(arguments.length===0)return b.extend({},e.options);if(typeof a==="string"){if(c===undefined)return this.options[a];d={};d[a]=c}b.each(d,function(f,
h){e._setOption(f,h)});return e},_setOption:function(a,c){this.options[a]=c;if(a==="disabled")this.widget()[c?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",c);return this},enable:function(){return this._setOption("disabled",false)},disable:function(){return this._setOption("disabled",true)},_trigger:function(a,c,d){var e=this.options[a];c=b.Event(c);c.type=(a===this.widgetEventPrefix?a:this.widgetEventPrefix+a).toLowerCase();d=d||{};if(c.originalEvent){a=
b.event.props.length;for(var f;a;){f=b.event.props[--a];c[f]=c.originalEvent[f]}}this.element.trigger(c,d);return!(b.isFunction(e)&&e.call(this.element[0],c,d)===false||c.isDefaultPrevented())}}})(jQuery);
;/*!
 * jQuery UI Mouse 1.8.1
 *
 * Copyright (c) 2010 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/Mouse
 *
 * Depends:
 *	jquery.ui.widget.js
 */
(function(c){c.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var a=this;this.element.bind("mousedown."+this.widgetName,function(b){return a._mouseDown(b)}).bind("click."+this.widgetName,function(b){if(a._preventClickEvent){a._preventClickEvent=false;b.stopImmediatePropagation();return false}});this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName)},_mouseDown:function(a){a.originalEvent=a.originalEvent||{};if(!a.originalEvent.mouseHandled){this._mouseStarted&&
this._mouseUp(a);this._mouseDownEvent=a;var b=this,e=a.which==1,f=typeof this.options.cancel=="string"?c(a.target).parents().add(a.target).filter(this.options.cancel).length:false;if(!e||f||!this._mouseCapture(a))return true;this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet)this._mouseDelayTimer=setTimeout(function(){b.mouseDelayMet=true},this.options.delay);if(this._mouseDistanceMet(a)&&this._mouseDelayMet(a)){this._mouseStarted=this._mouseStart(a)!==false;if(!this._mouseStarted){a.preventDefault();
return true}}this._mouseMoveDelegate=function(d){return b._mouseMove(d)};this._mouseUpDelegate=function(d){return b._mouseUp(d)};c(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);c.browser.safari||a.preventDefault();return a.originalEvent.mouseHandled=true}},_mouseMove:function(a){if(c.browser.msie&&!a.button)return this._mouseUp(a);if(this._mouseStarted){this._mouseDrag(a);return a.preventDefault()}if(this._mouseDistanceMet(a)&&
this._mouseDelayMet(a))(this._mouseStarted=this._mouseStart(this._mouseDownEvent,a)!==false)?this._mouseDrag(a):this._mouseUp(a);return!this._mouseStarted},_mouseUp:function(a){c(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;this._preventClickEvent=a.target==this._mouseDownEvent.target;this._mouseStop(a)}return false},_mouseDistanceMet:function(a){return Math.max(Math.abs(this._mouseDownEvent.pageX-
a.pageX),Math.abs(this._mouseDownEvent.pageY-a.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return true}})})(jQuery);
;/*
 * jQuery UI Slider 1.8.1
 *
 * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Slider
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.mouse.js
 *	jquery.ui.widget.js
 */
(function(d){d.widget("ui.slider",d.ui.mouse,{widgetEventPrefix:"slide",options:{animate:false,distance:0,max:100,min:0,orientation:"horizontal",range:false,step:1,value:0,values:null},_create:function(){var b=this,a=this.options;this._mouseSliding=this._keySliding=false;this._animateOff=true;this._handleIndex=null;this._detectOrientation();this._mouseInit();this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget ui-widget-content ui-corner-all");a.disabled&&this.element.addClass("ui-slider-disabled ui-disabled");
this.range=d([]);if(a.range){if(a.range===true){this.range=d("<div></div>");if(!a.values)a.values=[this._valueMin(),this._valueMin()];if(a.values.length&&a.values.length!==2)a.values=[a.values[0],a.values[0]]}else this.range=d("<div></div>");this.range.appendTo(this.element).addClass("ui-slider-range");if(a.range==="min"||a.range==="max")this.range.addClass("ui-slider-range-"+a.range);this.range.addClass("ui-widget-header")}d(".ui-slider-handle",this.element).length===0&&d("<a href='#'></a>").appendTo(this.element).addClass("ui-slider-handle");
if(a.values&&a.values.length)for(;d(".ui-slider-handle",this.element).length<a.values.length;)d("<a href='#'></a>").appendTo(this.element).addClass("ui-slider-handle");this.handles=d(".ui-slider-handle",this.element).addClass("ui-state-default ui-corner-all");this.handle=this.handles.eq(0);this.handles.add(this.range).filter("a").click(function(c){c.preventDefault()}).hover(function(){a.disabled||d(this).addClass("ui-state-hover")},function(){d(this).removeClass("ui-state-hover")}).focus(function(){if(a.disabled)d(this).blur();
else{d(".ui-slider .ui-state-focus").removeClass("ui-state-focus");d(this).addClass("ui-state-focus")}}).blur(function(){d(this).removeClass("ui-state-focus")});this.handles.each(function(c){d(this).data("index.ui-slider-handle",c)});this.handles.keydown(function(c){var e=true,f=d(this).data("index.ui-slider-handle"),g,h,i;if(!b.options.disabled){switch(c.keyCode){case d.ui.keyCode.HOME:case d.ui.keyCode.END:case d.ui.keyCode.PAGE_UP:case d.ui.keyCode.PAGE_DOWN:case d.ui.keyCode.UP:case d.ui.keyCode.RIGHT:case d.ui.keyCode.DOWN:case d.ui.keyCode.LEFT:e=
false;if(!b._keySliding){b._keySliding=true;d(this).addClass("ui-state-active");g=b._start(c,f);if(g===false)return}break}i=b.options.step;g=b.options.values&&b.options.values.length?(h=b.values(f)):(h=b.value());switch(c.keyCode){case d.ui.keyCode.HOME:h=b._valueMin();break;case d.ui.keyCode.END:h=b._valueMax();break;case d.ui.keyCode.PAGE_UP:h=g+(b._valueMax()-b._valueMin())/5;break;case d.ui.keyCode.PAGE_DOWN:h=g-(b._valueMax()-b._valueMin())/5;break;case d.ui.keyCode.UP:case d.ui.keyCode.RIGHT:if(g===
b._valueMax())return;h=g+i;break;case d.ui.keyCode.DOWN:case d.ui.keyCode.LEFT:if(g===b._valueMin())return;h=g-i;break}b._slide(c,f,h);return e}}).keyup(function(c){var e=d(this).data("index.ui-slider-handle");if(b._keySliding){b._keySliding=false;b._stop(c,e);b._change(c,e);d(this).removeClass("ui-state-active")}});this._refreshValue();this._animateOff=false},destroy:function(){this.handles.remove();this.range.remove();this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all").removeData("slider").unbind(".slider");
this._mouseDestroy();return this},_mouseCapture:function(b){var a=this.options,c,e,f,g,h,i;if(a.disabled)return false;this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()};this.elementOffset=this.element.offset();c={x:b.pageX,y:b.pageY};e=this._normValueFromMouse(c);f=this._valueMax()-this._valueMin()+1;h=this;this.handles.each(function(j){var k=Math.abs(e-h.values(j));if(f>k){f=k;g=d(this);i=j}});if(a.range===true&&this.values(1)===a.min){i+=1;g=d(this.handles[i])}if(this._start(b,
i)===false)return false;this._mouseSliding=true;h._handleIndex=i;g.addClass("ui-state-active").focus();a=g.offset();this._clickOffset=!d(b.target).parents().andSelf().is(".ui-slider-handle")?{left:0,top:0}:{left:b.pageX-a.left-g.width()/2,top:b.pageY-a.top-g.height()/2-(parseInt(g.css("borderTopWidth"),10)||0)-(parseInt(g.css("borderBottomWidth"),10)||0)+(parseInt(g.css("marginTop"),10)||0)};e=this._normValueFromMouse(c);this._slide(b,i,e);return this._animateOff=true},_mouseStart:function(){return true},
_mouseDrag:function(b){var a=this._normValueFromMouse({x:b.pageX,y:b.pageY});this._slide(b,this._handleIndex,a);return false},_mouseStop:function(b){this.handles.removeClass("ui-state-active");this._mouseSliding=false;this._stop(b,this._handleIndex);this._change(b,this._handleIndex);this._clickOffset=this._handleIndex=null;return this._animateOff=false},_detectOrientation:function(){this.orientation=this.options.orientation==="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(b){var a;
if(this.orientation==="horizontal"){a=this.elementSize.width;b=b.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)}else{a=this.elementSize.height;b=b.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)}a=b/a;if(a>1)a=1;if(a<0)a=0;if(this.orientation==="vertical")a=1-a;b=this._valueMax()-this._valueMin();return this._trimAlignValue(this._valueMin()+a*b)},_start:function(b,a){var c={handle:this.handles[a],value:this.value()};if(this.options.values&&this.options.values.length){c.value=
this.values(a);c.values=this.values()}return this._trigger("start",b,c)},_slide:function(b,a,c){var e;if(this.options.values&&this.options.values.length){e=this.values(a?0:1);if(this.options.values.length===2&&this.options.range===true&&(a===0&&c>e||a===1&&c<e))c=e;if(c!==this.values(a)){e=this.values();e[a]=c;b=this._trigger("slide",b,{handle:this.handles[a],value:c,values:e});this.values(a?0:1);b!==false&&this.values(a,c,true)}}else if(c!==this.value()){b=this._trigger("slide",b,{handle:this.handles[a],
value:c});b!==false&&this.value(c)}},_stop:function(b,a){var c={handle:this.handles[a],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(a);c.values=this.values()}this._trigger("stop",b,c)},_change:function(b,a){if(!this._keySliding&&!this._mouseSliding){var c={handle:this.handles[a],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(a);c.values=this.values()}this._trigger("change",b,c)}},value:function(b){if(arguments.length){this.options.value=
this._trimAlignValue(b);this._refreshValue();this._change(null,0)}return this._value()},values:function(b,a){var c,e,f;if(arguments.length>1){this.options.values[b]=this._trimAlignValue(a);this._refreshValue();this._change(null,b)}if(arguments.length)if(d.isArray(arguments[0])){c=this.options.values;e=arguments[0];for(f=0;f<c.length;f+=1){c[f]=this._trimAlignValue(e[f]);this._change(null,f)}this._refreshValue()}else return this.options.values&&this.options.values.length?this._values(b):this.value();
else return this._values()},_setOption:function(b,a){var c,e=0;if(d.isArray(this.options.values))e=this.options.values.length;d.Widget.prototype._setOption.apply(this,arguments);switch(b){case "disabled":if(a){this.handles.filter(".ui-state-focus").blur();this.handles.removeClass("ui-state-hover");this.handles.attr("disabled","disabled");this.element.addClass("ui-disabled")}else{this.handles.removeAttr("disabled");this.element.removeClass("ui-disabled")}break;case "orientation":this._detectOrientation();
this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation);this._refreshValue();break;case "value":this._animateOff=true;this._refreshValue();this._change(null,0);this._animateOff=false;break;case "values":this._animateOff=true;this._refreshValue();for(c=0;c<e;c+=1)this._change(null,c);this._animateOff=false;break}},_value:function(){var b=this.options.value;return b=this._trimAlignValue(b)},_values:function(b){var a,c;if(arguments.length){a=this.options.values[b];
return a=this._trimAlignValue(a)}else{a=this.options.values.slice();for(c=0;c<a.length;c+=1)a[c]=this._trimAlignValue(a[c]);return a}},_trimAlignValue:function(b){if(b<this._valueMin())return this._valueMin();if(b>this._valueMax())return this._valueMax();var a=this.options.step,c=b%a;b=b-c;if(c>=a/2)b+=a;return parseFloat(b.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var b=this.options.range,a=this.options,c=this,
e=!this._animateOff?a.animate:false,f,g={},h,i,j,k;if(this.options.values&&this.options.values.length)this.handles.each(function(l){f=(c.values(l)-c._valueMin())/(c._valueMax()-c._valueMin())*100;g[c.orientation==="horizontal"?"left":"bottom"]=f+"%";d(this).stop(1,1)[e?"animate":"css"](g,a.animate);if(c.options.range===true)if(c.orientation==="horizontal"){if(l===0)c.range.stop(1,1)[e?"animate":"css"]({left:f+"%"},a.animate);if(l===1)c.range[e?"animate":"css"]({width:f-h+"%"},{queue:false,duration:a.animate})}else{if(l===
0)c.range.stop(1,1)[e?"animate":"css"]({bottom:f+"%"},a.animate);if(l===1)c.range[e?"animate":"css"]({height:f-h+"%"},{queue:false,duration:a.animate})}h=f});else{i=this.value();j=this._valueMin();k=this._valueMax();f=k!==j?(i-j)/(k-j)*100:0;g[c.orientation==="horizontal"?"left":"bottom"]=f+"%";this.handle.stop(1,1)[e?"animate":"css"](g,a.animate);if(b==="min"&&this.orientation==="horizontal")this.range.stop(1,1)[e?"animate":"css"]({width:f+"%"},a.animate);if(b==="max"&&this.orientation==="horizontal")this.range[e?
"animate":"css"]({width:100-f+"%"},{queue:false,duration:a.animate});if(b==="min"&&this.orientation==="vertical")this.range.stop(1,1)[e?"animate":"css"]({height:f+"%"},a.animate);if(b==="max"&&this.orientation==="vertical")this.range[e?"animate":"css"]({height:100-f+"%"},{queue:false,duration:a.animate})}}});d.extend(d.ui.slider,{version:"1.8.1"})})(jQuery);
;;

function popup(url) {
    var params  = 'width='+screen.width;
    params += ', height='+screen.height;
    params += ', top=0, left=0';
    params += ', fullscreen=no';
    params += ', directories=no';
    params += ', location=no';
    params += ', menubar=no';
    params += ', resizable=yes';
    params += ', scrollbars=1';
    params += ', status=no';
    params += ', toolbar=no';

    window.open(url, 'name', params);
    return false;
}

function loadingShow(text) {
    if (!text)
        text = loadingmessage;
    jQuery('#loadingtext').html(text);
    jQuery('#loading').show();
}

function loadingHide() {
    setTimeout(function () { jQuery('#loading').hide(); }, 500);    
}

function message_show(id, timeToFade) {
    
    if (!timeToFade)
        timeToFade = 12000;
        
    $('#message_' + id).fadeIn('slow');

    setTimeout(function () { $('#message_' + id).fadeOut('slow'); }, timeToFade);
}

function message_hide(id) {
    $('#message_' + id).fadeOut('slow');
}

function messages_hide() {
    $('.message').fadeOut('slow');
}

function toggleCheckboxes(element, name) {
    var checked_status = element.checked;
    jQuery("input[name='" + name + "']").each(function() {
        this.checked = checked_status;
    });
}

function alertmessage(id) {
    alert(message[id]);
}

function goto_url(url) {
    document.location = url;
}

function disable_elements(formName) {
    formElement = document.getElementById(formName);
    totalElements = formElement.length;

    for(x=0;x<totalElements;x++) {
        formElement.elements[x].disabled = true;
    }
}

function enable_elements(formName) {
    formElement = document.getElementById(formName);
    totalElements = formElement.length;

    for(x=0;x<totalElements;x++) {
        formElement.elements[x].disabled = false;
    }
}

function show_error(error, input, form_name) {
    if (error) {
        $('#error_' + error).show();
        $('#input_' + input).addClass('error_input');
    }
    enable_elements(form_name);
}

function highlight(element, id, status) {
    if (status == 'on') {
        $('#help_' + id + ' span, #help_' + id + ' .text').addClass('selected');
    } else {
        $('#help_' + id + ' span, #help_' + id + ' .text').removeClass('selected');
    }
}

var ajaxParams = {};

function setAjaxParam(key, value) {
    ajaxParams[key] = value;
}

function callAjax(function_to_call, params, no_loading) {
    
    if (!no_loading)
        loadingShow();
    
    if (!params)
        var params = [];
        
    params.unshift(ajaxParams);
        
    Sijax.request(function_to_call, params);
}
;

if (typeof(GhostPlayer) === 'undefined') {

var GhostPlayer = {};

GhostPlayer._pageNumber = 1;
GhostPlayer._speed = 1;
GhostPlayer._skipInactivity = false;
GhostPlayer._isPlaying = null;

GhostPlayer._envParams = {};

GhostPlayer.getParam = function (key, defaultValue) {
	if (typeof(GhostPlayer._envParams[key]) === 'undefined') {
		return defaultValue;
	}
	return GhostPlayer._envParams[key];
};

GhostPlayer.getReplayer = function () {
	return window.frames['replayer'].GhostReplay;
};

GhostPlayer.setSpeed = function (speed) {
	$('.changespeed').removeClass('selected');
	$('#cs' + speed).addClass('selected');
	GhostPlayer._speed = speed;

	if (GhostPlayer._isPlaying) {
		GhostPlayer.getReplayer().onPlaybackSettingsChange();
	}
};

GhostPlayer.getSpeed = function () {
	return GhostPlayer._speed;
};

GhostPlayer.isSkippingInactivity = function () {
	return GhostPlayer._skipInactivity;
};

GhostPlayer.setSkipInactivityStatus = function(skipStatus) {
	if (skipStatus) {
		$('#sitrue').addClass('selected');
		$('#sifalse').removeClass('selected');
	} else {
		$('#sifalse').addClass('selected');
		$('#sitrue').removeClass('selected');
	}
	GhostPlayer._skipInactivity = skipStatus;
	if (GhostPlayer._isPlaying) {
		GhostPlayer.getReplayer().onPlaybackSettingsChange();
	}
};

GhostPlayer.next = function () {
	GhostPlayer.getReplayer().next();
};

GhostPlayer.prev = function () {
	GhostPlayer.getReplayer().prev();
};

/**
 * Called by the replay iframe when we're in the process of loading a replay.
 * Note that the replay's HTML is not yet loaded, but we've received enough data
 * to update our UI elements and stuff.
 */
GhostPlayer.onReplayLoading = function () {
	GhostPlayer.refreshUI();
	var replayer = GhostPlayer.getReplayer();
	GhostPlayer.onWindowResize(replayer.getInitialWidth(), replayer.getInitialHeight());
};

/**
 * Called by the replay iframe when it's ready to be played.
*/
GhostPlayer.onReplayLoaded = function () {
	var replayer = GhostPlayer.getReplayer();
	GhostPlayer._isPlaying = true;
	GhostPlayer.refreshUI();
	GhostPlayer.onWindowResize(replayer.getInitialWidth(), replayer.getInitialHeight());
	replayer.startReplay();
};

GhostPlayer.substring = function (string, length) {
	if (string.length <= length) {
		return string;
	}
	return string.substr(0, length) + '..';
};

/**
 * Called when a new replay has been loaded in the iframe,
 * so that we can refresh some elements - like the URL, duration, etc.
*/
GhostPlayer.refreshUI = function () {
	var replayer = GhostPlayer.getReplayer(),
		url = replayer.getUrl();

	$('#replay-url').html(url);
	$('#url').html(GhostPlayer.substring(url, 30));

	var durationHuman = replayer.getDurationHuman();
	$('#current_duration_min').html(durationHuman.min);
	$('#current_duration_sec').html(durationHuman.sec);

	$('#ghostplayercurpage').html(GhostPlayer._pageNumber);

	var isTrialMode = GhostPlayer.getParam('trialMode', true);
	if (GhostPlayer._pageNumber > 3 && isTrialMode) {
		GhostPlayer._showTrialOverlay();
	} else {
		GhostPlayer._hideTrialOverlay();
	}
};

GhostPlayer._showTrialOverlay = function () {
	var id = 'trial-overlay';
	if ($('#' + id).length === 0) {
		window.location = window.location;
	}
	$('#' + id).css({'display': 'block'});

	var id = 'trial-content-box';
	if ($('#' + id).length === 0) {
		window.location = window.location;
	}
	$('#' + id).css({'display': 'block'});
};

GhostPlayer._hideTrialOverlay = function () {
	$('#trial-overlay, #trial-content-box').css({'display': 'none'});
};

/**
 * Called when the replayer switches to the next page.
 */
GhostPlayer.onPageNext = function () {
	GhostPlayer._pageNumber += 1;
	GhostPlayer.refreshUI();
};

/**
 * Called when the replayer switches to the prev page.
 */
GhostPlayer.onPagePrev = function () {
	GhostPlayer._pageNumber -= 1;
	GhostPlayer.refreshUI();
};

GhostPlayer.onWindowResize = function (width, height) {
	$('#replayer').width(width);
	$('#replayer').height(height);
	$('#replay-resolution').html(width + 'x' + height);
};

GhostPlayer.togglePause = function () {
	GhostPlayer._isPlaying = ! GhostPlayer._isPlaying;
	GhostPlayer.refreshUI();
	GhostPlayer.getReplayer().onPauseChange(GhostPlayer._isPlaying);
    $('#control').toggleClass('pause');
};

GhostPlayer.initEnvironment = function (params) {
	GhostPlayer._envParams = params;
	$('#btn_play').bind('click', GhostPlayer.togglePause);

	$('#btn_prev').click(GhostPlayer.prev);
	$('#btn_next').click(GhostPlayer.next);

	$('#sitrue').click(function () { GhostPlayer.setSkipInactivityStatus(true); });
	$('#sifalse').click(function () { GhostPlayer.setSkipInactivityStatus(false); });

	$('.changespeed').live('click', function () {
		var speed = parseInt($(this).attr('id').replace('cs', ''), 10);
		GhostPlayer.setSpeed(speed);
	});

	//We only want to run this intensive code for trial accounts
	if (params.trialMode) {
		var maintainTrialContainers = function () {
			//Ensure the params haven't been touched..
			GhostPlayer._envParams = params;

			var $overlay = $('#trial-overlay'),
				$box = $('#trial-content-box');
			if ($overlay.length === 0 || $box.length === 0) {
				window.location = window.location;
			}

			//Visibility and display of boxes handled below..

			$overlay.css({
				"backgroundColor": "#000",
				"position": "absolute",
				"top": "85px",
				"left": "0px",
				"width": "100%",
				"height": ($(document).height() - 85) + "px",
				"z-index": 10000,
				"opacity": "0.80",
				"filter": "alpha(opacity=80)",
				"text-align": "center"
			});

			$box.css({
				"position": "fixed",
				"top": "20%",
				"left": "50%",
				"margin-left": "-357px",
				"backgroundColor": "#fff",
				"vertical-align": "middle",
				"width": "635px",
				"height": "438px",
				"padding": "40px",
				"z-index": 10002,
				"backgroundColor": "#fff",
				"-webkit-border-radius": "15px",
				"-moz-border-radius": "15px",
				"border-radius": "15px"
			});

			if (GhostPlayer._pageNumber > 3) {
				$overlay.css({
					"visibility": "visible",
					"display": "block"
				});
				$box.css({
					"visibility": "visible",
					"display": "block"
				});
			}
		};
		maintainTrialContainers();
		window.setInterval(maintainTrialContainers, 2000);
	}
};

}
;

function toggle_filters(state) {
    if (state == 'show') {
        $('#filter .content').show();
        $('#filter_show').hide();
    }
}

function toggle_date(id) {
    if (id == 5) {
        jQuery('#filter_calendar').slideDown();
    } else {
        jQuery('#filter_calendar').slideUp();
    }
}

function sort_by(column) {
    callAjax('sortTableBy', [column]);
}

function change_project(projectid, sitekey) {
    window.location = '?key=' + sitekey + '&id=' + projectid;
};

function toggle_recording(id, status) {
    if (status == 1) {
        $('#pause_' + id).hide();
        $('#recording_' + id).show();
    } else if (status == 0) {
        $('#pause_' + id).show();
        $('#recording_' + id).hide();
    }
}

function highlight(element, id, status) {
    if (status == 'on') {
        $('#help_' + id + ' span, #help_' + id + ' .text').addClass('selected');
        $(element).addClass('selected');
    } else {
        $('#help_' + id + ' span, #help_' + id + ' .text').removeClass('selected');
        $(element).removeClass('selected');
    }
}

function delete_task(id) {
    $('#moretask_' + id).remove();
    task_num--;
}

function add_task() {
    $('#more_tasks').append('<div class="form-item border-bottom-dashed"><label style="width: 160px;">' + task_text + '</label><textarea name="tasks[]" class="taskinput"></textarea></div>');
    $('#more_tasks').show();
    
}

function confirm_delete() {
    var c = confirm(confirm_delete_message);
    enable_elements('form_project');
    
    if (c) {
        $('#confirm_delete').val(1);
        $('#form_project').submit();
    } else {
        $('#confirm_delete').val(0);
    }
    
};


