/* 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}}}}}();
/**
 * Form's validator
 * 
 * Copyright (c) 2007 CSC
 *
 * @description Client side form validation. Integrating client side form validation is as simple 
 * as adding a css class to a form element
 * @param All parameters are optional
 * @author rz <roman@plotinka.ru>
 * @version 1.0.1
 */
 
var Forms = {};

Forms.conf = {
	prefix_req_field_id:   'req',
    prefix_error_elem_id:  'error',
	prefix_help_elem_id:   'help',
	error_field_classname: 'input-field-error'
};

Forms.Form = function (fid, pref) {
	fid = (null != fid && 'object' == typeof fid) ? fid : document.getElementById(fid);
	
	if (null == fid) {
		return false;
	}
	
	this.oForm    = fid;
	this.aFields  = {};
	this.aButtons = {};
	this.aLabels  = {};
	this.reqprefix   = pref || Forms.conf['prefix_req_field_id'];
	this.init();
};

Forms.Field = function (fid, type) {
    this.oField = fid;
	this.pType  = type || '';
};

Forms.Button = function (bid, type) {
    this.oButton = bid;
	this.pType   = type || '';
};

Forms.Label = function (lid, id) {
    this.oLabel = lid;
	this.pFor   = id;
};

Forms.Form.prototype.init = function() {
    var frm = this, i, j, l, k, commelem, f, labels, id, name, optelem, switcher, type;
	
	f = this.oForm.elements;

	for (i = 0, l = f.length; i < l; i++) {

		switch (f[i].type) {
			case 'submit': {

				this.aButtons[f[i].type] = new Forms.Button(f[i], type);
				f[i].onclick = function() {
					return function () {
					    if (frm.validate()) {
							this.value    = 'Loading...';
							this.disabled = true;
							this.form.submit();
						} else {
						    return false;
						}
					}
				}();
					
			}
			break;
			case 'reset': {
			
				this.aButtons[f[i].type] = new Forms.Button(f[i], type);
				f[i].onclick = function() {
					return function () {
					    return confirm(this.value + '?');
					}
				}();
				
			}
			break;
			default: {
				
				id = (f[i].name) ? f[i].name : f[i].id;

				if (-1 != id.indexOf(this.reqprefix + ':')) {
								  
					name = id.replace(this.reqprefix + ':', ''); //.slice(0, -1);
					type = f[i].value.replace(/\s.*/gi, '');

					if ('' == name) {
						continue;
					}

					if (null != f[name] && 'object' == typeof f[name]) {
						this.aFields[name] = new Forms.Field(f[name], type);

						if (null == this.oForm.focally) {
							if ('' == f[name].value && 1 == f[name].tabIndex) {
								this.oForm.focally = name;
								f[name].focus();
							}
						}
					}

				}

			}
		}

	}

	labels = this.oForm.getElementsByTagName('label');
	for (i = 0, l = labels.length; i < l; i++) {
		if (labels[i].htmlFor && null != this.aFields[labels[i].htmlFor]) {
			
			this.aLabels[labels[i].htmlFor] = new Forms.Label(labels[i], labels[i].htmlFor);
			
			commelem = document.getElementById(Forms.conf['prefix_help_elem_id'] + ':' + labels[i].htmlFor);
			
			if (null != commelem && 'object' == typeof commelem) {
				labels[i].onclick = function(elem) {
					return function () {
						if ('none' == frm.getElementStyle(elem, 'display')) {
							elem.style.display = 'block';
						} else {
							elem.style.display = 'none';
						}
						return true;
					}
				}(commelem);
				
			 // labels[i].style.textDecoration = 'underline';
				labels[i].style.borderBottom = '1px dashed';
			} else {
				labels[i].title= '';
			}
		}	
	}
	
	switcher = this.oForm.getElementsByTagName('a');
	for (i = 0, l = switcher.length; i < l; i++) {
		if (-1 != switcher[i].id.indexOf(Forms.conf['prefix_req_field_id'] + ':')) {
		    
			id = switcher[i].id.replace(Forms.conf['prefix_req_field_id'] + ':', ''); //.slice(0, -1);
																						   
			if (-1 != id.indexOf(':')) {
				name = id.substr(0, id.indexOf(':')); 
				id   = id.substr(id.indexOf(':') + 1);
				
                var optarr = [];
				optelem = this.oForm.getElementsByTagName(name);
				for (j = 0, k = optelem.length; j < k; j++) {
					if (id == optelem[j].className) {
						optarr[optarr.length] = optelem[j];
					}
				}
				
				switcher[i].onclick = function(obj) {
					return function () {
						var i, l;
						
						l = obj.childNodes.length;
						if (l > 1) {
							for (i = 0; i < l; i++) {
								obj.childNodes[i].style.display = ('none' == frm.getElementStyle(obj.childNodes[i], 'display')) ? 'inline' : 'none';
							}	
						}
						
						for (i = 0, l = optarr.length; i < l; i++) {
							optarr[i].style.display = ('none' == frm.getElementStyle(optarr[i], 'display')) ? 'block' : 'none';
						}
						return false;
					}
				}(switcher[i]);	
	
				break;
			}
			
		}
	}
    
	return true;
};

Forms.Form.prototype.validate = function() {
    var i, j, l, aFields = this.aFields, error = true, oFirstField = null;
	
    for (i in aFields) {

		switch (aFields[i].oField.type) {
			case 'text':
			case 'hidden':
			case 'file':
			case 'textarea': 
			case 'password': { 
			    error = this.errorHandler(aFields[i], aFields[i].oField.value);
			}
			break;
			case 'radio': {  
		      	for (j = 1, l = aFields[i].oField[aFields[i].oField.name].length; j < l; j++) {
		      		if (aFields[i].oField[aFields[i].oField.name][j].checked) {
						error = false;
						break;
		      		}
		      	}
			}
			break;
			case 'checkbox': { 
			    error = aFields[i].oField.checked;
			}
			break;
			case 'select-one': { 
			    error = (0 == aFields[i].oField.options.length) ? true : this.errorHandler(aFields[i], aFields[i].oField.options[aFields[i].oField.selectedIndex].value);
			}
			break;
			case 'select-multiple': { 
		      	for (j = 1, l = aFields[i].oField.options.length; j < l; j++) {
		      		if (aFields[i].oField.options[j].selected) {
						error = this.errorHandler(aFields[i], aFields[i].oField.options[j].value);
		      		}
		      	}
			}
			break;
			default: {
			}
		}
		
        if (!error) {
			this.errorShower(aFields[i], error);
		} else {
			oFirstField = (null == oFirstField) ? aFields[i] : oFirstField;
		}
		
    }
	
	if (null != oFirstField) {
		this.errorShower(oFirstField, true);
		return false;
	}
	
	return true;
};

Forms.Form.prototype.errorHandler = function(obj, str) {
    var error = true, etype = obj.pType, i, l, reg, str2 = '';
    
    if (null == str || 'undefined' == str || 0 == str.length) {
		return error;
	}

	switch (etype) {
		case 'login': {
			if (3 > str.length || 20 < str.length) {
				error = true;
			} else {
				reg   = /^[a-zA-Z0-9-]+$/;
				error = (str.match(reg)) ? false : true;
			}
		}
		break;
		case 'surname': {
		    reg = /\s{2,}/;
			str = str.replace(reg, ' ');
			obj.oField.value = str;
			
			if (3 > str.length || 30 < str.length) {
				error = true;
			} else {
				reg   = /^([а-яА-Яa-zA-Z]+[-\s]?[а-яА-Яa-zA-Z]+)+$/;
				error = (str.match(reg)) ? false : true;
			}
		}
		break;
		case 'email': { 
		    reg = /\.{2,}/;
			str = str.replace(reg, '.');
			obj.oField.value = str;
			
			if (7 > str.length || 40 < str.length) {
				error = true;
			} else {
				reg   = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
				error = (str.match(reg)) ? false : true;
			}
		}
		break;
		case 'passw':
		case 'code': {
			if (3 > str.length || 32 < str.length) {
				error = true;
			} else {
				reg   = /^[a-zA-Z0-9]+$/;
				error = (str.match(reg)) ? false : true;
			}
		}
		break;
		case 'imgcode': {
			if (6 != str.length) {
				error = true;
			} else {
				reg   = /^[a-zA-Z0-9]+$/;
				error = (str.match(reg)) ? false : true;
			}
		}
		break;
		case 'phone': {
			reg = /[^0-9]/g;
			str2 = str.replace(reg, '');
			
			if (8 == str2.charAt(0) || 7 == str2.charAt(0)) {
		        str2 = str2.substr(1);
			}

			if (9 < str2.length || 12 > str2.length) {
			     str = '8 ';
				 for (i = 0, l = str2.length; i < l; i++) {
				     if (7 < l) {
					     str += (0 == i) ? '(' : ((3 == i) ? ') ' : '');
					 }
					 
					 str += str2.charAt(i) + ((((7 >= l && i == 2) || i == 4 || i == 7 || i == 9) && str2.charAt(i + 1)) ? '-' : '');
				 }
				 obj.oField.value = str;
				 
				 error = false;
			}
		}
		break;
		case 'int':
		case 'number':
		case 'float': {
		    reg = /[,\.]{2,}/;
			str = str.replace(reg, '.');
			if (obj.oField.value) {
				obj.oField.value = str;
			}
			
		    reg   = /^-?(\d+)\.?(\d+)?$/;
			error = (str.match(reg)) ? false : true;
		}
		break;
		case 'text':
		case 'string':
		case 'message': {
			str   = str.toString();
			error = (str.length >= 3) ? false : true;
		 // && str != obj.oField.defaultValue
		}
		break;
		default: {
		}
	}

	return error;
};

Forms.Form.prototype.errorShower = function(obj, error) {
    var i, classname, errorelem, commelem;

	errorelem = document.getElementById(Forms.conf['prefix_error_elem_id'] + ':' + obj.oField.id);
	commelem  = document.getElementById(Forms.conf['prefix_help_elem_id'] + ':' + obj.oField.id);

	if (null != errorelem && 'object' == typeof errorelem) {
		if (error) {
			errorelem.style.display = 'block';
			classname = obj.oField.className.replace(Forms.conf['error_field_classname'], '');	
			
		    switch (obj.oField.type) {
				case 'text':
				case 'file':
				case 'textarea': 
				case 'password': {
				    obj.oField.className = ('' == classname) ? Forms.conf['error_field_classname'] : classname + ' ' + Forms.conf['error_field_classname'];
				    obj.oField.focus();
			    }
		    }
			
			if (obj.oField.select) {
			    obj.oField.select();
			}
			
			if (null != commelem && 'object' == typeof commelem) {
			    commelem.style.display = 'block';
			}
		} else {
			errorelem.style.display = 'none';
			obj.oField.className = obj.oField.className.replace(Forms.conf['error_field_classname'], '');
			
			if (null != commelem && 'object' == typeof commelem) {
			    commelem.style.display = 'none';
			}
			
			return true;
		}
	}
		
	return false;
};

Forms.Form.prototype.getElementStyle = function(obj, ieProp, cssProp) {
	var val = '', cssProp = cssProp || ieProp;
	
	if (null == obj || 'object' != typeof obj || !ieProp) {
		return val;
	}
	
	if (obj.currentStyle) {
		val = obj.currentStyle[ieProp];
	} else if (window.getComputedStyle && cssProp) {
		val = window.getComputedStyle(obj, '').getPropertyValue(cssProp);
	} 

	return val;
}
;function openJs (file, param) {
	var opt, msg, msg2, i, userAgent;
	opt  = 'toolbar=no, location=no, directories=no, status=no, scrollbars=no, resizable=yes, copyhistory=no, fullscreen=yes';
	
	userAgent=navigator.userAgent;
	
	if (userAgent.indexOf('MSIE') == -1) {
		opt += ', width=' + screen.availWidth + ', height=' + screen.availHeight + '';
	}

	msg2 = 'function onLoadBody () {\n';

    var variable = '';
    for (i in param) {
		variable += ', "' + i + '": "' + param[i] + '"';
	}

    msg2 += 'swfobject.embedSWF("/img/default/videoplayer/player.swf", "player", "100%", "100%", "8", {}, {"fullscreen": "true"' + variable + '}, { "bgcolor": "#f7f5ef", "allowscriptaccess": "sameDomain", "allowfullscreen": "true", "menu": "false", "allownetworking": "all" }, {} );';

	/*if (userAgent.indexOf('MSIE') != -1) {
		msg2 += 'window.document.getElementById("player").focus();';
	}*/

	msg2 += '}\n';

	msg  = '<'+'?xml version="1.0" encoding="windows-1251"?'+'>\n';
	msg += '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n';
	msg += '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ru" lang="ru">\n';
	msg += '<head>\n';
	msg += '<title></title>\n';
	msg += '<meta http-equiv="Content-Type" content="text/html; charset=windows-1251" />\n';
	/*msg += '<s'+'cript type="text/javascript" src="/_design/js/lib/utilities/swfobject.js"></s'+'cript>\n';*/
    msg += '<s'+'cript type="text/javascript" src="/js/default/csc_1.0.1.js"></s'+'cript>\n';
    /*msg += '<s'+'cript type="text/javascript" src="/js/default/swfobject.js"></s'+'cript>\n';*/
	msg += '<s'+'cript type="text/javascript">' + msg2 + '</s'+'cript>\n';

	if (userAgent.indexOf('MSIE') == -1) {
		msg += '<s'+'cript type="text/javascript">window.captureEvents(Event.KEYPRESS); window.onkeypress= pressed; function pressed(e) {if (0 == e.which) {window.close();}}</s'+'cript>\n';
	}

	msg += '<style>\n';
	msg += 'html, body { margin: 0; padding: 0; height: 100%; }\n';
	msg += 'div { height: 100%; }\n';
	msg += '</style>\n';
	msg += '</head>\n';

	msg += '<body id="bd" onLoad="onLoadBody()">\n';
	msg += '<div id="player"></div>\n';
	msg += '</body>\n';
	msg += '</html>';

	var win = window.open("about:blank", 'player', opt);
	win.document.write(msg);
	win.document.close();

	if (userAgent.indexOf('MSIE') != -1) {
        var t = setTimeout(function () {
            clearTimeout(t);
            win.document.getElementById("player").focus();
        }, 100);
	}
};
/**
 * Utilites
 *
 * @name Utilites
 * @description utility function
 * @author rz <roman@plotinka.ru>
 * @data   21.06.2008 
 * @version 1.0.0
 */

var Utils = {

 // Cookies
	
	Cookie : {
	
		set : function(sName, sValue, sExpire, sPath, sDomain, sSecure) {
		
			document.cookie = escape(sName) + '=' 
				+ ( window.encodeURI  ? encodeURI(sValue) : escape(sValue) ) 
				+ ( (null == sExpire) ? '' : '; expires=' + sExpire.toGMTString() ) 
				+ ( (null == sPath)   ? '' : '; path=' + sPath ) 
				+ ( (null == sDomain) ? '' : '; domain=' + sDomain ) 
				+ ( (null == sSecure) ? '' : '; secure' );
		
		},
		
		get : function(sName) {
		
			var d = document, iOffset, iEnd, sSearch = sName + '=';
			
			if ( d.cookie.length > 0 ) {
			
				iOffset = d.cookie.indexOf(sSearch);
				
				if ( -1 != iOffset ) {
				
					iOffset += sSearch.length;
			
					iEnd = d.cookie.indexOf(';', iOffset);
			
					if ( -1 == iEnd ) {
						iEnd = d.cookie.length;
					}
					
					return window.decodeURI ?
						decodeURI(d.cookie.substring(iOffset, iEnd)) :
						unescape(d.cookie.substring(iOffset, iEnd));
					
				}
			}
			
			return '';			
		
		}
	
	},
	
 // Popup
 
	Popup : function(sUrl, sName, oOptions) {
			
		var oSettings = Utils.extend(
			{	
			    iLeft       : 0,
				iTop        : 0,
				iWidth      : 600,
				iHeight     : 600,
				sToolbar    : 'no',
				sMenubar    : 'no',
				sResizeable : 'yes',
				sScrollbars : 'yes',
				sStatus     : 'yes'
			}, 
			oOptions
		);	
	
		oNW = window.open(
			sUrl,
			sName,
			'left='       + ( oSettings.iLeft || screen.availWidth / 2 - oSettings.iWidth / 2 ) + ', ' +
			'top = '      + ( oSettings.iTop || screen.availHeight / 2 - oSettings.iHeight / 2 ) + ', ' +
			'width='      + ( oSettings.iWidth || document.body.clientWidth || window.innerWidth ) + ', ' +
			'height='     + ( oSettings.iHeight || document.body.clientHeight || window.innerHeight ) + ', ' +
			'menubar='    + oSettings.sMenubar + ', ' +
			'toolbar='    + oSettings.sToolbar + ', ' +
			'resizable='  + oSettings.sResizeable + ', ' +
			'scrollbars=' + oSettings.sScrollbars + ', ' +
			'status='     + oSettings.sStatus
		);
			
		if ( sUrl.match(/\.(gif|png|jpe?g)$/i) ) {

			var sHtml = '<?xml version="1.0" encoding="windows-1251"?>';
			sHtml += '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
			sHtml += '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ru"><head><title></title>';
			sHtml += '<style>';
			sHtml += 'html,body{background:#fff;height:100%;margin:0;padding:0}';
			sHtml += 'table{border-collapse:collapse;width:100%;height:100%}';
			sHtml += 'td{text-align:center}';
			sHtml += '</style></head><body>';
			sHtml += '<table><tr><td><img s'+'rc="'+ sUrl +'" alt="" /></td></tr></table>';
			sHtml += '</body></html>';
		
			oNW.document.open();
			oNW.document.write(sHtml);
			oNW.document.close();
	
		}
		
		oNW.focus();				

		return false;
		
	},
	
	iepngfix: function(o) {	
		if ( /MSIE (5\.5|6).+Win/.test(navigator.userAgent )) {
			var sImgSrc;

			if ( 'IMG' == o.tagName ) {
				if (/\.png$/.test(o.src)) {
					sImgSrc = o.src;
					o.src = '/img/n.gif';
				}
			} else {
				sImgSrc = o.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i);
				if ( sImgSrc ) {
					sImgSrc = sImgSrc[1];
					o.runtimeStyle.backgroundImage = 'none';
				}
			}
			
			if ( sImgSrc ) {
			    o.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + sImgSrc + "',sizingMethod='crop')";
			}
		}
	},

    dw: function(sString) {
	
	    return ( sString.length > 0 ) ? document.writeln(sString) : false;
		
	},
	
	extend: function(oDestination, oSource, bNoReplace) {
	
	    var i;
		for (i in oSource) {
		    if ( !oDestination[i] || !bNoReplace ) {
			    oDestination[i] = oSource[i];
			}
		}
		
		return oDestination;
	}

}
;(function(){
/*
 * jQuery 1.2.6 - New Wave Javascript
 *
 * Copyright (c) 2008 John Resig (jquery.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * $Date: 2008-05-24 14:22:17 -0400 (Sat, 24 May 2008) $
 * $Rev: 5685 $
 */

// Map over jQuery in case of overwrite
var _jQuery = window.jQuery,
// Map over the $ in case of overwrite
	_$ = window.$;

var jQuery = window.jQuery = window.$ = function( selector, context ) {
	// The jQuery object is actually just the init constructor 'enhanced'
	return new jQuery.fn.init( selector, context );
};

// A simple way to check for HTML strings or ID strings
// (both of which we optimize for)
var quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/,

// Is it a simple selector
	isSimple = /^.[^:#\[\.]*$/,

// Will speed up references to undefined, and allows munging its name.
	undefined;

jQuery.fn = jQuery.prototype = {
	init: function( selector, context ) {
		// Make sure that a selection was provided
		selector = selector || document;

		// Handle $(DOMElement)
		if ( selector.nodeType ) {
			this[0] = selector;
			this.length = 1;
			return this;
		}
		// Handle HTML strings
		if ( typeof selector == "string" ) {
			// Are we dealing with HTML string or an ID?
			var match = quickExpr.exec( selector );

			// Verify a match, and that no context was specified for #id
			if ( match && (match[1] || !context) ) {

				// HANDLE: $(html) -> $(array)
				if ( match[1] )
					selector = jQuery.clean( [ match[1] ], context );

				// HANDLE: $("#id")
				else {
					var elem = document.getElementById( match[3] );

					// Make sure an element was located
					if ( elem ){
						// Handle the case where IE and Opera return items
						// by name instead of ID
						if ( elem.id != match[3] )
							return jQuery().find( selector );

						// Otherwise, we inject the element directly into the jQuery object
						return jQuery( elem );
					}
					selector = [];
				}

			// HANDLE: $(expr, [context])
			// (which is just equivalent to: $(content).find(expr)
			} else
				return jQuery( context ).find( selector );

		// HANDLE: $(function)
		// Shortcut for document ready
		} else if ( jQuery.isFunction( selector ) )
			return jQuery( document )[ jQuery.fn.ready ? "ready" : "load" ]( selector );

		return this.setArray(jQuery.makeArray(selector));
	},

	// The current version of jQuery being used
	jquery: "1.2.6",

	// The number of elements contained in the matched element set
	size: function() {
		return this.length;
	},

	// The number of elements contained in the matched element set
	length: 0,

	// Get the Nth element in the matched element set OR
	// Get the whole matched element set as a clean array
	get: function( num ) {
		return num == undefined ?

			// Return a 'clean' array
			jQuery.makeArray( this ) :

			// Return just the object
			this[ num ];
	},

	// Take an array of elements and push it onto the stack
	// (returning the new matched element set)
	pushStack: function( elems ) {
		// Build a new jQuery matched element set
		var ret = jQuery( elems );

		// Add the old object onto the stack (as a reference)
		ret.prevObject = this;

		// Return the newly-formed element set
		return ret;
	},

	// Force the current matched set of elements to become
	// the specified array of elements (destroying the stack in the process)
	// You should use pushStack() in order to do this, but maintain the stack
	setArray: function( elems ) {
		// Resetting the length to 0, then using the native Array push
		// is a super-fast way to populate an object with array-like properties
		this.length = 0;
		Array.prototype.push.apply( this, elems );

		return this;
	},

	// Execute a callback for every element in the matched set.
	// (You can seed the arguments with an array of args, but this is
	// only used internally.)
	each: function( callback, args ) {
		return jQuery.each( this, callback, args );
	},

	// Determine the position of an element within
	// the matched set of elements
	index: function( elem ) {
		var ret = -1;

		// Locate the position of the desired element
		return jQuery.inArray(
			// If it receives a jQuery object, the first element is used
			elem && elem.jquery ? elem[0] : elem
		, this );
	},

	attr: function( name, value, type ) {
		var options = name;

		// Look for the case where we're accessing a style value
		if ( name.constructor == String )
			if ( value === undefined )
				return this[0] && jQuery[ type || "attr" ]( this[0], name );

			else {
				options = {};
				options[ name ] = value;
			}

		// Check to see if we're setting style values
		return this.each(function(i){
			// Set all the styles
			for ( name in options )
				jQuery.attr(
					type ?
						this.style :
						this,
					name, jQuery.prop( this, options[ name ], type, i, name )
				);
		});
	},

	css: function( key, value ) {
		// ignore negative width and height values
		if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 )
			value = undefined;
		return this.attr( key, value, "curCSS" );
	},

	text: function( text ) {
		if ( typeof text != "object" && text != null )
			return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );

		var ret = "";

		jQuery.each( text || this, function(){
			jQuery.each( this.childNodes, function(){
				if ( this.nodeType != 8 )
					ret += this.nodeType != 1 ?
						this.nodeValue :
						jQuery.fn.text( [ this ] );
			});
		});

		return ret;
	},

	wrapAll: function( html ) {
		if ( this[0] )
			// The elements to wrap the target around
			jQuery( html, this[0].ownerDocument )
				.clone()
				.insertBefore( this[0] )
				.map(function(){
					var elem = this;

					while ( elem.firstChild )
						elem = elem.firstChild;

					return elem;
				})
				.append(this);

		return this;
	},

	wrapInner: function( html ) {
		return this.each(function(){
			jQuery( this ).contents().wrapAll( html );
		});
	},

	wrap: function( html ) {
		return this.each(function(){
			jQuery( this ).wrapAll( html );
		});
	},

	append: function() {
		return this.domManip(arguments, true, false, function(elem){
			if (this.nodeType == 1)
				this.appendChild( elem );
		});
	},

	prepend: function() {
		return this.domManip(arguments, true, true, function(elem){
			if (this.nodeType == 1)
				this.insertBefore( elem, this.firstChild );
		});
	},

	before: function() {
		return this.domManip(arguments, false, false, function(elem){
			this.parentNode.insertBefore( elem, this );
		});
	},

	after: function() {
		return this.domManip(arguments, false, true, function(elem){
			this.parentNode.insertBefore( elem, this.nextSibling );
		});
	},

	end: function() {
		return this.prevObject || jQuery( [] );
	},

	find: function( selector ) {
		var elems = jQuery.map(this, function(elem){
			return jQuery.find( selector, elem );
		});

		return this.pushStack( /[^+>] [^+>]/.test( selector ) || selector.indexOf("..") > -1 ?
			jQuery.unique( elems ) :
			elems );
	},

	clone: function( events ) {
		// Do the clone
		var ret = this.map(function(){
			if ( jQuery.browser.msie && !jQuery.isXMLDoc(this) ) {
				// IE copies events bound via attachEvent when
				// using cloneNode. Calling detachEvent on the
				// clone will also remove the events from the orignal
				// In order to get around this, we use innerHTML.
				// Unfortunately, this means some modifications to
				// attributes in IE that are actually only stored
				// as properties will not be copied (such as the
				// the name attribute on an input).
				var clone = this.cloneNode(true),
					container = document.createElement("div");
				container.appendChild(clone);
				return jQuery.clean([container.innerHTML])[0];
			} else
				return this.cloneNode(true);
		});

		// Need to set the expando to null on the cloned set if it exists
		// removeData doesn't work here, IE removes it from the original as well
		// this is primarily for IE but the data expando shouldn't be copied over in any browser
		var clone = ret.find("*").andSelf().each(function(){
			if ( this[ expando ] != undefined )
				this[ expando ] = null;
		});

		// Copy the events from the original to the clone
		if ( events === true )
			this.find("*").andSelf().each(function(i){
				if (this.nodeType == 3)
					return;
				var events = jQuery.data( this, "events" );

				for ( var type in events )
					for ( var handler in events[ type ] )
						jQuery.event.add( clone[ i ], type, events[ type ][ handler ], events[ type ][ handler ].data );
			});

		// Return the cloned set
		return ret;
	},

	filter: function( selector ) {
		return this.pushStack(
			jQuery.isFunction( selector ) &&
			jQuery.grep(this, function(elem, i){
				return selector.call( elem, i );
			}) ||

			jQuery.multiFilter( selector, this ) );
	},

	not: function( selector ) {
		if ( selector.constructor == String )
			// test special case where just one selector is passed in
			if ( isSimple.test( selector ) )
				return this.pushStack( jQuery.multiFilter( selector, this, true ) );
			else
				selector = jQuery.multiFilter( selector, this );

		var isArrayLike = selector.length && selector[selector.length - 1] !== undefined && !selector.nodeType;
		return this.filter(function() {
			return isArrayLike ? jQuery.inArray( this, selector ) < 0 : this != selector;
		});
	},

	add: function( selector ) {
		return this.pushStack( jQuery.unique( jQuery.merge(
			this.get(),
			typeof selector == 'string' ?
				jQuery( selector ) :
				jQuery.makeArray( selector )
		)));
	},

	is: function( selector ) {
		return !!selector && jQuery.multiFilter( selector, this ).length > 0;
	},

	hasClass: function( selector ) {
		return this.is( "." + selector );
	},

	val: function( value ) {
		if ( value == undefined ) {

			if ( this.length ) {
				var elem = this[0];

				// We need to handle select boxes special
				if ( jQuery.nodeName( elem, "select" ) ) {
					var index = elem.selectedIndex,
						values = [],
						options = elem.options,
						one = elem.type == "select-one";

					// Nothing was selected
					if ( index < 0 )
						return null;

					// Loop through all the selected options
					for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
						var option = options[ i ];

						if ( option.selected ) {
							// Get the specifc value for the option
							value = jQuery.browser.msie && !option.attributes.value.specified ? option.text : option.value;

							// We don't need an array for one selects
							if ( one )
								return value;

							// Multi-Selects return an array
							values.push( value );
						}
					}

					return values;

				// Everything else, we just grab the value
				} else
					return (this[0].value || "").replace(/\r/g, "");

			}

			return undefined;
		}

		if( value.constructor == Number )
			value += '';

		return this.each(function(){
			if ( this.nodeType != 1 )
				return;

			if ( value.constructor == Array && /radio|checkbox/.test( this.type ) )
				this.checked = (jQuery.inArray(this.value, value) >= 0 ||
					jQuery.inArray(this.name, value) >= 0);

			else if ( jQuery.nodeName( this, "select" ) ) {
				var values = jQuery.makeArray(value);

				jQuery( "option", this ).each(function(){
					this.selected = (jQuery.inArray( this.value, values ) >= 0 ||
						jQuery.inArray( this.text, values ) >= 0);
				});

				if ( !values.length )
					this.selectedIndex = -1;

			} else
				this.value = value;
		});
	},

	html: function( value ) {
		return value == undefined ?
			(this[0] ?
				this[0].innerHTML :
				null) :
			this.empty().append( value );
	},

	replaceWith: function( value ) {
		return this.after( value ).remove();
	},

	eq: function( i ) {
		return this.slice( i, i + 1 );
	},

	slice: function() {
		return this.pushStack( Array.prototype.slice.apply( this, arguments ) );
	},

	map: function( callback ) {
		return this.pushStack( jQuery.map(this, function(elem, i){
			return callback.call( elem, i, elem );
		}));
	},

	andSelf: function() {
		return this.add( this.prevObject );
	},

	data: function( key, value ){
		var parts = key.split(".");
		parts[1] = parts[1] ? "." + parts[1] : "";

		if ( value === undefined ) {
			var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);

			if ( data === undefined && this.length )
				data = jQuery.data( this[0], key );

			return data === undefined && parts[1] ?
				this.data( parts[0] ) :
				data;
		} else
			return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function(){
				jQuery.data( this, key, value );
			});
	},

	removeData: function( key ){
		return this.each(function(){
			jQuery.removeData( this, key );
		});
	},

	domManip: function( args, table, reverse, callback ) {
		var clone = this.length > 1, elems;

		return this.each(function(){
			if ( !elems ) {
				elems = jQuery.clean( args, this.ownerDocument );

				if ( reverse )
					elems.reverse();
			}

			var obj = this;

			if ( table && jQuery.nodeName( this, "table" ) && jQuery.nodeName( elems[0], "tr" ) )
				obj = this.getElementsByTagName("tbody")[0] || this.appendChild( this.ownerDocument.createElement("tbody") );

			var scripts = jQuery( [] );

			jQuery.each(elems, function(){
				var elem = clone ?
					jQuery( this ).clone( true )[0] :
					this;

				// execute all scripts after the elements have been injected
				if ( jQuery.nodeName( elem, "script" ) )
					scripts = scripts.add( elem );
				else {
					// Remove any inner scripts for later evaluation
					if ( elem.nodeType == 1 )
						scripts = scripts.add( jQuery( "script", elem ).remove() );

					// Inject the elements into the document
					callback.call( obj, elem );
				}
			});

			scripts.each( evalScript );
		});
	}
};

// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;

function evalScript( i, elem ) {
	if ( elem.src )
		jQuery.ajax({
			url: elem.src,
			async: false,
			dataType: "script"
		});

	else
		jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );

	if ( elem.parentNode )
		elem.parentNode.removeChild( elem );
}

function now(){
	return +new Date;
}

jQuery.extend = jQuery.fn.extend = function() {
	// copy reference to target object
	var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;

	// Handle a deep copy situation
	if ( target.constructor == Boolean ) {
		deep = target;
		target = arguments[1] || {};
		// skip the boolean and the target
		i = 2;
	}

	// Handle case when target is a string or something (possible in deep copy)
	if ( typeof target != "object" && typeof target != "function" )
		target = {};

	// extend jQuery itself if only one argument is passed
	if ( length == i ) {
		target = this;
		--i;
	}

	for ( ; i < length; i++ )
		// Only deal with non-null/undefined values
		if ( (options = arguments[ i ]) != null )
			// Extend the base object
			for ( var name in options ) {
				var src = target[ name ], copy = options[ name ];

				// Prevent never-ending loop
				if ( target === copy )
					continue;

				// Recurse if we're merging object values
				if ( deep && copy && typeof copy == "object" && !copy.nodeType )
					target[ name ] = jQuery.extend( deep, 
						// Never move original objects, clone them
						src || ( copy.length != null ? [ ] : { } )
					, copy );

				// Don't bring in undefined values
				else if ( copy !== undefined )
					target[ name ] = copy;

			}

	// Return the modified object
	return target;
};

var expando = "jQuery" + now(), uuid = 0, windowData = {},
	// exclude the following css properties to add px
	exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
	// cache defaultView
	defaultView = document.defaultView || {};

jQuery.extend({
	noConflict: function( deep ) {
		window.$ = _$;

		if ( deep )
			window.jQuery = _jQuery;

		return jQuery;
	},

	// See test/unit/core.js for details concerning this function.
	isFunction: function( fn ) {
		return !!fn && typeof fn != "string" && !fn.nodeName &&
			fn.constructor != Array && /^[\s[]?function/.test( fn + "" );
	},

	// check if an element is in a (or is an) XML document
	isXMLDoc: function( elem ) {
		return elem.documentElement && !elem.body ||
			elem.tagName && elem.ownerDocument && !elem.ownerDocument.body;
	},

	// Evalulates a script in a global context
	globalEval: function( data ) {
		data = jQuery.trim( data );

		if ( data ) {
			// Inspired by code by Andrea Giammarchi
			// http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
			var head = document.getElementsByTagName("head")[0] || document.documentElement,
				script = document.createElement("script");

			script.type = "text/javascript";
			if ( jQuery.browser.msie )
				script.text = data;
			else
				script.appendChild( document.createTextNode( data ) );

			// Use insertBefore instead of appendChild  to circumvent an IE6 bug.
			// This arises when a base node is used (#2709).
			head.insertBefore( script, head.firstChild );
			head.removeChild( script );
		}
	},

	nodeName: function( elem, name ) {
		return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase();
	},

	cache: {},

	data: function( elem, name, data ) {
		elem = elem == window ?
			windowData :
			elem;

		var id = elem[ expando ];

		// Compute a unique ID for the element
		if ( !id )
			id = elem[ expando ] = ++uuid;

		// Only generate the data cache if we're
		// trying to access or manipulate it
		if ( name && !jQuery.cache[ id ] )
			jQuery.cache[ id ] = {};

		// Prevent overriding the named cache with undefined values
		if ( data !== undefined )
			jQuery.cache[ id ][ name ] = data;

		// Return the named cache data, or the ID for the element
		return name ?
			jQuery.cache[ id ][ name ] :
			id;
	},

	removeData: function( elem, name ) {
		elem = elem == window ?
			windowData :
			elem;

		var id = elem[ expando ];

		// If we want to remove a specific section of the element's data
		if ( name ) {
			if ( jQuery.cache[ id ] ) {
				// Remove the section of cache data
				delete jQuery.cache[ id ][ name ];

				// If we've removed all the data, remove the element's cache
				name = "";

				for ( name in jQuery.cache[ id ] )
					break;

				if ( !name )
					jQuery.removeData( elem );
			}

		// Otherwise, we want to remove all of the element's data
		} else {
			// Clean up the element expando
			try {
				delete elem[ expando ];
			} catch(e){
				// IE has trouble directly removing the expando
				// but it's ok with using removeAttribute
				if ( elem.removeAttribute )
					elem.removeAttribute( expando );
			}

			// Completely remove the data cache
			delete jQuery.cache[ id ];
		}
	},

	// args is for internal usage only
	each: function( object, callback, args ) {
		var name, i = 0, length = object.length;

		if ( args ) {
			if ( length == undefined ) {
				for ( name in object )
					if ( callback.apply( object[ name ], args ) === false )
						break;
			} else
				for ( ; i < length; )
					if ( callback.apply( object[ i++ ], args ) === false )
						break;

		// A special, fast, case for the most common use of each
		} else {
			if ( length == undefined ) {
				for ( name in object )
					if ( callback.call( object[ name ], name, object[ name ] ) === false )
						break;
			} else
				for ( var value = object[0];
					i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
		}

		return object;
	},

	prop: function( elem, value, type, i, name ) {
		// Handle executable functions
		if ( jQuery.isFunction( value ) )
			value = value.call( elem, i );

		// Handle passing in a number to a CSS property
		return value && value.constructor == Number && type == "curCSS" && !exclude.test( name ) ?
			value + "px" :
			value;
	},

	className: {
		// internal only, use addClass("class")
		add: function( elem, classNames ) {
			jQuery.each((classNames || "").split(/\s+/), function(i, className){
				if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) )
					elem.className += (elem.className ? " " : "") + className;
			});
		},

		// internal only, use removeClass("class")
		remove: function( elem, classNames ) {
			if (elem.nodeType == 1)
				elem.className = classNames != undefined ?
					jQuery.grep(elem.className.split(/\s+/), function(className){
						return !jQuery.className.has( classNames, className );
					}).join(" ") :
					"";
		},

		// internal only, use hasClass("class")
		has: function( elem, className ) {
			return jQuery.inArray( className, (elem.className || elem).toString().split(/\s+/) ) > -1;
		}
	},

	// A method for quickly swapping in/out CSS properties to get correct calculations
	swap: function( elem, options, callback ) {
		var old = {};
		// Remember the old values, and insert the new ones
		for ( var name in options ) {
			old[ name ] = elem.style[ name ];
			elem.style[ name ] = options[ name ];
		}

		callback.call( elem );

		// Revert the old values
		for ( var name in options )
			elem.style[ name ] = old[ name ];
	},

	css: function( elem, name, force ) {
		if ( name == "width" || name == "height" ) {
			var val, props = { position: "absolute", visibility: "hidden", display:"block" }, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ];

			function getWH() {
				val = name == "width" ? elem.offsetWidth : elem.offsetHeight;
				var padding = 0, border = 0;
				jQuery.each( which, function() {
					padding += parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0;
					border += parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0;
				});
				val -= Math.round(padding + border);
			}

			if ( jQuery(elem).is(":visible") )
				getWH();
			else
				jQuery.swap( elem, props, getWH );

			return Math.max(0, val);
		}

		return jQuery.curCSS( elem, name, force );
	},

	curCSS: function( elem, name, force ) {
		var ret, style = elem.style;

		// A helper method for determining if an element's values are broken
		function color( elem ) {
			if ( !jQuery.browser.safari )
				return false;

			// defaultView is cached
			var ret = defaultView.getComputedStyle( elem, null );
			return !ret || ret.getPropertyValue("color") == "";
		}

		// We need to handle opacity special in IE
		if ( name == "opacity" && jQuery.browser.msie ) {
			ret = jQuery.attr( style, "opacity" );

			return ret == "" ?
				"1" :
				ret;
		}
		// Opera sometimes will give the wrong display answer, this fixes it, see #2037
		if ( jQuery.browser.opera && name == "display" ) {
			var save = style.outline;
			style.outline = "0 solid black";
			style.outline = save;
		}

		// Make sure we're using the right name for getting the float value
		if ( name.match( /float/i ) )
			name = styleFloat;

		if ( !force && style && style[ name ] )
			ret = style[ name ];

		else if ( defaultView.getComputedStyle ) {

			// Only "float" is needed here
			if ( name.match( /float/i ) )
				name = "float";

			name = name.replace( /([A-Z])/g, "-$1" ).toLowerCase();

			var computedStyle = defaultView.getComputedStyle( elem, null );

			if ( computedStyle && !color( elem ) )
				ret = computedStyle.getPropertyValue( name );

			// If the element isn't reporting its values properly in Safari
			// then some display: none elements are involved
			else {
				var swap = [], stack = [], a = elem, i = 0;

				// Locate all of the parent display: none elements
				for ( ; a && color(a); a = a.parentNode )
					stack.unshift(a);

				// Go through and make them visible, but in reverse
				// (It would be better if we knew the exact display type that they had)
				for ( ; i < stack.length; i++ )
					if ( color( stack[ i ] ) ) {
						swap[ i ] = stack[ i ].style.display;
						stack[ i ].style.display = "block";
					}

				// Since we flip the display style, we have to handle that
				// one special, otherwise get the value
				ret = name == "display" && swap[ stack.length - 1 ] != null ?
					"none" :
					( computedStyle && computedStyle.getPropertyValue( name ) ) || "";

				// Finally, revert the display styles back
				for ( i = 0; i < swap.length; i++ )
					if ( swap[ i ] != null )
						stack[ i ].style.display = swap[ i ];
			}

			// We should always get a number back from opacity
			if ( name == "opacity" && ret == "" )
				ret = "1";

		} else if ( elem.currentStyle ) {
			var camelCase = name.replace(/\-(\w)/g, function(all, letter){
				return letter.toUpperCase();
			});

			ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ];

			// From the awesome hack by Dean Edwards
			// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291

			// If we're not dealing with a regular pixel number
			// but a number that has a weird ending, we need to convert it to pixels
			if ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) {
				// Remember the original values
				var left = style.left, rsLeft = elem.runtimeStyle.left;

				// Put in the new values to get a computed value out
				elem.runtimeStyle.left = elem.currentStyle.left;
				style.left = ret || 0;
				ret = style.pixelLeft + "px";

				// Revert the changed values
				style.left = left;
				elem.runtimeStyle.left = rsLeft;
			}
		}

		return ret;
	},

	clean: function( elems, context ) {
		var ret = [];
		context = context || document;
		// !context.createElement fails in IE with an error but returns typeof 'object'
		if (typeof context.createElement == 'undefined')
			context = context.ownerDocument || context[0] && context[0].ownerDocument || document;

		jQuery.each(elems, function(i, elem){
			if ( !elem )
				return;

			if ( elem.constructor == Number )
				elem += '';

			// Convert html string into DOM nodes
			if ( typeof elem == "string" ) {
				// Fix "XHTML"-style tags in all browsers
				elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){
					return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ?
						all :
						front + "></" + tag + ">";
				});

				// Trim whitespace, otherwise indexOf won't work as expected
				var tags = jQuery.trim( elem ).toLowerCase(), div = context.createElement("div");

				var wrap =
					// option or optgroup
					!tags.indexOf("<opt") &&
					[ 1, "<select multiple='multiple'>", "</select>" ] ||

					!tags.indexOf("<leg") &&
					[ 1, "<fieldset>", "</fieldset>" ] ||

					tags.match(/^<(thead|tbody|tfoot|colg|cap)/) &&
					[ 1, "<table>", "</table>" ] ||

					!tags.indexOf("<tr") &&
					[ 2, "<table><tbody>", "</tbody></table>" ] ||

				 	// <thead> matched above
					(!tags.indexOf("<td") || !tags.indexOf("<th")) &&
					[ 3, "<table><tbody><tr>", "</tr></tbody></table>" ] ||

					!tags.indexOf("<col") &&
					[ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ] ||

					// IE can't serialize <link> and <script> tags normally
					jQuery.browser.msie &&
					[ 1, "div<div>", "</div>" ] ||

					[ 0, "", "" ];

				// Go to html and back, then peel off extra wrappers
				div.innerHTML = wrap[1] + elem + wrap[2];

				// Move to the right depth
				while ( wrap[0]-- )
					div = div.lastChild;

				// Remove IE's autoinserted <tbody> from table fragments
				if ( jQuery.browser.msie ) {

					// String was a <table>, *may* have spurious <tbody>
					var tbody = !tags.indexOf("<table") && tags.indexOf("<tbody") < 0 ?
						div.firstChild && div.firstChild.childNodes :

						// String was a bare <thead> or <tfoot>
						wrap[1] == "<table>" && tags.indexOf("<tbody") < 0 ?
							div.childNodes :
							[];

					for ( var j = tbody.length - 1; j >= 0 ; --j )
						if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length )
							tbody[ j ].parentNode.removeChild( tbody[ j ] );

					// IE completely kills leading whitespace when innerHTML is used
					if ( /^\s/.test( elem ) )
						div.insertBefore( context.createTextNode( elem.match(/^\s*/)[0] ), div.firstChild );

				}

				elem = jQuery.makeArray( div.childNodes );
			}

			if ( elem.length === 0 && (!jQuery.nodeName( elem, "form" ) && !jQuery.nodeName( elem, "select" )) )
				return;

			if ( elem[0] == undefined || jQuery.nodeName( elem, "form" ) || elem.options )
				ret.push( elem );

			else
				ret = jQuery.merge( ret, elem );

		});

		return ret;
	},

	attr: function( elem, name, value ) {
		// don't set attributes on text and comment nodes
		if (!elem || elem.nodeType == 3 || elem.nodeType == 8)
			return undefined;

		var notxml = !jQuery.isXMLDoc( elem ),
			// Whether we are setting (or getting)
			set = value !== undefined,
			msie = jQuery.browser.msie;

		// Try to normalize/fix the name
		name = notxml && jQuery.props[ name ] || name;

		// Only do all the following if this is a node (faster for style)
		// IE elem.getAttribute passes even for style
		if ( elem.tagName ) {

			// These attributes require special treatment
			var special = /href|src|style/.test( name );

			// Safari mis-reports the default selected property of a hidden option
			// Accessing the parent's selectedIndex property fixes it
			if ( name == "selected" && jQuery.browser.safari )
				elem.parentNode.selectedIndex;

			// If applicable, access the attribute via the DOM 0 way
			if ( name in elem && notxml && !special ) {
				if ( set ){
					// We can't allow the type property to be changed (since it causes problems in IE)
					if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode )
						throw "type property can't be changed";

					elem[ name ] = value;
				}

				// browsers index elements by id/name on forms, give priority to attributes.
				if( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) )
					return elem.getAttributeNode( name ).nodeValue;

				return elem[ name ];
			}

			if ( msie && notxml &&  name == "style" )
				return jQuery.attr( elem.style, "cssText", value );

			if ( set )
				// convert the value to a string (all browsers do this but IE) see #1070
				elem.setAttribute( name, "" + value );

			var attr = msie && notxml && special
					// Some attributes require a special call on IE
					? elem.getAttribute( name, 2 )
					: elem.getAttribute( name );

			// Non-existent attributes return null, we normalize to undefined
			return attr === null ? undefined : attr;
		}

		// elem is actually elem.style ... set the style

		// IE uses filters for opacity
		if ( msie && name == "opacity" ) {
			if ( set ) {
				// IE has trouble with opacity if it does not have layout
				// Force it by setting the zoom level
				elem.zoom = 1;

				// Set the alpha filter to set the opacity
				elem.filter = (elem.filter || "").replace( /alpha\([^)]*\)/, "" ) +
					(parseInt( value ) + '' == "NaN" ? "" : "alpha(opacity=" + value * 100 + ")");
			}

			return elem.filter && elem.filter.indexOf("opacity=") >= 0 ?
				(parseFloat( elem.filter.match(/opacity=([^)]*)/)[1] ) / 100) + '':
				"";
		}

		name = name.replace(/-([a-z])/ig, function(all, letter){
			return letter.toUpperCase();
		});

		if ( set )
			elem[ name ] = value;

		return elem[ name ];
	},

	trim: function( text ) {
		return (text || "").replace( /^\s+|\s+$/g, "" );
	},

	makeArray: function( array ) {
		var ret = [];

		if( array != null ){
			var i = array.length;
			//the window, strings and functions also have 'length'
			if( i == null || array.split || array.setInterval || array.call )
				ret[0] = array;
			else
				while( i )
					ret[--i] = array[i];
		}

		return ret;
	},

	inArray: function( elem, array ) {
		for ( var i = 0, length = array.length; i < length; i++ )
		// Use === because on IE, window == document
			if ( array[ i ] === elem )
				return i;

		return -1;
	},

	merge: function( first, second ) {
		// We have to loop this way because IE & Opera overwrite the length
		// expando of getElementsByTagName
		var i = 0, elem, pos = first.length;
		// Also, we need to make sure that the correct elements are being returned
		// (IE returns comment nodes in a '*' query)
		if ( jQuery.browser.msie ) {
			while ( elem = second[ i++ ] )
				if ( elem.nodeType != 8 )
					first[ pos++ ] = elem;

		} else
			while ( elem = second[ i++ ] )
				first[ pos++ ] = elem;

		return first;
	},

	unique: function( array ) {
		var ret = [], done = {};

		try {

			for ( var i = 0, length = array.length; i < length; i++ ) {
				var id = jQuery.data( array[ i ] );

				if ( !done[ id ] ) {
					done[ id ] = true;
					ret.push( array[ i ] );
				}
			}

		} catch( e ) {
			ret = array;
		}

		return ret;
	},

	grep: function( elems, callback, inv ) {
		var ret = [];

		// Go through the array, only saving the items
		// that pass the validator function
		for ( var i = 0, length = elems.length; i < length; i++ )
			if ( !inv != !callback( elems[ i ], i ) )
				ret.push( elems[ i ] );

		return ret;
	},

	map: function( elems, callback ) {
		var ret = [];

		// Go through the array, translating each of the items to their
		// new value (or values).
		for ( var i = 0, length = elems.length; i < length; i++ ) {
			var value = callback( elems[ i ], i );

			if ( value != null )
				ret[ ret.length ] = value;
		}

		return ret.concat.apply( [], ret );
	}
});

var userAgent = navigator.userAgent.toLowerCase();

// Figure out what browser is being used
jQuery.browser = {
	version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
	safari: /webkit/.test( userAgent ),
	opera: /opera/.test( userAgent ),
	msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
	mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};

var styleFloat = jQuery.browser.msie ?
	"styleFloat" :
	"cssFloat";

jQuery.extend({
	// Check to see if the W3C box model is being used
	boxModel: !jQuery.browser.msie || document.compatMode == "CSS1Compat",

	props: {
		"for": "htmlFor",
		"class": "className",
		"float": styleFloat,
		cssFloat: styleFloat,
		styleFloat: styleFloat,
		readonly: "readOnly",
		maxlength: "maxLength",
		cellspacing: "cellSpacing"
	}
});

jQuery.each({
	parent: function(elem){return elem.parentNode;},
	parents: function(elem){return jQuery.dir(elem,"parentNode");},
	next: function(elem){return jQuery.nth(elem,2,"nextSibling");},
	prev: function(elem){return jQuery.nth(elem,2,"previousSibling");},
	nextAll: function(elem){return jQuery.dir(elem,"nextSibling");},
	prevAll: function(elem){return jQuery.dir(elem,"previousSibling");},
	siblings: function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},
	children: function(elem){return jQuery.sibling(elem.firstChild);},
	contents: function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}
}, function(name, fn){
	jQuery.fn[ name ] = function( selector ) {
		var ret = jQuery.map( this, fn );

		if ( selector && typeof selector == "string" )
			ret = jQuery.multiFilter( selector, ret );

		return this.pushStack( jQuery.unique( ret ) );
	};
});

jQuery.each({
	appendTo: "append",
	prependTo: "prepend",
	insertBefore: "before",
	insertAfter: "after",
	replaceAll: "replaceWith"
}, function(name, original){
	jQuery.fn[ name ] = function() {
		var args = arguments;

		return this.each(function(){
			for ( var i = 0, length = args.length; i < length; i++ )
				jQuery( args[ i ] )[ original ]( this );
		});
	};
});

jQuery.each({
	removeAttr: function( name ) {
		jQuery.attr( this, name, "" );
		if (this.nodeType == 1)
			this.removeAttribute( name );
	},

	addClass: function( classNames ) {
		jQuery.className.add( this, classNames );
	},

	removeClass: function( classNames ) {
		jQuery.className.remove( this, classNames );
	},

	toggleClass: function( classNames ) {
		jQuery.className[ jQuery.className.has( this, classNames ) ? "remove" : "add" ]( this, classNames );
	},

	remove: function( selector ) {
		if ( !selector || jQuery.filter( selector, [ this ] ).r.length ) {
			// Prevent memory leaks
			jQuery( "*", this ).add(this).each(function(){
				jQuery.event.remove(this);
				jQuery.removeData(this);
			});
			if (this.parentNode)
				this.parentNode.removeChild( this );
		}
	},

	empty: function() {
		// Remove element nodes and prevent memory leaks
		jQuery( ">*", this ).remove();

		// Remove any remaining nodes
		while ( this.firstChild )
			this.removeChild( this.firstChild );
	}
}, function(name, fn){
	jQuery.fn[ name ] = function(){
		return this.each( fn, arguments );
	};
});

jQuery.each([ "Height", "Width" ], function(i, name){
	var type = name.toLowerCase();

	jQuery.fn[ type ] = function( size ) {
		// Get window width or height
		return this[0] == window ?
			// Opera reports document.body.client[Width/Height] properly in both quirks and standards
			jQuery.browser.opera && document.body[ "client" + name ] ||

			// Safari reports inner[Width/Height] just fine (Mozilla and Opera include scroll bar widths)
			jQuery.browser.safari && window[ "inner" + name ] ||

			// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
			document.compatMode == "CSS1Compat" && document.documentElement[ "client" + name ] || document.body[ "client" + name ] :

			// Get document width or height
			this[0] == document ?
				// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
				Math.max(
					Math.max(document.body["scroll" + name], document.documentElement["scroll" + name]),
					Math.max(document.body["offset" + name], document.documentElement["offset" + name])
				) :

				// Get or set width or height on the element
				size == undefined ?
					// Get width or height on the element
					(this.length ? jQuery.css( this[0], type ) : null) :

					// Set the width or height on the element (default to pixels if value is unitless)
					this.css( type, size.constructor == String ? size : size + "px" );
	};
});

// Helper function used by the dimensions and offset modules
function num(elem, prop) {
	return elem[0] && parseInt( jQuery.curCSS(elem[0], prop, true), 10 ) || 0;
}var chars = jQuery.browser.safari && parseInt(jQuery.browser.version) < 417 ?
		"(?:[\\w*_-]|\\\\.)" :
		"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",
	quickChild = new RegExp("^>\\s*(" + chars + "+)"),
	quickID = new RegExp("^(" + chars + "+)(#)(" + chars + "+)"),
	quickClass = new RegExp("^([#.]?)(" + chars + "*)");

jQuery.extend({
	expr: {
		"": function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},
		"#": function(a,i,m){return a.getAttribute("id")==m[2];},
		":": {
			// Position Checks
			lt: function(a,i,m){return i<m[3]-0;},
			gt: function(a,i,m){return i>m[3]-0;},
			nth: function(a,i,m){return m[3]-0==i;},
			eq: function(a,i,m){return m[3]-0==i;},
			first: function(a,i){return i==0;},
			last: function(a,i,m,r){return i==r.length-1;},
			even: function(a,i){return i%2==0;},
			odd: function(a,i){return i%2;},

			// Child Checks
			"first-child": function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},
			"last-child": function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},
			"only-child": function(a){return !jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},

			// Parent Checks
			parent: function(a){return a.firstChild;},
			empty: function(a){return !a.firstChild;},

			// Text Check
			contains: function(a,i,m){return (a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},

			// Visibility
			visible: function(a){return "hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},
			hidden: function(a){return "hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},

			// Form attributes
			enabled: function(a){return !a.disabled;},
			disabled: function(a){return a.disabled;},
			checked: function(a){return a.checked;},
			selected: function(a){return a.selected||jQuery.attr(a,"selected");},

			// Form elements
			text: function(a){return "text"==a.type;},
			radio: function(a){return "radio"==a.type;},
			checkbox: function(a){return "checkbox"==a.type;},
			file: function(a){return "file"==a.type;},
			password: function(a){return "password"==a.type;},
			submit: function(a){return "submit"==a.type;},
			image: function(a){return "image"==a.type;},
			reset: function(a){return "reset"==a.type;},
			button: function(a){return "button"==a.type||jQuery.nodeName(a,"button");},
			input: function(a){return /input|select|textarea|button/i.test(a.nodeName);},

			// :has()
			has: function(a,i,m){return jQuery.find(m[3],a).length;},

			// :header
			header: function(a){return /h\d/i.test(a.nodeName);},

			// :animated
			animated: function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}
		}
	},

	// The regular expressions that power the parsing engine
	parse: [
		// Match: [@value='test'], [@foo]
		/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,

		// Match: :contains('foo')
		/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,

		// Match: :even, :last-child, #id, .class
		new RegExp("^([:.#]*)(" + chars + "+)")
	],

	multiFilter: function( expr, elems, not ) {
		var old, cur = [];

		while ( expr && expr != old ) {
			old = expr;
			var f = jQuery.filter( expr, elems, not );
			expr = f.t.replace(/^\s*,\s*/, "" );
			cur = not ? elems = f.r : jQuery.merge( cur, f.r );
		}

		return cur;
	},

	find: function( t, context ) {
		// Quickly handle non-string expressions
		if ( typeof t != "string" )
			return [ t ];

		// check to make sure context is a DOM element or a document
		if ( context && context.nodeType != 1 && context.nodeType != 9)
			return [ ];

		// Set the correct context (if none is provided)
		context = context || document;

		// Initialize the search
		var ret = [context], done = [], last, nodeName;

		// Continue while a selector expression exists, and while
		// we're no longer looping upon ourselves
		while ( t && last != t ) {
			var r = [];
			last = t;

			t = jQuery.trim(t);

			var foundToken = false,

			// An attempt at speeding up child selectors that
			// point to a specific element tag
				re = quickChild,

				m = re.exec(t);

			if ( m ) {
				nodeName = m[1].toUpperCase();

				// Perform our own iteration and filter
				for ( var i = 0; ret[i]; i++ )
					for ( var c = ret[i].firstChild; c; c = c.nextSibling )
						if ( c.nodeType == 1 && (nodeName == "*" || c.nodeName.toUpperCase() == nodeName) )
							r.push( c );

				ret = r;
				t = t.replace( re, "" );
				if ( t.indexOf(" ") == 0 ) continue;
				foundToken = true;
			} else {
				re = /^([>+~])\s*(\w*)/i;

				if ( (m = re.exec(t)) != null ) {
					r = [];

					var merge = {};
					nodeName = m[2].toUpperCase();
					m = m[1];

					for ( var j = 0, rl = ret.length; j < rl; j++ ) {
						var n = m == "~" || m == "+" ? ret[j].nextSibling : ret[j].firstChild;
						for ( ; n; n = n.nextSibling )
							if ( n.nodeType == 1 ) {
								var id = jQuery.data(n);

								if ( m == "~" && merge[id] ) break;

								if (!nodeName || n.nodeName.toUpperCase() == nodeName ) {
									if ( m == "~" ) merge[id] = true;
									r.push( n );
								}

								if ( m == "+" ) break;
							}
					}

					ret = r;

					// And remove the token
					t = jQuery.trim( t.replace( re, "" ) );
					foundToken = true;
				}
			}

			// See if there's still an expression, and that we haven't already
			// matched a token
			if ( t && !foundToken ) {
				// Handle multiple expressions
				if ( !t.indexOf(",") ) {
					// Clean the result set
					if ( context == ret[0] ) ret.shift();

					// Merge the result sets
					done = jQuery.merge( done, ret );

					// Reset the context
					r = ret = [context];

					// Touch up the selector string
					t = " " + t.substr(1,t.length);

				} else {
					// Optimize for the case nodeName#idName
					var re2 = quickID;
					var m = re2.exec(t);

					// Re-organize the results, so that they're consistent
					if ( m ) {
						m = [ 0, m[2], m[3], m[1] ];

					} else {
						// Otherwise, do a traditional filter check for
						// ID, class, and element selectors
						re2 = quickClass;
						m = re2.exec(t);
					}

					m[2] = m[2].replace(/\\/g, "");

					var elem = ret[ret.length-1];

					// Try to do a global search by ID, where we can
					if ( m[1] == "#" && elem && elem.getElementById && !jQuery.isXMLDoc(elem) ) {
						// Optimization for HTML document case
						var oid = elem.getElementById(m[2]);

						// Do a quick check for the existence of the actual ID attribute
						// to avoid selecting by the name attribute in IE
						// also check to insure id is a string to avoid selecting an element with the name of 'id' inside a form
						if ( (jQuery.browser.msie||jQuery.browser.opera) && oid && typeof oid.id == "string" && oid.id != m[2] )
							oid = jQuery('[@id="'+m[2]+'"]', elem)[0];

						// Do a quick check for node name (where applicable) so
						// that div#foo searches will be really fast
						ret = r = oid && (!m[3] || jQuery.nodeName(oid, m[3])) ? [oid] : [];
					} else {
						// We need to find all descendant elements
						for ( var i = 0; ret[i]; i++ ) {
							// Grab the tag name being searched for
							var tag = m[1] == "#" && m[3] ? m[3] : m[1] != "" || m[0] == "" ? "*" : m[2];

							// Handle IE7 being really dumb about <object>s
							if ( tag == "*" && ret[i].nodeName.toLowerCase() == "object" )
								tag = "param";

							r = jQuery.merge( r, ret[i].getElementsByTagName( tag ));
						}

						// It's faster to filter by class and be done with it
						if ( m[1] == "." )
							r = jQuery.classFilter( r, m[2] );

						// Same with ID filtering
						if ( m[1] == "#" ) {
							var tmp = [];

							// Try to find the element with the ID
							for ( var i = 0; r[i]; i++ )
								if ( r[i].getAttribute("id") == m[2] ) {
									tmp = [ r[i] ];
									break;
								}

							r = tmp;
						}

						ret = r;
					}

					t = t.replace( re2, "" );
				}

			}

			// If a selector string still exists
			if ( t ) {
				// Attempt to filter it
				var val = jQuery.filter(t,r);
				ret = r = val.r;
				t = jQuery.trim(val.t);
			}
		}

		// An error occurred with the selector;
		// just return an empty set instead
		if ( t )
			ret = [];

		// Remove the root context
		if ( ret && context == ret[0] )
			ret.shift();

		// And combine the results
		done = jQuery.merge( done, ret );

		return done;
	},

	classFilter: function(r,m,not){
		m = " " + m + " ";
		var tmp = [];
		for ( var i = 0; r[i]; i++ ) {
			var pass = (" " + r[i].className + " ").indexOf( m ) >= 0;
			if ( !not && pass || not && !pass )
				tmp.push( r[i] );
		}
		return tmp;
	},

	filter: function(t,r,not) {
		var last;

		// Look for common filter expressions
		while ( t && t != last ) {
			last = t;

			var p = jQuery.parse, m;

			for ( var i = 0; p[i]; i++ ) {
				m = p[i].exec( t );

				if ( m ) {
					// Remove what we just matched
					t = t.substring( m[0].length );

					m[2] = m[2].replace(/\\/g, "");
					break;
				}
			}

			if ( !m )
				break;

			// :not() is a special case that can be optimized by
			// keeping it out of the expression list
			if ( m[1] == ":" && m[2] == "not" )
				// optimize if only one selector found (most common case)
				r = isSimple.test( m[3] ) ?
					jQuery.filter(m[3], r, true).r :
					jQuery( r ).not( m[3] );

			// We can get a big speed boost by filtering by class here
			else if ( m[1] == "." )
				r = jQuery.classFilter(r, m[2], not);

			else if ( m[1] == "[" ) {
				var tmp = [], type = m[3];

				for ( var i = 0, rl = r.length; i < rl; i++ ) {
					var a = r[i], z = a[ jQuery.props[m[2]] || m[2] ];

					if ( z == null || /href|src|selected/.test(m[2]) )
						z = jQuery.attr(a,m[2]) || '';

					if ( (type == "" && !!z ||
						 type == "=" && z == m[5] ||
						 type == "!=" && z != m[5] ||
						 type == "^=" && z && !z.indexOf(m[5]) ||
						 type == "$=" && z.substr(z.length - m[5].length) == m[5] ||
						 (type == "*=" || type == "~=") && z.indexOf(m[5]) >= 0) ^ not )
							tmp.push( a );
				}

				r = tmp;

			// We can get a speed boost by handling nth-child here
			} else if ( m[1] == ":" && m[2] == "nth-child" ) {
				var merge = {}, tmp = [],
					// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
					test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
						m[3] == "even" && "2n" || m[3] == "odd" && "2n+1" ||
						!/\D/.test(m[3]) && "0n+" + m[3] || m[3]),
					// calculate the numbers (first)n+(last) including if they are negative
					first = (test[1] + (test[2] || 1)) - 0, last = test[3] - 0;

				// loop through all the elements left in the jQuery object
				for ( var i = 0, rl = r.length; i < rl; i++ ) {
					var node = r[i], parentNode = node.parentNode, id = jQuery.data(parentNode);

					if ( !merge[id] ) {
						var c = 1;

						for ( var n = parentNode.firstChild; n; n = n.nextSibling )
							if ( n.nodeType == 1 )
								n.nodeIndex = c++;

						merge[id] = true;
					}

					var add = false;

					if ( first == 0 ) {
						if ( node.nodeIndex == last )
							add = true;
					} else if ( (node.nodeIndex - last) % first == 0 && (node.nodeIndex - last) / first >= 0 )
						add = true;

					if ( add ^ not )
						tmp.push( node );
				}

				r = tmp;

			// Otherwise, find the expression to execute
			} else {
				var fn = jQuery.expr[ m[1] ];
				if ( typeof fn == "object" )
					fn = fn[ m[2] ];

				if ( typeof fn == "string" )
					fn = eval("false||function(a,i){return " + fn + ";}");

				// Execute it against the current filter
				r = jQuery.grep( r, function(elem, i){
					return fn(elem, i, m, r);
				}, not );
			}
		}

		// Return an array of filtered elements (r)
		// and the modified expression string (t)
		return { r: r, t: t };
	},

	dir: function( elem, dir ){
		var matched = [],
			cur = elem[dir];
		while ( cur && cur != document ) {
			if ( cur.nodeType == 1 )
				matched.push( cur );
			cur = cur[dir];
		}
		return matched;
	},

	nth: function(cur,result,dir,elem){
		result = result || 1;
		var num = 0;

		for ( ; cur; cur = cur[dir] )
			if ( cur.nodeType == 1 && ++num == result )
				break;

		return cur;
	},

	sibling: function( n, elem ) {
		var r = [];

		for ( ; n; n = n.nextSibling ) {
			if ( n.nodeType == 1 && n != elem )
				r.push( n );
		}

		return r;
	}
});
/*
 * A number of helper functions used for managing events.
 * Many of the ideas behind this code orignated from
 * Dean Edwards' addEvent library.
 */
jQuery.event = {

	// Bind an event to an element
	// Original by Dean Edwards
	add: function(elem, types, handler, data) {
		if ( elem.nodeType == 3 || elem.nodeType == 8 )
			return;

		// For whatever reason, IE has trouble passing the window object
		// around, causing it to be cloned in the process
		if ( jQuery.browser.msie && elem.setInterval )
			elem = window;

		// Make sure that the function being executed has a unique ID
		if ( !handler.guid )
			handler.guid = this.guid++;

		// if data is passed, bind to handler
		if( data != undefined ) {
			// Create temporary function pointer to original handler
			var fn = handler;

			// Create unique handler function, wrapped around original handler
			handler = this.proxy( fn, function() {
				// Pass arguments and context to original handler
				return fn.apply(this, arguments);
			});

			// Store data in unique handler
			handler.data = data;
		}

		// Init the element's event structure
		var events = jQuery.data(elem, "events") || jQuery.data(elem, "events", {}),
			handle = jQuery.data(elem, "handle") || jQuery.data(elem, "handle", function(){
				// Handle the second event of a trigger and when
				// an event is called after a page has unloaded
				if ( typeof jQuery != "undefined" && !jQuery.event.triggered )
					return jQuery.event.handle.apply(arguments.callee.elem, arguments);
			});
		// Add elem as a property of the handle function
		// This is to prevent a memory leak with non-native
		// event in IE.
		handle.elem = elem;

		// Handle multiple events separated by a space
		// jQuery(...).bind("mouseover mouseout", fn);
		jQuery.each(types.split(/\s+/), function(index, type) {
			// Namespaced event handlers
			var parts = type.split(".");
			type = parts[0];
			handler.type = parts[1];

			// Get the current list of functions bound to this event
			var handlers = events[type];

			// Init the event handler queue
			if (!handlers) {
				handlers = events[type] = {};

				// Check for a special event handler
				// Only use addEventListener/attachEvent if the special
				// events handler returns false
				if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem) === false ) {
					// Bind the global event handler to the element
					if (elem.addEventListener)
						elem.addEventListener(type, handle, false);
					else if (elem.attachEvent)
						elem.attachEvent("on" + type, handle);
				}
			}

			// Add the function to the element's handler list
			handlers[handler.guid] = handler;

			// Keep track of which events have been used, for global triggering
			jQuery.event.global[type] = true;
		});

		// Nullify elem to prevent memory leaks in IE
		elem = null;
	},

	guid: 1,
	global: {},

	// Detach an event or set of events from an element
	remove: function(elem, types, handler) {
		// don't do events on text and comment nodes
		if ( elem.nodeType == 3 || elem.nodeType == 8 )
			return;

		var events = jQuery.data(elem, "events"), ret, index;

		if ( events ) {
			// Unbind all events for the element
			if ( types == undefined || (typeof types == "string" && types.charAt(0) == ".") )
				for ( var type in events )
					this.remove( elem, type + (types || "") );
			else {
				// types is actually an event object here
				if ( types.type ) {
					handler = types.handler;
					types = types.type;
				}

				// Handle multiple events seperated by a space
				// jQuery(...).unbind("mouseover mouseout", fn);
				jQuery.each(types.split(/\s+/), function(index, type){
					// Namespaced event handlers
					var parts = type.split(".");
					type = parts[0];

					if ( events[type] ) {
						// remove the given handler for the given type
						if ( handler )
							delete events[type][handler.guid];

						// remove all handlers for the given type
						else
							for ( handler in events[type] )
								// Handle the removal of namespaced events
								if ( !parts[1] || events[type][handler].type == parts[1] )
									delete events[type][handler];

						// remove generic event handler if no more handlers exist
						for ( ret in events[type] ) break;
						if ( !ret ) {
							if ( !jQuery.event.special[type] || jQuery.event.special[type].teardown.call(elem) === false ) {
								if (elem.removeEventListener)
									elem.removeEventListener(type, jQuery.data(elem, "handle"), false);
								else if (elem.detachEvent)
									elem.detachEvent("on" + type, jQuery.data(elem, "handle"));
							}
							ret = null;
							delete events[type];
						}
					}
				});
			}

			// Remove the expando if it's no longer used
			for ( ret in events ) break;
			if ( !ret ) {
				var handle = jQuery.data( elem, "handle" );
				if ( handle ) handle.elem = null;
				jQuery.removeData( elem, "events" );
				jQuery.removeData( elem, "handle" );
			}
		}
	},

	trigger: function(type, data, elem, donative, extra) {
		// Clone the incoming data, if any
		data = jQuery.makeArray(data);

		if ( type.indexOf("!") >= 0 ) {
			type = type.slice(0, -1);
			var exclusive = true;
		}

		// Handle a global trigger
		if ( !elem ) {
			// Only trigger if we've ever bound an event for it
			if ( this.global[type] )
				jQuery("*").add([window, document]).trigger(type, data);

		// Handle triggering a single element
		} else {
			// don't do events on text and comment nodes
			if ( elem.nodeType == 3 || elem.nodeType == 8 )
				return undefined;

			var val, ret, fn = jQuery.isFunction( elem[ type ] || null ),
				// Check to see if we need to provide a fake event, or not
				event = !data[0] || !data[0].preventDefault;

			// Pass along a fake event
			if ( event ) {
				data.unshift({
					type: type,
					target: elem,
					preventDefault: function(){},
					stopPropagation: function(){},
					timeStamp: now()
				});
				data[0][expando] = true; // no need to fix fake event
			}

			// Enforce the right trigger type
			data[0].type = type;
			if ( exclusive )
				data[0].exclusive = true;

			// Trigger the event, it is assumed that "handle" is a function
			var handle = jQuery.data(elem, "handle");
			if ( handle )
				val = handle.apply( elem, data );

			// Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
			if ( (!fn || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
				val = false;

			// Extra functions don't get the custom event object
			if ( event )
				data.shift();

			// Handle triggering of extra function
			if ( extra && jQuery.isFunction( extra ) ) {
				// call the extra function and tack the current return value on the end for possible inspection
				ret = extra.apply( elem, val == null ? data : data.concat( val ) );
				// if anything is returned, give it precedence and have it overwrite the previous value
				if (ret !== undefined)
					val = ret;
			}

			// Trigger the native events (except for clicks on links)
			if ( fn && donative !== false && val !== false && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
				this.triggered = true;
				try {
					elem[ type ]();
				// prevent IE from throwing an error for some hidden elements
				} catch (e) {}
			}

			this.triggered = false;
		}

		return val;
	},

	handle: function(event) {
		// returned undefined or false
		var val, ret, namespace, all, handlers;

		event = arguments[0] = jQuery.event.fix( event || window.event );

		// Namespaced event handlers
		namespace = event.type.split(".");
		event.type = namespace[0];
		namespace = namespace[1];
		// Cache this now, all = true means, any handler
		all = !namespace && !event.exclusive;

		handlers = ( jQuery.data(this, "events") || {} )[event.type];

		for ( var j in handlers ) {
			var handler = handlers[j];

			// Filter the functions by class
			if ( all || handler.type == namespace ) {
				// Pass in a reference to the handler function itself
				// So that we can later remove it
				event.handler = handler;
				event.data = handler.data;

				ret = handler.apply( this, arguments );

				if ( val !== false )
					val = ret;

				if ( ret === false ) {
					event.preventDefault();
					event.stopPropagation();
				}
			}
		}

		return val;
	},

	fix: function(event) {
		if ( event[expando] == true )
			return event;

		// store a copy of the original event object
		// and "clone" to set read-only properties
		var originalEvent = event;
		event = { originalEvent: originalEvent };
		var 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 timeStamp toElement type view wheelDelta which".split(" ");
		for ( var i=props.length; i; i-- )
			event[ props[i] ] = originalEvent[ props[i] ];

		// Mark it as fixed
		event[expando] = true;

		// add preventDefault and stopPropagation since
		// they will not work on the clone
		event.preventDefault = function() {
			// if preventDefault exists run it on the original event
			if (originalEvent.preventDefault)
				originalEvent.preventDefault();
			// otherwise set the returnValue property of the original event to false (IE)
			originalEvent.returnValue = false;
		};
		event.stopPropagation = function() {
			// if stopPropagation exists run it on the original event
			if (originalEvent.stopPropagation)
				originalEvent.stopPropagation();
			// otherwise set the cancelBubble property of the original event to true (IE)
			originalEvent.cancelBubble = true;
		};

		// Fix timeStamp
		event.timeStamp = event.timeStamp || now();

		// Fix target property, if necessary
		if ( !event.target )
			event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either

		// check if target is a textnode (safari)
		if ( event.target.nodeType == 3 )
			event.target = event.target.parentNode;

		// Add relatedTarget, if necessary
		if ( !event.relatedTarget && event.fromElement )
			event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;

		// Calculate pageX/Y if missing and clientX/Y available
		if ( event.pageX == null && event.clientX != null ) {
			var doc = document.documentElement, body = document.body;
			event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
			event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
		}

		// Add which for key events
		if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) )
			event.which = event.charCode || event.keyCode;

		// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
		if ( !event.metaKey && event.ctrlKey )
			event.metaKey = event.ctrlKey;

		// Add which for click: 1 == left; 2 == middle; 3 == right
		// Note: button is not normalized, so don't use it
		if ( !event.which && event.button )
			event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));

		return event;
	},

	proxy: function( fn, proxy ){
		// Set the guid of unique handler to the same of original handler, so it can be removed
		proxy.guid = fn.guid = fn.guid || proxy.guid || this.guid++;
		// So proxy can be declared as an argument
		return proxy;
	},

	special: {
		ready: {
			setup: function() {
				// Make sure the ready event is setup
				bindReady();
				return;
			},

			teardown: function() { return; }
		},

		mouseenter: {
			setup: function() {
				if ( jQuery.browser.msie ) return false;
				jQuery(this).bind("mouseover", jQuery.event.special.mouseenter.handler);
				return true;
			},

			teardown: function() {
				if ( jQuery.browser.msie ) return false;
				jQuery(this).unbind("mouseover", jQuery.event.special.mouseenter.handler);
				return true;
			},

			handler: function(event) {
				// If we actually just moused on to a sub-element, ignore it
				if ( withinElement(event, this) ) return true;
				// Execute the right handlers by setting the event type to mouseenter
				event.type = "mouseenter";
				return jQuery.event.handle.apply(this, arguments);
			}
		},

		mouseleave: {
			setup: function() {
				if ( jQuery.browser.msie ) return false;
				jQuery(this).bind("mouseout", jQuery.event.special.mouseleave.handler);
				return true;
			},

			teardown: function() {
				if ( jQuery.browser.msie ) return false;
				jQuery(this).unbind("mouseout", jQuery.event.special.mouseleave.handler);
				return true;
			},

			handler: function(event) {
				// If we actually just moused on to a sub-element, ignore it
				if ( withinElement(event, this) ) return true;
				// Execute the right handlers by setting the event type to mouseleave
				event.type = "mouseleave";
				return jQuery.event.handle.apply(this, arguments);
			}
		}
	}
};

jQuery.fn.extend({
	bind: function( type, data, fn ) {
		return type == "unload" ? this.one(type, data, fn) : this.each(function(){
			jQuery.event.add( this, type, fn || data, fn && data );
		});
	},

	one: function( type, data, fn ) {
		var one = jQuery.event.proxy( fn || data, function(event) {
			jQuery(this).unbind(event, one);
			return (fn || data).apply( this, arguments );
		});
		return this.each(function(){
			jQuery.event.add( this, type, one, fn && data);
		});
	},

	unbind: function( type, fn ) {
		return this.each(function(){
			jQuery.event.remove( this, type, fn );
		});
	},

	trigger: function( type, data, fn ) {
		return this.each(function(){
			jQuery.event.trigger( type, data, this, true, fn );
		});
	},

	triggerHandler: function( type, data, fn ) {
		return this[0] && jQuery.event.trigger( type, data, this[0], false, fn );
	},

	toggle: function( fn ) {
		// Save reference to arguments for access in closure
		var args = arguments, i = 1;

		// link all the functions, so any of them can unbind this click handler
		while( i < args.length )
			jQuery.event.proxy( fn, args[i++] );

		return this.click( jQuery.event.proxy( fn, function(event) {
			// Figure out which function to execute
			this.lastToggle = ( this.lastToggle || 0 ) % i;

			// Make sure that clicks stop
			event.preventDefault();

			// and execute the function
			return args[ this.lastToggle++ ].apply( this, arguments ) || false;
		}));
	},

	hover: function(fnOver, fnOut) {
		return this.bind('mouseenter', fnOver).bind('mouseleave', fnOut);
	},

	ready: function(fn) {
		// Attach the listeners
		bindReady();

		// If the DOM is already ready
		if ( jQuery.isReady )
			// Execute the function immediately
			fn.call( document, jQuery );

		// Otherwise, remember the function for later
		else
			// Add the function to the wait list
			jQuery.readyList.push( function() { return fn.call(this, jQuery); } );

		return this;
	}
});

jQuery.extend({
	isReady: false,
	readyList: [],
	// Handle when the DOM is ready
	ready: function() {
		// Make sure that the DOM is not already loaded
		if ( !jQuery.isReady ) {
			// Remember that the DOM is ready
			jQuery.isReady = true;

			// If there are functions bound, to execute
			if ( jQuery.readyList ) {
				// Execute all of them
				jQuery.each( jQuery.readyList, function(){
					this.call( document );
				});

				// Reset the list of functions
				jQuery.readyList = null;
			}

			// Trigger any bound ready events
			jQuery(document).triggerHandler("ready");
		}
	}
});

var readyBound = false;

function bindReady(){
	if ( readyBound ) return;
	readyBound = true;

	// Mozilla, Opera (see further below for it) and webkit nightlies currently support this event
	if ( document.addEventListener && !jQuery.browser.opera)
		// Use the handy event callback
		document.addEventListener( "DOMContentLoaded", jQuery.ready, false );

	// If IE is used and is not in a frame
	// Continually check to see if the document is ready
	if ( jQuery.browser.msie && window == top ) (function(){
		if (jQuery.isReady) return;
		try {
			// If IE is used, use the trick by Diego Perini
			// http://javascript.nwbox.com/IEContentLoaded/
			document.documentElement.doScroll("left");
		} catch( error ) {
			setTimeout( arguments.callee, 0 );
			return;
		}
		// and execute any waiting functions
		jQuery.ready();
	})();

	if ( jQuery.browser.opera )
		document.addEventListener( "DOMContentLoaded", function () {
			if (jQuery.isReady) return;
			for (var i = 0; i < document.styleSheets.length; i++)
				if (document.styleSheets[i].disabled) {
					setTimeout( arguments.callee, 0 );
					return;
				}
			// and execute any waiting functions
			jQuery.ready();
		}, false);

	if ( jQuery.browser.safari ) {
		var numStyles;
		(function(){
			if (jQuery.isReady) return;
			if ( document.readyState != "loaded" && document.readyState != "complete" ) {
				setTimeout( arguments.callee, 0 );
				return;
			}
			if ( numStyles === undefined )
				numStyles = jQuery("style, link[rel=stylesheet]").length;
			if ( document.styleSheets.length != numStyles ) {
				setTimeout( arguments.callee, 0 );
				return;
			}
			// and execute any waiting functions
			jQuery.ready();
		})();
	}

	// A fallback to window.onload, that will always work
	jQuery.event.add( window, "load", jQuery.ready );
}

jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
	"mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
	"submit,keydown,keypress,keyup,error").split(","), function(i, name){

	// Handle event binding
	jQuery.fn[name] = function(fn){
		return fn ? this.bind(name, fn) : this.trigger(name);
	};
});

// Checks if an event happened on an element within another element
// Used in jQuery.event.special.mouseenter and mouseleave handlers
var withinElement = function(event, elem) {
	// Check if mouse(over|out) are still within the same parent element
	var parent = event.relatedTarget;
	// Traverse up the tree
	while ( parent && parent != elem ) try { parent = parent.parentNode; } catch(error) { parent = elem; }
	// Return true if we actually just moused on to a sub-element
	return parent == elem;
};

// Prevent memory leaks in IE
// And prevent errors on refresh with events like mouseover in other browsers
// Window isn't included so as not to unbind existing unload events
jQuery(window).bind("unload", function() {
	jQuery("*").add(document).unbind();
});
jQuery.fn.extend({
	// Keep a copy of the old load
	_load: jQuery.fn.load,

	load: function( url, params, callback ) {
		if ( typeof url != 'string' )
			return this._load( url );

		var off = url.indexOf(" ");
		if ( off >= 0 ) {
			var selector = url.slice(off, url.length);
			url = url.slice(0, off);
		}

		callback = callback || function(){};

		// Default to a GET request
		var type = "GET";

		// If the second parameter was provided
		if ( params )
			// If it's a function
			if ( jQuery.isFunction( params ) ) {
				// We assume that it's the callback
				callback = params;
				params = null;

			// Otherwise, build a param string
			} else {
				params = jQuery.param( params );
				type = "POST";
			}

		var self = this;

		// Request the remote document
		jQuery.ajax({
			url: url,
			type: type,
			dataType: "html",
			data: params,
			complete: function(res, status){
				// If successful, inject the HTML into all the matched elements
				if ( status == "success" || status == "notmodified" )
					// See if a selector was specified
					self.html( selector ?
						// Create a dummy div to hold the results
						jQuery("<div/>")
							// inject the contents of the document in, removing the scripts
							// to avoid any 'Permission Denied' errors in IE
							.append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))

							// Locate the specified elements
							.find(selector) :

						// If not, just inject the full result
						res.responseText );

				self.each( callback, [res.responseText, status, res] );
			}
		});
		return this;
	},

	serialize: function() {
		return jQuery.param(this.serializeArray());
	},
	serializeArray: function() {
		return this.map(function(){
			return jQuery.nodeName(this, "form") ?
				jQuery.makeArray(this.elements) : this;
		})
		.filter(function(){
			return this.name && !this.disabled &&
				(this.checked || /select|textarea/i.test(this.nodeName) ||
					/text|hidden|password/i.test(this.type));
		})
		.map(function(i, elem){
			var val = jQuery(this).val();
			return val == null ? null :
				val.constructor == Array ?
					jQuery.map( val, function(val, i){
						return {name: elem.name, value: val};
					}) :
					{name: elem.name, value: val};
		}).get();
	}
});

// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
	jQuery.fn[o] = function(f){
		return this.bind(o, f);
	};
});

var jsc = now();

jQuery.extend({
	get: function( url, data, callback, type ) {
		// shift arguments if data argument was ommited
		if ( jQuery.isFunction( data ) ) {
			callback = data;
			data = null;
		}

		return jQuery.ajax({
			type: "GET",
			url: url,
			data: data,
			success: callback,
			dataType: type
		});
	},

	getScript: function( url, callback ) {
		return jQuery.get(url, null, callback, "script");
	},

	getJSON: function( url, data, callback ) {
		return jQuery.get(url, data, callback, "json");
	},

	post: function( url, data, callback, type ) {
		if ( jQuery.isFunction( data ) ) {
			callback = data;
			data = {};
		}

		return jQuery.ajax({
			type: "POST",
			url: url,
			data: data,
			success: callback,
			dataType: type
		});
	},

	ajaxSetup: function( settings ) {
		jQuery.extend( jQuery.ajaxSettings, settings );
	},

	ajaxSettings: {
		url: location.href,
		global: true,
		type: "GET",
		timeout: 0,
		contentType: "application/x-www-form-urlencoded",
		processData: true,
		async: true,
		data: null,
		username: null,
		password: null,
		accepts: {
			xml: "application/xml, text/xml",
			html: "text/html",
			script: "text/javascript, application/javascript",
			json: "application/json, text/javascript",
			text: "text/plain",
			_default: "*/*"
		}
	},

	// Last-Modified header cache for next request
	lastModified: {},

	ajax: function( s ) {
		// Extend the settings, but re-extend 's' so that it can be
		// checked again later (in the test suite, specifically)
		s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));

		var jsonp, jsre = /=\?(&|$)/g, status, data,
			type = s.type.toUpperCase();

		// convert data if not already a string
		if ( s.data && s.processData && typeof s.data != "string" )
			s.data = jQuery.param(s.data);

		// Handle JSONP Parameter Callbacks
		if ( s.dataType == "jsonp" ) {
			if ( type == "GET" ) {
				if ( !s.url.match(jsre) )
					s.url += (s.url.match(/\?/) ? "&" : "?") + (s.jsonp || "callback") + "=?";
			} else if ( !s.data || !s.data.match(jsre) )
				s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
			s.dataType = "json";
		}

		// Build temporary JSONP function
		if ( s.dataType == "json" && (s.data && s.data.match(jsre) || s.url.match(jsre)) ) {
			jsonp = "jsonp" + jsc++;

			// Replace the =? sequence both in the query string and the data
			if ( s.data )
				s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
			s.url = s.url.replace(jsre, "=" + jsonp + "$1");

			// We need to make sure
			// that a JSONP style response is executed properly
			s.dataType = "script";

			// Handle JSONP-style loading
			window[ jsonp ] = function(tmp){
				data = tmp;
				success();
				complete();
				// Garbage collect
				window[ jsonp ] = undefined;
				try{ delete window[ jsonp ]; } catch(e){}
				if ( head )
					head.removeChild( script );
			};
		}

		if ( s.dataType == "script" && s.cache == null )
			s.cache = false;

		if ( s.cache === false && type == "GET" ) {
			var ts = now();
			// try replacing _= if it is there
			var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
			// if nothing was replaced, add timestamp to the end
			s.url = ret + ((ret == s.url) ? (s.url.match(/\?/) ? "&" : "?") + "_=" + ts : "");
		}

		// If data is available, append data to url for get requests
		if ( s.data && type == "GET" ) {
			s.url += (s.url.match(/\?/) ? "&" : "?") + s.data;

			// IE likes to send both get and post data, prevent this
			s.data = null;
		}

		// Watch for a new set of requests
		if ( s.global && ! jQuery.active++ )
			jQuery.event.trigger( "ajaxStart" );

		// Matches an absolute URL, and saves the domain
		var remote = /^(?:\w+:)?\/\/([^\/?#]+)/;

		// If we're requesting a remote document
		// and trying to load JSON or Script with a GET
		if ( s.dataType == "script" && type == "GET"
				&& remote.test(s.url) && remote.exec(s.url)[1] != location.host ){
			var head = document.getElementsByTagName("head")[0];
			var script = document.createElement("script");
			script.src = s.url;
			if (s.scriptCharset)
				script.charset = s.scriptCharset;

			// Handle Script loading
			if ( !jsonp ) {
				var done = false;

				// Attach handlers for all browsers
				script.onload = script.onreadystatechange = function(){
					if ( !done && (!this.readyState ||
							this.readyState == "loaded" || this.readyState == "complete") ) {
						done = true;
						success();
						complete();
						head.removeChild( script );
					}
				};
			}

			head.appendChild(script);

			// We handle everything using the script element injection
			return undefined;
		}

		var requestDone = false;

		// Create the request object; Microsoft failed to properly
		// implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
		var xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();

		// Open the socket
		// Passing null username, generates a login popup on Opera (#2865)
		if( s.username )
			xhr.open(type, s.url, s.async, s.username, s.password);
		else
			xhr.open(type, s.url, s.async);

		// Need an extra try/catch for cross domain requests in Firefox 3
		try {
			// Set the correct header, if data is being sent
			if ( s.data )
				xhr.setRequestHeader("Content-Type", s.contentType);

			// Set the If-Modified-Since header, if ifModified mode.
			if ( s.ifModified )
				xhr.setRequestHeader("If-Modified-Since",
					jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );

			// Set header so the called script knows that it's an XMLHttpRequest
			xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

			// Set the Accepts header for the server, depending on the dataType
			xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
				s.accepts[ s.dataType ] + ", */*" :
				s.accepts._default );
		} catch(e){}

		// Allow custom headers/mimetypes
		if ( s.beforeSend && s.beforeSend(xhr, s) === false ) {
			// cleanup active request counter
			s.global && jQuery.active--;
			// close opended socket
			xhr.abort();
			return false;
		}

		if ( s.global )
			jQuery.event.trigger("ajaxSend", [xhr, s]);

		// Wait for a response to come back
		var onreadystatechange = function(isTimeout){
			// The transfer is complete and the data is available, or the request timed out
			if ( !requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout") ) {
				requestDone = true;

				// clear poll interval
				if (ival) {
					clearInterval(ival);
					ival = null;
				}

				status = isTimeout == "timeout" && "timeout" ||
					!jQuery.httpSuccess( xhr ) && "error" ||
					s.ifModified && jQuery.httpNotModified( xhr, s.url ) && "notmodified" ||
					"success";

				if ( status == "success" ) {
					// Watch for, and catch, XML document parse errors
					try {
						// process the data (runs the xml through httpData regardless of callback)
						data = jQuery.httpData( xhr, s.dataType, s.dataFilter );
					} catch(e) {
						status = "parsererror";
					}
				}

				// Make sure that the request was successful or notmodified
				if ( status == "success" ) {
					// Cache Last-Modified header, if ifModified mode.
					var modRes;
					try {
						modRes = xhr.getResponseHeader("Last-Modified");
					} catch(e) {} // swallow exception thrown by FF if header is not available

					if ( s.ifModified && modRes )
						jQuery.lastModified[s.url] = modRes;

					// JSONP handles its own success callback
					if ( !jsonp )
						success();
				} else
					jQuery.handleError(s, xhr, status);

				// Fire the complete handlers
				complete();

				// Stop memory leaks
				if ( s.async )
					xhr = null;
			}
		};

		if ( s.async ) {
			// don't attach the handler to the request, just poll it instead
			var ival = setInterval(onreadystatechange, 13);

			// Timeout checker
			if ( s.timeout > 0 )
				setTimeout(function(){
					// Check to see if the request is still happening
					if ( xhr ) {
						// Cancel the request
						xhr.abort();

						if( !requestDone )
							onreadystatechange( "timeout" );
					}
				}, s.timeout);
		}

		// Send the data
		try {
			xhr.send(s.data);
		} catch(e) {
			jQuery.handleError(s, xhr, null, e);
		}

		// firefox 1.5 doesn't fire statechange for sync requests
		if ( !s.async )
			onreadystatechange();

		function success(){
			// If a local callback was specified, fire it and pass it the data
			if ( s.success )
				s.success( data, status );

			// Fire the global callback
			if ( s.global )
				jQuery.event.trigger( "ajaxSuccess", [xhr, s] );
		}

		function complete(){
			// Process result
			if ( s.complete )
				s.complete(xhr, status);

			// The request was completed
			if ( s.global )
				jQuery.event.trigger( "ajaxComplete", [xhr, s] );

			// Handle the global AJAX counter
			if ( s.global && ! --jQuery.active )
				jQuery.event.trigger( "ajaxStop" );
		}

		// return XMLHttpRequest to allow aborting the request etc.
		return xhr;
	},

	handleError: function( s, xhr, status, e ) {
		// If a local callback was specified, fire it
		if ( s.error ) s.error( xhr, status, e );

		// Fire the global callback
		if ( s.global )
			jQuery.event.trigger( "ajaxError", [xhr, s, e] );
	},

	// Counter for holding the number of active queries
	active: 0,

	// Determines if an XMLHttpRequest was successful or not
	httpSuccess: function( xhr ) {
		try {
			// IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
			return !xhr.status && location.protocol == "file:" ||
				( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223 ||
				jQuery.browser.safari && xhr.status == undefined;
		} catch(e){}
		return false;
	},

	// Determines if an XMLHttpRequest returns NotModified
	httpNotModified: function( xhr, url ) {
		try {
			var xhrRes = xhr.getResponseHeader("Last-Modified");

			// Firefox always returns 200. check Last-Modified date
			return xhr.status == 304 || xhrRes == jQuery.lastModified[url] ||
				jQuery.browser.safari && xhr.status == undefined;
		} catch(e){}
		return false;
	},

	httpData: function( xhr, type, filter ) {
		var ct = xhr.getResponseHeader("content-type"),
			xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
			data = xml ? xhr.responseXML : xhr.responseText;

		if ( xml && data.documentElement.tagName == "parsererror" )
			throw "parsererror";
			
		// Allow a pre-filtering function to sanitize the response
		if( filter )
			data = filter( data, type );

		// If the type is "script", eval it in global context
		if ( type == "script" )
			jQuery.globalEval( data );

		// Get the JavaScript object, if JSON is used.
		if ( type == "json" )
			data = eval("(" + data + ")");

		return data;
	},

	// Serialize an array of form elements or a set of
	// key/values into a query string
	param: function( a ) {
		var s = [];

		// If an array was passed in, assume that it is an array
		// of form elements
		if ( a.constructor == Array || a.jquery )
			// Serialize the form elements
			jQuery.each( a, function(){
				s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) );
			});

		// Otherwise, assume that it's an object of key/value pairs
		else
			// Serialize the key/values
			for ( var j in a )
				// If the value is an array then the key names need to be repeated
				if ( a[j] && a[j].constructor == Array )
					jQuery.each( a[j], function(){
						s.push( encodeURIComponent(j) + "=" + encodeURIComponent( this ) );
					});
				else
					s.push( encodeURIComponent(j) + "=" + encodeURIComponent( jQuery.isFunction(a[j]) ? a[j]() : a[j] ) );

		// Return the resulting serialization
		return s.join("&").replace(/%20/g, "+");
	}

});
jQuery.fn.extend({
	show: function(speed,callback){
		return speed ?
			this.animate({
				height: "show", width: "show", opacity: "show"
			}, speed, callback) :

			this.filter(":hidden").each(function(){
				this.style.display = this.oldblock || "";
				if ( jQuery.css(this,"display") == "none" ) {
					var elem = jQuery("<" + this.tagName + " />").appendTo("body");
					this.style.display = elem.css("display");
					// handle an edge condition where css is - div { display:none; } or similar
					if (this.style.display == "none")
						this.style.display = "block";
					elem.remove();
				}
			}).end();
	},

	hide: function(speed,callback){
		return speed ?
			this.animate({
				height: "hide", width: "hide", opacity: "hide"
			}, speed, callback) :

			this.filter(":visible").each(function(){
				this.oldblock = this.oldblock || jQuery.css(this,"display");
				this.style.display = "none";
			}).end();
	},

	// Save the old toggle function
	_toggle: jQuery.fn.toggle,

	toggle: function( fn, fn2 ){
		return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ?
			this._toggle.apply( this, arguments ) :
			fn ?
				this.animate({
					height: "toggle", width: "toggle", opacity: "toggle"
				}, fn, fn2) :
				this.each(function(){
					jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ]();
				});
	},

	slideDown: function(speed,callback){
		return this.animate({height: "show"}, speed, callback);
	},

	slideUp: function(speed,callback){
		return this.animate({height: "hide"}, speed, callback);
	},

	slideToggle: function(speed, callback){
		return this.animate({height: "toggle"}, speed, callback);
	},

	fadeIn: function(speed, callback){
		return this.animate({opacity: "show"}, speed, callback);
	},

	fadeOut: function(speed, callback){
		return this.animate({opacity: "hide"}, speed, callback);
	},

	fadeTo: function(speed,to,callback){
		return this.animate({opacity: to}, speed, callback);
	},

	animate: function( prop, speed, easing, callback ) {
		var optall = jQuery.speed(speed, easing, callback);

		return this[ optall.queue === false ? "each" : "queue" ](function(){
			if ( this.nodeType != 1)
				return false;

			var opt = jQuery.extend({}, optall), p,
				hidden = jQuery(this).is(":hidden"), self = this;

			for ( p in prop ) {
				if ( prop[p] == "hide" && hidden || prop[p] == "show" && !hidden )
					return opt.complete.call(this);

				if ( p == "height" || p == "width" ) {
					// Store display property
					opt.display = jQuery.css(this, "display");

					// Make sure that nothing sneaks out
					opt.overflow = this.style.overflow;
				}
			}

			if ( opt.overflow != null )
				this.style.overflow = "hidden";

			opt.curAnim = jQuery.extend({}, prop);

			jQuery.each( prop, function(name, val){
				var e = new jQuery.fx( self, opt, name );

				if ( /toggle|show|hide/.test(val) )
					e[ val == "toggle" ? hidden ? "show" : "hide" : val ]( prop );
				else {
					var parts = val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),
						start = e.cur(true) || 0;

					if ( parts ) {
						var end = parseFloat(parts[2]),
							unit = parts[3] || "px";

						// We need to compute starting value
						if ( unit != "px" ) {
							self.style[ name ] = (end || 1) + unit;
							start = ((end || 1) / e.cur(true)) * start;
							self.style[ name ] = start + unit;
						}

						// If a +=/-= token was provided, we're doing a relative animation
						if ( parts[1] )
							end = ((parts[1] == "-=" ? -1 : 1) * end) + start;

						e.custom( start, end, unit );
					} else
						e.custom( start, val, "" );
				}
			});

			// For JS strict compliance
			return true;
		});
	},

	queue: function(type, fn){
		if ( jQuery.isFunction(type) || ( type && type.constructor == Array )) {
			fn = type;
			type = "fx";
		}

		if ( !type || (typeof type == "string" && !fn) )
			return queue( this[0], type );

		return this.each(function(){
			if ( fn.constructor == Array )
				queue(this, type, fn);
			else {
				queue(this, type).push( fn );

				if ( queue(this, type).length == 1 )
					fn.call(this);
			}
		});
	},

	stop: function(clearQueue, gotoEnd){
		var timers = jQuery.timers;

		if (clearQueue)
			this.queue([]);

		this.each(function(){
			// go in reverse order so anything added to the queue during the loop is ignored
			for ( var i = timers.length - 1; i >= 0; i-- )
				if ( timers[i].elem == this ) {
					if (gotoEnd)
						// force the next step to be the last
						timers[i](true);
					timers.splice(i, 1);
				}
		});

		// start the next in the queue if the last step wasn't forced
		if (!gotoEnd)
			this.dequeue();

		return this;
	}

});

var queue = function( elem, type, array ) {
	if ( elem ){

		type = type || "fx";

		var q = jQuery.data( elem, type + "queue" );

		if ( !q || array )
			q = jQuery.data( elem, type + "queue", jQuery.makeArray(array) );

	}
	return q;
};

jQuery.fn.dequeue = function(type){
	type = type || "fx";

	return this.each(function(){
		var q = queue(this, type);

		q.shift();

		if ( q.length )
			q[0].call( this );
	});
};

jQuery.extend({

	speed: function(speed, easing, fn) {
		var opt = speed && speed.constructor == Object ? speed : {
			complete: fn || !fn && easing ||
				jQuery.isFunction( speed ) && speed,
			duration: speed,
			easing: fn && easing || easing && easing.constructor != Function && easing
		};

		opt.duration = (opt.duration && opt.duration.constructor == Number ?
			opt.duration :
			jQuery.fx.speeds[opt.duration]) || jQuery.fx.speeds.def;

		// Queueing
		opt.old = opt.complete;
		opt.complete = function(){
			if ( opt.queue !== false )
				jQuery(this).dequeue();
			if ( jQuery.isFunction( opt.old ) )
				opt.old.call( this );
		};

		return opt;
	},

	easing: {
		linear: function( p, n, firstNum, diff ) {
			return firstNum + diff * p;
		},
		swing: function( p, n, firstNum, diff ) {
			return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
		}
	},

	timers: [],
	timerId: null,

	fx: function( elem, options, prop ){
		this.options = options;
		this.elem = elem;
		this.prop = prop;

		if ( !options.orig )
			options.orig = {};
	}

});

jQuery.fx.prototype = {

	// Simple function for setting a style value
	update: function(){
		if ( this.options.step )
			this.options.step.call( this.elem, this.now, this );

		(jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );

		// Set display property to block for height/width animations
		if ( this.prop == "height" || this.prop == "width" )
			this.elem.style.display = "block";
	},

	// Get the current size
	cur: function(force){
		if ( this.elem[this.prop] != null && this.elem.style[this.prop] == null )
			return this.elem[ this.prop ];

		var r = parseFloat(jQuery.css(this.elem, this.prop, force));
		return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0;
	},

	// Start an animation from one number to another
	custom: function(from, to, unit){
		this.startTime = now();
		this.start = from;
		this.end = to;
		this.unit = unit || this.unit || "px";
		this.now = this.start;
		this.pos = this.state = 0;
		this.update();

		var self = this;
		function t(gotoEnd){
			return self.step(gotoEnd);
		}

		t.elem = this.elem;

		jQuery.timers.push(t);

		if ( jQuery.timerId == null ) {
			jQuery.timerId = setInterval(function(){
				var timers = jQuery.timers;

				for ( var i = 0; i < timers.length; i++ )
					if ( !timers[i]() )
						timers.splice(i--, 1);

				if ( !timers.length ) {
					clearInterval( jQuery.timerId );
					jQuery.timerId = null;
				}
			}, 13);
		}
	},

	// Simple 'show' function
	show: function(){
		// Remember where we started, so that we can go back to it later
		this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
		this.options.show = true;

		// Begin the animation
		this.custom(0, this.cur());

		// Make sure that we start at a small width/height to avoid any
		// flash of content
		if ( this.prop == "width" || this.prop == "height" )
			this.elem.style[this.prop] = "1px";

		// Start by showing the element
		jQuery(this.elem).show();
	},

	// Simple 'hide' function
	hide: function(){
		// Remember where we started, so that we can go back to it later
		this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
		this.options.hide = true;

		// Begin the animation
		this.custom(this.cur(), 0);
	},

	// Each step of an animation
	step: function(gotoEnd){
		var t = now();

		if ( gotoEnd || t > this.options.duration + this.startTime ) {
			this.now = this.end;
			this.pos = this.state = 1;
			this.update();

			this.options.curAnim[ this.prop ] = true;

			var done = true;
			for ( var i in this.options.curAnim )
				if ( this.options.curAnim[i] !== true )
					done = false;

			if ( done ) {
				if ( this.options.display != null ) {
					// Reset the overflow
					this.elem.style.overflow = this.options.overflow;

					// Reset the display
					this.elem.style.display = this.options.display;
					if ( jQuery.css(this.elem, "display") == "none" )
						this.elem.style.display = "block";
				}

				// Hide the element if the "hide" operation was done
				if ( this.options.hide )
					this.elem.style.display = "none";

				// Reset the properties, if the item has been hidden or shown
				if ( this.options.hide || this.options.show )
					for ( var p in this.options.curAnim )
						jQuery.attr(this.elem.style, p, this.options.orig[p]);
			}

			if ( done )
				// Execute the complete function
				this.options.complete.call( this.elem );

			return false;
		} else {
			var n = t - this.startTime;
			this.state = n / this.options.duration;

			// Perform the easing function, defaults to swing
			this.pos = jQuery.easing[this.options.easing || (jQuery.easing.swing ? "swing" : "linear")](this.state, n, 0, 1, this.options.duration);
			this.now = this.start + ((this.end - this.start) * this.pos);

			// Perform the next step of the animation
			this.update();
		}

		return true;
	}

};

jQuery.extend( jQuery.fx, {
	speeds:{
		slow: 600,
 		fast: 200,
 		// Default speed
 		def: 400
	},
	step: {
		scrollLeft: function(fx){
			fx.elem.scrollLeft = fx.now;
		},

		scrollTop: function(fx){
			fx.elem.scrollTop = fx.now;
		},

		opacity: function(fx){
			jQuery.attr(fx.elem.style, "opacity", fx.now);
		},

		_default: function(fx){
			fx.elem.style[ fx.prop ] = fx.now + fx.unit;
		}
	}
});
// The Offset Method
// Originally By Brandon Aaron, part of the Dimension Plugin
// http://jquery.com/plugins/project/dimensions
jQuery.fn.offset = function() {
	var left = 0, top = 0, elem = this[0], results;

	if ( elem ) with ( jQuery.browser ) {
		var parent       = elem.parentNode,
		    offsetChild  = elem,
		    offsetParent = elem.offsetParent,
		    doc          = elem.ownerDocument,
		    safari2      = safari && parseInt(version) < 522 && !/adobeair/i.test(userAgent),
		    css          = jQuery.curCSS,
		    fixed        = css(elem, "position") == "fixed";

		// Use getBoundingClientRect if available
		if ( elem.getBoundingClientRect ) {
			var box = elem.getBoundingClientRect();

			// Add the document scroll offsets
			add(box.left + Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft),
				box.top  + Math.max(doc.documentElement.scrollTop,  doc.body.scrollTop));

			// IE adds the HTML element's border, by default it is medium which is 2px
			// IE 6 and 7 quirks mode the border width is overwritable by the following css html { border: 0; }
			// IE 7 standards mode, the border is always 2px
			// This border/offset is typically represented by the clientLeft and clientTop properties
			// However, in IE6 and 7 quirks mode the clientLeft and clientTop properties are not updated when overwriting it via CSS
			// Therefore this method will be off by 2px in IE while in quirksmode
			add( -doc.documentElement.clientLeft, -doc.documentElement.clientTop );

		// Otherwise loop through the offsetParents and parentNodes
		} else {

			// Initial element offsets
			add( elem.offsetLeft, elem.offsetTop );

			// Get parent offsets
			while ( offsetParent ) {
				// Add offsetParent offsets
				add( offsetParent.offsetLeft, offsetParent.offsetTop );

				// Mozilla and Safari > 2 does not include the border on offset parents
				// However Mozilla adds the border for table or table cells
				if ( mozilla && !/^t(able|d|h)$/i.test(offsetParent.tagName) || safari && !safari2 )
					border( offsetParent );

				// Add the document scroll offsets if position is fixed on any offsetParent
				if ( !fixed && css(offsetParent, "position") == "fixed" )
					fixed = true;

				// Set offsetChild to previous offsetParent unless it is the body element
				offsetChild  = /^body$/i.test(offsetParent.tagName) ? offsetChild : offsetParent;
				// Get next offsetParent
				offsetParent = offsetParent.offsetParent;
			}

			// Get parent scroll offsets
			while ( parent && parent.tagName && !/^body|html$/i.test(parent.tagName) ) {
				// Remove parent scroll UNLESS that parent is inline or a table to work around Opera inline/table scrollLeft/Top bug
				if ( !/^inline|table.*$/i.test(css(parent, "display")) )
					// Subtract parent scroll offsets
					add( -parent.scrollLeft, -parent.scrollTop );

				// Mozilla does not add the border for a parent that has overflow != visible
				if ( mozilla && css(parent, "overflow") != "visible" )
					border( parent );

				// Get next parent
				parent = parent.parentNode;
			}

			// Safari <= 2 doubles body offsets with a fixed position element/offsetParent or absolutely positioned offsetChild
			// Mozilla doubles body offsets with a non-absolutely positioned offsetChild
			if ( (safari2 && (fixed || css(offsetChild, "position") == "absolute")) ||
				(mozilla && css(offsetChild, "position") != "absolute") )
					add( -doc.body.offsetLeft, -doc.body.offsetTop );

			// Add the document scroll offsets if position is fixed
			if ( fixed )
				add(Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft),
					Math.max(doc.documentElement.scrollTop,  doc.body.scrollTop));
		}

		// Return an object with top and left properties
		results = { top: top, left: left };
	}

	function border(elem) {
		add( jQuery.curCSS(elem, "borderLeftWidth", true), jQuery.curCSS(elem, "borderTopWidth", true) );
	}

	function add(l, t) {
		left += parseInt(l, 10) || 0;
		top += parseInt(t, 10) || 0;
	}

	return results;
};


jQuery.fn.extend({
	position: function() {
		var left = 0, top = 0, results;

		if ( this[0] ) {
			// Get *real* offsetParent
			var offsetParent = this.offsetParent(),

			// Get correct offsets
			offset       = this.offset(),
			parentOffset = /^body|html$/i.test(offsetParent[0].tagName) ? { top: 0, left: 0 } : offsetParent.offset();

			// Subtract element margins
			// note: when an element has margin: auto the offsetLeft and marginLeft 
			// are the same in Safari causing offset.left to incorrectly be 0
			offset.top  -= num( this, 'marginTop' );
			offset.left -= num( this, '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) && jQuery.css(offsetParent, 'position') == 'static') )
			offsetParent = offsetParent.offsetParent;
		return jQuery(offsetParent);
	}
});


// Create scrollLeft and scrollTop methods
jQuery.each( ['Left', 'Top'], function(i, name) {
	var method = 'scroll' + name;
	
	jQuery.fn[ method ] = function(val) {
		if (!this[0]) return;

		return val != undefined ?

			// Set the scroll offset
			this.each(function() {
				this == window || this == document ?
					window.scrollTo(
						!i ? val : jQuery(window).scrollLeft(),
						 i ? val : jQuery(window).scrollTop()
					) :
					this[ method ] = val;
			}) :

			// Return the scroll offset
			this[0] == window || this[0] == document ?
				self[ i ? 'pageYOffset' : 'pageXOffset' ] ||
					jQuery.boxModel && document.documentElement[ method ] ||
					document.body[ method ] :
				this[0][ method ];
	};
});
// Create innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Height", "Width" ], function(i, name){

	var tl = i ? "Left"  : "Top",  // top or left
		br = i ? "Right" : "Bottom"; // bottom or right

	// innerHeight and innerWidth
	jQuery.fn["inner" + name] = function(){
		return this[ name.toLowerCase() ]() +
			num(this, "padding" + tl) +
			num(this, "padding" + br);
	};

	// outerHeight and outerWidth
	jQuery.fn["outer" + name] = function(margin) {
		return this["inner" + name]() +
			num(this, "border" + tl + "Width") +
			num(this, "border" + br + "Width") +
			(margin ?
				num(this, "margin" + tl) + num(this, "margin" + br) : 0);
	};

});})();

/* Copyright (c) 2007 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.
 *
 * Version: 1.0.2
 * Requires jQuery 1.1.3+
 * Docs: http://docs.jquery.com/Plugins/livequery
 */

(function($) {
	
$.extend($.fn, {
	livequery: function(type, fn, fn2) {
		var self = this, q;
		
		// Handle different call patterns
		if ($.isFunction(type))
			fn2 = fn, fn = type, type = undefined;
			
		// See if Live Query already exists
		$.each( $.livequery.queries, function(i, query) {
			if ( self.selector == query.selector && self.context == query.context &&
				type == query.type && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) )
					// Found the query, exit the each loop
					return (q = query) && false;
		});
		
		// Create new Live Query if it wasn't found
		q = q || new $.livequery(this.selector, this.context, type, fn, fn2);
		
		// Make sure it is running
		q.stopped = false;
		
		// Run it
		$.livequery.run( q.id );
		
		// Contnue the chain
		return this;
	},
	
	expire: function(type, fn, fn2) {
		var self = this;
		
		// Handle different call patterns
		if ($.isFunction(type))
			fn2 = fn, fn = type, type = undefined;
			
		// Find the Live Query based on arguments and stop it
		$.each( $.livequery.queries, function(i, query) {
			if ( self.selector == query.selector && self.context == query.context && 
				(!type || type == query.type) && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) && !this.stopped )
					$.livequery.stop(query.id);
		});
		
		// Continue the chain
		return this;
	}
});

$.livequery = function(selector, context, type, fn, fn2) {
	this.selector = selector;
	this.context  = context || document;
	this.type     = type;
	this.fn       = fn;
	this.fn2      = fn2;
	this.elements = [];
	this.stopped  = false;
	
	// The id is the index of the Live Query in $.livequery.queries
	this.id = $.livequery.queries.push(this)-1;
	
	// Mark the functions for matching later on
	fn.$lqguid = fn.$lqguid || $.livequery.guid++;
	if (fn2) fn2.$lqguid = fn2.$lqguid || $.livequery.guid++;
	
	// Return the Live Query
	return this;
};

$.livequery.prototype = {
	stop: function() {
		var query = this;
		
		if ( this.type )
			// Unbind all bound events
			this.elements.unbind(this.type, this.fn);
		else if (this.fn2)
			// Call the second function for all matched elements
			this.elements.each(function(i, el) {
				query.fn2.apply(el);
			});
			
		// Clear out matched elements
		this.elements = [];
		
		// Stop the Live Query from running until restarted
		this.stopped = true;
	},
	
	run: function() {
		// Short-circuit if stopped
		if ( this.stopped ) return;
		var query = this;
		
		var oEls = this.elements,
			els  = $(this.selector, this.context),
			nEls = els.not(oEls);
		
		// Set elements to the latest set of matched elements
		this.elements = els;
		
		if (this.type) {
			// Bind events to newly matched elements
			nEls.bind(this.type, this.fn);
			
			// Unbind events to elements no longer matched
			if (oEls.length > 0)
				$.each(oEls, function(i, el) {
					if ( $.inArray(el, els) < 0 )
						$.event.remove(el, query.type, query.fn);
				});
		}
		else {
			// Call the first function for newly matched elements
			nEls.each(function() {
				query.fn.apply(this);
			});
			
			// Call the second function for elements no longer matched
			if ( this.fn2 && oEls.length > 0 )
				$.each(oEls, function(i, el) {
					if ( $.inArray(el, els) < 0 )
						query.fn2.apply(el);
				});
		}
	}
};

$.extend($.livequery, {
	guid: 0,
	queries: [],
	queue: [],
	running: false,
	timeout: null,
	
	checkQueue: function() {
		if ( $.livequery.running && $.livequery.queue.length ) {
			var length = $.livequery.queue.length;
			// Run each Live Query currently in the queue
			while ( length-- )
				$.livequery.queries[ $.livequery.queue.shift() ].run();
		}
	},
	
	pause: function() {
		// Don't run anymore Live Queries until restarted
		$.livequery.running = false;
	},
	
	play: function() {
		// Restart Live Queries
		$.livequery.running = true;
		// Request a run of the Live Queries
		$.livequery.run();
	},
	
	registerPlugin: function() {
		$.each( arguments, function(i,n) {
			// Short-circuit if the method doesn't exist
			if (!$.fn[n]) return;
			
			// Save a reference to the original method
			var old = $.fn[n];
			
			// Create a new method
			$.fn[n] = function() {
				// Call the original method
				var r = old.apply(this, arguments);
				
				// Request a run of the Live Queries
				$.livequery.run();
				
				// Return the original methods result
				return r;
			}
		});
	},
	
	run: function(id) {
		if (id != undefined) {
			// Put the particular Live Query in the queue if it doesn't already exist
			if ( $.inArray(id, $.livequery.queue) < 0 )
				$.livequery.queue.push( id );
		}
		else
			// Put each Live Query in the queue if it doesn't already exist
			$.each( $.livequery.queries, function(id) {
				if ( $.inArray(id, $.livequery.queue) < 0 )
					$.livequery.queue.push( id );
			});
		
		// Clear timeout if it already exists
		if ($.livequery.timeout) clearTimeout($.livequery.timeout);
		// Create a timeout to check the queue and actually run the Live Queries
		$.livequery.timeout = setTimeout($.livequery.checkQueue, 20);
	},
	
	stop: function(id) {
		if (id != undefined)
			// Stop are particular Live Query
			$.livequery.queries[ id ].stop();
		else
			// Stop all Live Queries
			$.each( $.livequery.queries, function(id) {
				$.livequery.queries[ id ].stop();
			});
	}
});

// Register core DOM manipulation methods
$.livequery.registerPlugin('append', 'prepend', 'after', 'before', 'wrap', 'attr', 'removeAttr', 'addClass', 'removeClass', 'toggleClass', 'empty', 'remove');

// Run Live Queries when the Document is ready
$(function() { $.livequery.play(); });


// Save a reference to the original init method
var init = $.prototype.init;

// Create a new init method that exposes two new properties: selector and context
$.prototype.init = function(a,c) {
	// Call the original init and save the result
	var r = init.apply(this, arguments);
	
	// Copy over properties if they exist already
	if (a && a.selector)
		r.context = a.context, r.selector = a.selector;
		
	// Set properties
	if ( typeof a == 'string' )
		r.context = c || document, r.selector = a;
	
	// Return the result
	return r;
};

// Give the init function the jQuery prototype for later instantiation (needed after Rev 4091)
$.prototype.init.prototype = $.prototype;
	
})(jQuery);
/**
 * @name $.eready
 * @desc While a page is loading, call a given callback function as soon as a specific
 * element is loaded into the DOM, even before the full DOM has been loaded.
 * Executes the function within the context of the element. This means that when
 * the passed-in function is executed, the 'this' keyword points to the specific
 * DOM element.
 * @param  String   id  string ID of the element to wait for
 * @param  Function fn  function to call when the element is ready
 * @cat    Plugins/Event
 * @author rz
 * @example $.eready('pic', function(){ this.src = 'img.png'; });
 * Change the source of a specific image as soon as it is loaded into the
 * DOM (before the whole DOM is loaded). Chain multiple calls to $.eready().eready().
 */
 
(function($) {

$.oR = {
    stack: [],
	timer: null,
	run: function() {
		var i, o, f, l = $.oR.stack.length;
		
		for (i = 0; i < l; i++) {
			o = $($.oR.stack[i].id);
			
			if (o.length) {
				f = $.oR.stack[i].fn;
				if ( 'function' == typeof f ) {
					$.oR.stack[i] = $.oR.stack[--l];
					$.oR.stack.pop();
					f.apply(o, [$]);
				}
			}
		}
	},
	init: function(id, fn) {
	    
		$.oR.stack.push({id: id, fn: fn});
		if (null == $.oR.timer) {
			$.oR.timer = setInterval(
			    function() {
				    $.oR.run();
					if ($.isReady) {
						clearInterval($.oR.timer);
						$.oR.timer = null;
						$.oR.run();
					}
				}
				, 15);
		}
		return this;
	}
};
$.eready = $.oR.init;

})(jQuery);
/**
 * Popup init
 *
 * @name Utilites
 * @description utility function
 * @author rz <roman@plotinka.ru>
 * @require utilites.js
 * @data   21.06.2008 
 * @version 1.0.0
 */
 
;(function($) {
/*
 // Настройки попапа по умолчанию
	iLeft       : 0,
	iTop        : 0,
	iWidth      : 600,
	iHeight     : 640,
	sToolbar    : 'no',
	sMenubar    : 'no',
	sResizeable : 'yes',
	sScrollbars : 'yes',
	sStatus     : 'yes'
*/

$(document).ready(
    function() {

	    $('a[@class^=popup]').each(
		    function(i) {
			
				var oLink   = $(this), 
					oOption = {}, 
					aWidth  = oLink.attr('class').match( new RegExp('w(\\d+)') ), 
					aHeight = oLink.attr('class').match( new RegExp('h(\\d+)') ), 
					aClass  =  oLink.attr('class').match( new RegExp('popup(\\w*)') );

				if ( null != aWidth ) {
					oOption['iWidth'] = aWidth[1];
				}
				
				if ( null != aHeight ) {
					oOption['iHeight'] = aHeight[1];
				}
				
				switch (aClass[1]) {
				 // Обратная связь (без status и resize)
					case '1':
					case '2': {
						oOption['sResizeable'] = 'no';
						oOption['sStatus']     = 'no';
						oOption['iWidth']      = 640;
						oOption['iHeight']     = 600;
					}
					break;
			     // Фотогалерея (без status и resize и scrolling)
					case '3': {
						oOption['sScrollbars'] = 'no';
						oOption['sStatus']     = 'no';
						oOption['sResizeable'] = 'no';
					}
					break;
				 // Медиа (без status и resize и scrolling)
					case '4': {
						oOption['sResizeable'] = 'no';
						oOption['sStatus']     = 'no';
						oOption['iWidth']      = 450;
						oOption['iHeight']     = 640;
					}
					break;
					default: {}
				}
						
			    $(this).click(
				    function(oOption) {
					
					    return function() {
						    window.Utils ? Utils.Popup(this.href, 'popup' + i, oOption) : false;
							return false;
						}
						
					}(oOption)
				);
				
			}
		);

	}
);

})(jQuery);
;(function($) {

	$.oNavigator = {
	    go: function(event) {
		
			if ( window.event ) {
			    event = window.event;
			}

			if ( event.ctrlKey ) {

				var href = null;

				switch ( event.keyCode ? event.keyCode : event.which ? event.which : null ) {
					case 0x25: {
						href = $('link[@rel=prev]').attr('href');
					}
					break;
					case 0x27: {
						href = $('link[@rel=next]').attr('href');
					}
					break;
					case 0x26: {
						href = $('link[@rel=up]').attr('href');
					}
					break;
					case 0x28: {
						href = $('link[@rel=down]').attr('href');
					}
					break;
					case 0x24: {
						href = '/';
					}
					break;
				}

				if ( href ) {
				    document.location = href;
				}
			}	
		
		}

	};

	$(document).keydown($.oNavigator.go);

})(jQuery);
/*
 * jQuery UI 1.6b
 *
 * Copyright (c) 2008 Paul Bakaus (ui.jquery.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
;(function($) {

// This adds a selector to check if data exists.
jQuery.extend(jQuery.expr[':'], { 
	data: "jQuery.data(a, m[3])"
});

$.ui = {
	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) { return; }
			
			for (var i = 0; i < set.length; i++) {
				if (instance.options[set[i][0]]) {
					set[i][1].apply(instance.element, args);
				}
			}
		}	
	},
	cssCache: {},
	css: function(name) {
		if ($.ui.cssCache[name]) { return $.ui.cssCache[name]; }
		var tmp = $('<div class="ui-gen">').addClass(name).css({position:'absolute', top:'-5000px', left:'-5000px', display:'block'}).appendTo('body');
		
		//if (!$.browser.safari)
			//tmp.appendTo('body'); 
		
		//Opera and Safari set width and height to 0px instead of auto
		//Safari returns rgba(0,0,0,0) when bgcolor is not set
		$.ui.cssCache[name] = !!(
			(!(/auto|default/).test(tmp.css('cursor')) || (/^[1-9]/).test(tmp.css('height')) || (/^[1-9]/).test(tmp.css('width')) || 
			!(/none/).test(tmp.css('backgroundImage')) || !(/transparent|rgba\(0, 0, 0, 0\)/).test(tmp.css('backgroundColor')))
		);
		try { $('body').get(0).removeChild(tmp.get(0));	} catch(e){}
		return $.ui.cssCache[name];
	},
	disableSelection: function(el) {
		$(el).attr('unselectable', 'on').css('MozUserSelect', 'none').bind('selectstart', function() { return false; });
	},
	enableSelection: function(el) {
		$(el).attr('unselectable', 'off').css('MozUserSelect', '').unbind('selectstart');
	},
	hasScroll: function(e, a) {
		var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop',
			has = false;
		
		if (e[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
		e[scroll] = 1;
		has = (e[scroll] > 0);
		e[scroll] = 0;
		return has;
	}
};


/** jQuery core modifications and additions **/

var _remove = $.fn.remove;
$.fn.remove = function() {
	$("*", this).add(this).triggerHandler("remove");
	return _remove.apply(this, arguments );
};

// $.widget is a factory to create jQuery plugins
// taking some boilerplate code out of the plugin code
// created by Scott GonzГЎlez and JГ¶rn Zaefferer
function getter(namespace, plugin, method) {
	var methods = $[namespace][plugin].getter || [];
	methods = (typeof methods == "string" ? methods.split(/,?\s+/) : methods);
	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);
		
		if (isMethodCall && getter(namespace, name, options)) {
			var instance = $.data(this[0], name);
			return (instance ? instance[options].apply(instance, args)
				: undefined);
		}
		
		return this.each(function() {
			var instance = $.data(this, name);
			if (isMethodCall && instance && $.isFunction(instance[options])) {
				instance[options].apply(instance, args);
			} else if (!isMethodCall) {
				$.data(this, name, new $[namespace][name](this, options));
			}
		});
	};
	
	// create widget constructor
	$[namespace][name] = function(element, options) {
		var self = this;
		
		this.widgetName = name;
		this.widgetEventPrefix = $[namespace][name].eventPrefix || name;
		this.widgetBaseClass = namespace + '-' + name;
		
		this.options = $.extend({}, $.widget.defaults, $[namespace][name].defaults, options);
		this.element = $(element)
			.bind('setData.' + name, function(e, key, value) {
				return self.setData(key, value);
			})
			.bind('getData.' + name, function(e, key) {
				return self.getData(key);
			})
			.bind('remove', function() {
				return self.destroy();
			});
		this.init();
	};
	
	// add widget prototype
	$[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);
};

$.widget.prototype = {
	init: function() {},
	destroy: function() {
		this.element.removeData(this.widgetName);
	},
	
	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');
		}
	},
	
	enable: function() {
		this.setData('disabled', false);
	},
	disable: function() {
		this.setData('disabled', true);
	},
	
	trigger: function(type, e, data) {
		var eventName = (type == this.widgetEventPrefix
			? type : this.widgetEventPrefix + type);
		e = e  || $.event.fix({ type: eventName, target: this.element[0] });
		return this.element.triggerHandler(eventName, [e, data], this.options[type]);
	}
};

$.widget.defaults = {
	disabled: false
};


/** Mouse Interaction Plugin **/

$.ui.mouse = {
	mouseInit: function() {
		var self = this;
	
		this.element.bind('mousedown.'+this.widgetName, function(e) {
			return self.mouseDown(e);
		});
		
		// 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(e) {
		// we may have missed mouseup (out of window)
		(this._mouseStarted && this.mouseUp(e));
		
		this._mouseDownEvent = e;
		
		var self = this,
			btnIsLeft = (e.which == 1),
			elIsCancel = (typeof this.options.cancel == "string" ? $(e.target).parents().add(e.target).filter(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this.mouseCapture(e)) {
			return true;
		}
		
		this._mouseDelayMet = !this.options.delay;
		if (!this._mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				self._mouseDelayMet = true;
			}, this.options.delay);
		}
		
		if (this.mouseDistanceMet(e) && this.mouseDelayMet(e)) {
			this._mouseStarted = (this.mouseStart(e) !== false);
			if (!this._mouseStarted) {
				e.preventDefault();
				return true;
			}
		}
		
		// these delegates are required to keep context
		this._mouseMoveDelegate = function(e) {
			return self.mouseMove(e);
		};
		this._mouseUpDelegate = function(e) {
			return self.mouseUp(e);
		};
		$(document)
			.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);
		
		return false;
	},
	
	mouseMove: function(e) {
		// IE mouseup check - mouseup happened when mouse was out of window
		if ($.browser.msie && !e.button) {
			return this.mouseUp(e);
		}
		
		if (this._mouseStarted) {
			this.mouseDrag(e);
			return false;
		}
		
		if (this.mouseDistanceMet(e) && this.mouseDelayMet(e)) {
			this._mouseStarted =
				(this.mouseStart(this._mouseDownEvent, e) !== false);
			(this._mouseStarted ? this.mouseDrag(e) : this.mouseUp(e));
		}
		
		return !this._mouseStarted;
	},
	
	mouseUp: function(e) {
		$(document)
			.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);
		
		if (this._mouseStarted) {
			this._mouseStarted = false;
			this.mouseStop(e);
		}
		
		return false;
	},
	
	mouseDistanceMet: function(e) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - e.pageX),
				Math.abs(this._mouseDownEvent.pageY - e.pageY)
			) >= this.options.distance
		);
	},
	
	mouseDelayMet: function(e) {
		return this._mouseDelayMet;
	},
	
	// These are placeholder methods, to be overriden by extending plugin
	mouseStart: function(e) {},
	mouseDrag: function(e) {},
	mouseStop: function(e) {},
	mouseCapture: function(e) { return true; }
};

$.ui.mouse.defaults = {
	cancel: null,
	distance: 1,
	delay: 0
};

})(jQuery);

/*
 * jQuery UI Tabs
 *
 * Copyright (c) 2007, 2008 Klaus Hartl (stilbuero.de)
 * 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() {
		this.options.event += '.tabs'; // namespace event
		
		// create tabs
		this.tabify(true);
	},
	setData: function(key, value) {
		if ((/^selected/).test(key))
			this.select(value);
		else {
			this.options[key] = value;
			this.tabify();
		}
	},
	length: function() {
		return this.$tabs.length;
	},
	tabId: function(a) {
		return a.title && a.title.replace(/\s/g, '_').replace(/[^A-Za-z0-9\-_:\.]/g, '')
			|| this.options.idPrefix + $.data(a);
	},
	ui: function(tab, panel) {
		return {
			options: this.options,
			tab: tab,
			panel: panel,
			index: this.$tabs.index(tab)
		};
	},
	tabify: function(init) {

		this.$lis = $('li:has(a[href])', this.element);
		this.$tabs = this.$lis.map(function() { return $('a', this)[0]; });
		this.$panels = $([]);

		var self = this, o = this.options;

		this.$tabs.each(function(i, a) {
			// inline tab
			if (a.hash && a.hash.replace('#', '')) // Safari 2 reports '#' for an empty hash
				self.$panels = self.$panels.add(a.hash);
			// remote tab
			else if ($(a).attr('href') != '#') { // prevent loading the page itself if href is just "#"
				$.data(a, 'href.tabs', a.href); // required for restore on destroy
				$.data(a, 'load.tabs', a.href); // mutable
				var id = self.tabId(a);
				a.href = '#' + id;
				var $panel = $('#' + id);
				if (!$panel.length) {
					$panel = $(o.panelTemplate).attr('id', id).addClass(o.panelClass)
						.insertAfter( self.$panels[i - 1] || self.element );
					$panel.data('destroy.tabs', true);
				}
				self.$panels = self.$panels.add( $panel );
			}
			// invalid tab href
			else
				o.disabled.push(i + 1);
		});

		if (init) {

			// attach necessary classes for styling if not present
			this.element.addClass(o.navClass);
			this.$panels.each(function() {
				var $this = $(this);
				$this.addClass(o.panelClass);
			});

			// 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.$tabs.each(function(i, a) {
						if (a.hash == location.hash) {
							o.selected = i;
							// prevent page scroll to fragment
							if ($.browser.msie || $.browser.opera) { // && !o.remote
								var $toShow = $(location.hash), toShowId = $toShow.attr('id');
								$toShow.attr('id', '');
								setTimeout(function() {
									$toShow.attr('id', toShowId); // restore id
								}, 500);
							}
							scrollTo(0, 0);
							return false; // break
						}
					});
				}
				else if (o.cookie) {
					var index = parseInt($.cookie('ui-tabs' + $.data(self.element)),10);
					if (index && self.$tabs[index])
						o.selected = index;
				}
				else if (self.$lis.filter('.' + o.selectedClass).length)
					o.selected = self.$lis.index( self.$lis.filter('.' + o.selectedClass)[0] );
			}
			o.selected = o.selected === null || o.selected !== undefined ? o.selected : 0; // first tab selected by default

			// 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('.' + o.disabledClass),
					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(o.hideClass);
			this.$lis.removeClass(o.selectedClass);
			if (o.selected !== null) {
				this.$panels.eq(o.selected).show().removeClass(o.hideClass); // use show and remove class to show in any case no matter how it has been hidden before
				this.$lis.eq(o.selected).addClass(o.selectedClass);
				
				// seems to be expected behavior that the show callback is fired
				var onShow = function() {
					self.trigger('show', null,
						self.ui(self.$tabs[o.selected], self.$panels[o.selected]));
				};

				// load if remote tab
				if ($.data(this.$tabs[o.selected], 'load.tabs'))
					this.load(o.selected, onShow);
				// just trigger show event
				else
					onShow();
			}
			
			// clean up to avoid memory leaks in certain versions of IE 6
			$(window).bind('unload', function() {
				self.$tabs.unbind('.tabs');
				self.$lis = self.$tabs = self.$panels = null;
			});

		}

		// disable tabs
		for (var i = 0, li; li = this.$lis[i]; i++)
			$(li)[$.inArray(i, o.disabled) != -1 && !$(li).hasClass(o.selectedClass) ? 'addClass' : 'removeClass'](o.disabledClass);

		// reset cache if switching from cached to not cached
		if (o.cache === false)
			this.$tabs.removeData('cache.tabs');
		
		// set up animations
		var hideFx, showFx, baseFx = { 'min-width': 0, duration: 1 }, baseDuration = 'normal';
		if (o.fx && o.fx.constructor == Array)
			hideFx = o.fx[0] || baseFx, showFx = o.fx[1] || baseFx;
		else
			hideFx = showFx = o.fx || baseFx;

		// reset some styles to maintain print style sheets etc.
		var resetCSS = { display: '', overflow: '', height: '' };
		if (!$.browser.msie) // not in IE to prevent ClearType font issue
			resetCSS.opacity = '';

		// Hide a tab, animation prevents browser scrolling to fragment,
		// $show is optional.
		function hideTab(clicked, $hide, $show) {
			$hide.animate(hideFx, hideFx.duration || baseDuration, function() { //
				$hide.addClass(o.hideClass).css(resetCSS); // maintain flexible height and accessibility in print etc.
				if ($.browser.msie && hideFx.opacity)
					$hide[0].style.filter = '';
				if ($show)
					showTab(clicked, $show, $hide);
			});
		}

		// Show a tab, animation prevents browser scrolling to fragment,
		// $hide is optional.
		function showTab(clicked, $show, $hide) {
			if (showFx === baseFx)
				$show.css('display', 'block'); // prevent occasionally occuring flicker in Firefox cause by gap between showing and hiding the tab panels
			$show.animate(showFx, showFx.duration || baseDuration, function() {
				$show.removeClass(o.hideClass).css(resetCSS); // maintain flexible height and accessibility in print etc.
				if ($.browser.msie && showFx.opacity)
					$show[0].style.filter = '';

				// callback
				self.trigger('show', null, self.ui(clicked, $show[0]));
			});
		}

		// switch a tab
		function switchTab(clicked, $li, $hide, $show) {
			/*if (o.bookmarkable && trueClick) { // add to history only if true click occured, not a triggered click
				$.ajaxHistory.update(clicked.hash);
			}*/
			$li.addClass(o.selectedClass)
				.siblings().removeClass(o.selectedClass);
			hideTab(clicked, $hide, $show);
		}

		// attach tab event handler, unbind to avoid duplicates from former tabifying...
		this.$tabs.unbind('.tabs').bind(o.event, function() {

			//var trueClick = e.clientX; // add to history only if true click occured, not a triggered click
			var $li = $(this).parents('li:eq(0)'),
				$hide = self.$panels.filter(':visible'),
				$show = $(this.hash);

			// If tab is already selected and not unselectable 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(o.selectedClass) && !o.unselect)
				|| $li.hasClass(o.disabledClass) 
				|| $(this).hasClass(o.loadingClass)
				|| self.trigger('select', null, self.ui(this, $show[0])) === false
				) {
				this.blur();
				return false;
			}

			self.options.selected = self.$tabs.index(this);

			// if tab may be closed
			if (o.unselect) {
				if ($li.hasClass(o.selectedClass)) {
					self.options.selected = null;
					$li.removeClass(o.selectedClass);
					self.$panels.stop();
					hideTab(this, $hide);
					this.blur();
					return false;
				} else if (!$hide.length) {
					self.$panels.stop();
					var a = this;
					self.load(self.$tabs.index(this), function() {
						$li.addClass(o.selectedClass).addClass(o.unselectClass);
						showTab(a, $show);
					});
					this.blur();
					return false;
				}
			}

			if (o.cookie)
				$.cookie('ui-tabs' + $.data(self.element), self.options.selected, o.cookie);

			// stop possibly running animations
			self.$panels.stop();

			// show new tab
			if ($show.length) {

				// prevent scrollbar scrolling to 0 and than back in IE7, happens only if bookmarking/history is enabled
				/*if ($.browser.msie && o.bookmarkable) {
					var showId = this.hash.replace('#', '');
					$show.attr('id', '');
					setTimeout(function() {
						$show.attr('id', showId); // restore id
					}, 0);
				}*/

				var a = this;
				self.load(self.$tabs.index(this), $hide.length ? 
					function() {
						switchTab(a, $li, $hide, $show);
					} :
					function() {
						$li.addClass(o.selectedClass);
						showTab(a, $show);
					}
				);

				// Set scrollbar to saved position - need to use timeout with 0 to prevent browser scroll to target of hash
				/*var scrollX = window.pageXOffset || document.documentElement && document.documentElement.scrollLeft || document.body.scrollLeft || 0;
				var scrollY = window.pageYOffset || document.documentElement && document.documentElement.scrollTop || document.body.scrollTop || 0;
				setTimeout(function() {
					scrollTo(scrollX, scrollY);
				}, 0);*/

			} 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 in modern
			// browsers via CSS, also blur removes focus from address bar in Firefox
			// which can become a usability and annoying problem with tabsRotate.
			if ($.browser.msie)
				this.blur();

			//return o.bookmarkable && !!trueClick; // convert trueClick == undefined to Boolean required in IE
			return false;

		});

		// disable click if event is configured to something else
		if (!(/^click/).test(o.event))
			this.$tabs.bind('click.tabs', function() { return false; });

	},
	add: function(url, label, index) {
		if (index == undefined) 
			index = this.$tabs.length; // append by default

		var o = this.options;
		var $li = $(o.tabTemplate.replace(/#\{href\}/g, url).replace(/#\{label\}/g, label));
		$li.data('destroy.tabs', true);

		var id = url.indexOf('#') == 0 ? url.replace('#', '') : this.tabId( $('a:first-child', $li)[0] );

		// try to find an existing element before creating a new one
		var $panel = $('#' + id);
		if (!$panel.length) {
			$panel = $(o.panelTemplate).attr('id', id)
				.addClass(o.hideClass)
				.data('destroy.tabs', true);
		}
		$panel.addClass(o.panelClass);
		if (index >= this.$lis.length) {
			$li.appendTo(this.element);
			$panel.appendTo(this.element[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.$tabs.length == 1) {
			$li.addClass(o.selectedClass);
			$panel.removeClass(o.hideClass);
			var href = $.data(this.$tabs[0], 'load.tabs');
			if (href)
				this.load(index, href);
		}

		// callback
		this.trigger('add', null, this.ui(this.$tabs[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(o.selectedClass) && this.$tabs.length > 1)
			this.select(index + (index + 1 < this.$tabs.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;
			
		var $li = this.$lis.eq(index).removeClass(o.disabledClass);
		if ($.browser.safari) { // fix disappearing tab (that used opacity indicating disabling) after enabling in Safari 2...
			$li.css('display', 'inline-block');
			setTimeout(function() {
				$li.css('display', 'block');
			}, 0);
		}

		o.disabled = $.grep(o.disabled, function(n, i) { return n != index; });

		// callback
		this.trigger('enable', null, this.ui(this.$tabs[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(o.disabledClass);

			o.disabled.push(index);
			o.disabled.sort();

			// callback
			this.trigger('disable', null, this.ui(this.$tabs[index], this.$panels[index]));
		}
	},
	select: function(index) {
		if (typeof index == 'string')
			index = this.$tabs.index( this.$tabs.filter('[href$=' + index + ']')[0] );
		this.$tabs.eq(index).trigger(this.options.event);
	},
	load: function(index, callback) { // callback is for internal usage only
		
		var self = this, o = this.options, $a = this.$tabs.eq(index), a = $a[0],
				bypassCache = callback == undefined || callback === false, url = $a.data('load.tabs');

		callback = callback || function() {};
		
		// no remote or from cache - just finish with callback
		if (!url || !bypassCache && $.data(a, 'cache.tabs')) {
			callback();
			return;
		}

		// load remote from here on
		
		var inner = function(parent) {
			var $parent = $(parent), $inner = $parent.find('*:last');
			return $inner.length && $inner.is(':not(img)') && $inner || $parent;
		};
		var cleanup = function() {
			self.$tabs.filter('.' + o.loadingClass).removeClass(o.loadingClass)
						.each(function() {
							if (o.spinner)
								inner(this).parent().html(inner(this).data('label.tabs'));
						});
			self.xhr = null;
		};
		
		if (o.spinner) {
			var label = inner(a).html();
			inner(a).wrapInner('<em></em>')
				.find('em').data('label.tabs', label).html(o.spinner);
		}

		var ajaxOptions = $.extend({}, o.ajaxOptions, {
			url: url,
			success: function(r, s) {
				$(a.hash).html(r);
				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.$tabs[index], self.$panels[index]));
				o.ajaxOptions.success && o.ajaxOptions.success(r, s);
				
				// This callback is required because the switch has to take
				// place after loading has completed. Call last in order to 
				// fire load before show callback...
				callback();
			}
		});
		if (this.xhr) {
			// terminate pending requests from other tabs and restore tab label
			this.xhr.abort();
			cleanup();
		}
		$a.addClass(o.loadingClass);
		setTimeout(function() { // timeout is again required in IE, "wait" for id being restored
			self.xhr = $.ajax(ajaxOptions);
		}, 0);

	},
	url: function(index, url) {
		this.$tabs.eq(index).removeData('cache.tabs').data('load.tabs', url);
	},
	destroy: function() {
		var o = this.options;
		this.element.unbind('.tabs')
			.removeClass(o.navClass).removeData('tabs');
		this.$tabs.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.add(this.$panels).each(function() {
			if ($.data(this, 'destroy.tabs'))
				$(this).remove();
			else
				$(this).removeClass([o.selectedClass, o.unselectClass,
					o.disabledClass, o.panelClass, o.hideClass].join(' '));
		});
	}
});

$.ui.tabs.defaults = {
	// basic setup
	unselect: false,
	event: 'click',
	disabled: [],
	cookie: null, // e.g. { expires: 7, path: '/', domain: 'jquery.com', secure: true }
	// TODO history: false,

	// Ajax
	spinner: 'Loading&#8230;',
	cache: false,
	idPrefix: 'ui-tabs-',
	ajaxOptions: {},

	// animations
	fx: null, // e.g. { height: 'toggle', opacity: 'toggle', duration: 200 }

	// templates
	tabTemplate: '<li><a href="#{href}"><span>#{label}</span></a></li>',
	panelTemplate: '<div></div>',

	// CSS classes
	navClass: 'ui-tabs-nav',
	selectedClass: 'ui-tabs-selected',
	unselectClass: 'ui-tabs-unselect',
	disabledClass: 'ui-tabs-disabled',
	panelClass: 'ui-tabs-panel',
	hideClass: 'ui-tabs-hide',
	loadingClass: 'ui-tabs-loading'
};

$.ui.tabs.getter = "length";

/*
 * Tabs Extensions
 */

/*
 * Rotate
 */
$.extend($.ui.tabs.prototype, {
	rotation: null,
	rotate: function(ms, continuing) {
		
		continuing = continuing || false;
		
		var self = this, t = this.options.selected;
		
		function start() {
			self.rotation = setInterval(function() {
				t = ++t < self.$tabs.length ? t : 0;
				self.select(t);
			}, ms); 
		}
		
		function stop(e) {
			if (!e || e.clientX) { // only in case of a true click
				clearInterval(self.rotation);
			}
		}
		
		// start interval
		if (ms) {
			start();
			if (!continuing)
				this.$tabs.bind(this.options.event, stop);
			else
				this.$tabs.bind(this.options.event, function() {
					stop();
					t = self.options.selected;
					start();
				});
		}
		// stop interval
		else {
			stop();
			this.$tabs.unbind(this.options.event, stop);
		}
	}
});

})(jQuery);

/**
 * Floating Windows
 *
 * @name FW
 * @description Create a floating windows
 * @param All parameters are optional
 * @cat Plugins/Interface
 * @author rz <roman@plotinka.ru>
 * @version 4.0.0
 * @depends ui.core.js, effects.core.js, effects.transfer.js, ui.resizable.js, ui.draggable.js
 */
 
(function($) {

if ('undefined' == typeof $.oFW) {
	$.oFW = {};
}

$.extend($.oFW, {
    fw: [],
    
    conf: {
		is_closable:         1,
		is_dragable:         1,
		is_resizable:        1,
		is_visible_button:   1,
		open_in_the_centre:  1,
		win_min_width:       200,
		win_min_height:      220,
		win_max_width:       1200,
		win_max_height:      1000
	},
	
	fw_init: function(options) {

	    if ( 0 == this.length ) {
		    return false;
		}
		
		options = options || {};
		
		$.extend($.oFW.conf, options);
		
	    var FWL     = $(this).find('a[@href*=#fw]'),
		    sLength = FWL.length, 
			iOffset = i = 0, 
			iNeedle = 15, 
			iCol    = parseInt(sLength / iNeedle), 
			iRem    = sLength - iCol * iNeedle;
        
		iCol += iRem ? 1 : 0;
		
		if ( 0 == sLength ) {
			return this;
		}
			
	    (function() {
			if ( i ) {
			
			    if ( iCol ) {
				    
					$.oFW.fw_init_win(FWL, iOffset, iOffset + iNeedle);
					setTimeout(arguments.callee, 0);
					
					iOffset = iOffset + iNeedle;
					iCol--;
					
				}
			
			} else {
				i++;
				setTimeout(arguments.callee, 0);
			}
		})();
		
		return this;
	},

	fw_init_win: function(FWL, i, sLength) {
	    
	    for ( i; i < sLength; i++ ) {

		    if ( !FWL[i] ) {
			    break;
			}
			
			var FWlink = $(FWL[i]), 
			    FWid   = FWlink.attr('href').substr(FWlink.attr('href').indexOf('#') + 1), 
				FW     = $('#' + FWid);
				
			if ( 0 == FW.length ) {
				continue;
			}
			
			FWlink.attr({'id': 'fwlink' + FWid, 'href': '', 'rel': FWid});
                
            $('#fwlink' + FWid).livequery(
                function() {
                    $(this).click(
                    
                        function() {
                            var oSelf = $(this), oFW = $('#' + oSelf.attr('rel'));
                            oSelf.blur();
                            
                            if ( 'none' == oFW.css('display') ) {
                                oFW.fw_open();
                            } else {
                                oFW.fw_close();
                            }
                            
                            return false;
                        }
                        
                    );
                }
            );
			
			if ( $.oFW.fw[FWid] || -1 != FW.attr('class').indexOf('fwin0') ) {
				continue;
			}
			
			$.oFW.fw[FWid] = 1;
			
			FW.fw_init_win_button();
			  //.fw_set_win_pos();

		}
		
		return this;
	},
	
 	fw_init_win_button: function() {
		
	    if ( 0 == this.length ) {
		    return this;
		}
		
		var oFW = this;
		
		$.extend(this, {
			oCont:  $('div.fwcontent'),
			oClose: $.oFW.conf['is_closable'] ? $('#' + this.attr('id') + 'close').css('display', ( $.oFW.conf['is_visible_button'] ? 'block' : 'none' )) : null,
			oDrag:  $.oFW.conf['is_dragable'] ? $('#' + this.attr('id') + 'drag').css('display', ( $.oFW.conf['is_visible_button'] ? 'block' : 'none' )) : null
		});
		
     // Close
        if ( $.oFW.conf['is_closable'] ) {
    		$('#' + this.oClose.attr('id')).livequery(
    		    function() {
    			    $(this).click(
                        function() {
                            oFW.fw_close();
                        }
                    );
    			}
    		);
        }
        
     // Dragable 
        if ( $.oFW.conf['is_dragable'] ) {
            $('#' + this.attr('id')).livequery(
                function() {
                    oFW.draggable({ opacity: 0.40, handle: '#' + oFW.oDrag.attr('id') }); 
                }
            );
        }

     // Resize
		if ( $.oFW.conf['is_resizable'] ) {
			$('#' + this.attr('id')).livequery(
                function() {
                    oFW.resizable({ handles: 'all', minWidth: $.oFW.conf['win_min_width']  || 200, minHeight: $.oFW.conf['win_min_height'] || 220, maxWidth: $.oFW.conf['win_max_width']  || 1200, maxHeight: $.oFW.conf['win_max_height'] || 1000, ghost: true, transparent: true, helper: 'proxy' });  
                }
            );
		}
        
		//$(this.oCont).fw_init();
		
		return this;
	},
	
    fw_open: function() {

        var oFW = $(this);

        if ( -1 != oFW.attr('class').indexOf('fwin0') ) {
        
            oFW.show();
            
        } else {
        
            oFW.fw_set_win_pos();

            $('#fwlink' + oFW.attr('id')).effect(
                'transfer', 
                { to: '#' + oFW.attr('id'), className: 'transferor' }, 
                500, 
                function() { 
                    
					
					if ( $.browser.msie ) {
					    oFW.show();
					} else {
					    oFW[0].style.display = 'table'; 
					}

                }
            );
               
        }

        return oFW;
    
    },
    
    fw_close: function() {
    
        var oFW = $(this);
        
        if ( -1 != oFW.attr('class').indexOf('fwin0') ) {
        
            oFW.hide();
            
        } else {
        
            if ( !$.oFW.conf['is_visible_button'] ) {
                oFW.hideButton();
            }

            oFW.effect(
                'transfer', 
                { to: '#fwlink' + oFW.attr('id'), className: 'transferor' }, 
                500
            ).hide();
               
        }
        
        return oFW;
            
    },
            
	fw_set_win_pos: function(o) {
		
	    if ( !o || 0 == o.length ) {
			if ( 1 == this.length && 'fw' == this.attr('id').substr(0, 2) ) {
				o = this;
			} else {
			    o = $(this).find('div[@id^=fw]');
			}
		}
		
		if (0 == o.length || 'absolute' != o.css('position')) {
		    return false;
		}
		
	 // [bug] ie resize fix
	//  $(window).ieresizefix(o.fw_set_win_pos);
		o.each(
			function(i) {
				var l, t, o = $(this), 
				    oh = o.height() || parseInt(o.css('height'), 10) || 0, 
					ow = o.width() || parseInt(o.css('width'), 10) || 0, 
					bh = $(window).height() || 0, 
					bw = $(window).width() || 0,				
					oL = $('#fwlink' + o.attr('id')), oI = oL.find('img'), sw;
					if ( 0 != oI.length) {
					    oL = oI;
					}
					sw = parseInt(oL.css('width'), 10) || oL.width() || 0;
                    
				if ( $.oFW.conf['open_in_the_centre'] ) {
				
					l = Math.round( (bw - ow) / 2 ); 
				 // t = Math.round( (bh - oh) / 2 );
					t = (parseInt(document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop, 10) + parseInt(document.documentElement.clientHeight || document.body.clientHeight, 10) / 2 - oh / 2);

				} else {
				
					l = parseInt(oL.position().left, 10); 
					t = parseInt(oL.position().top, 10);

					if ( (l + ow + 10) > bw ) {
						l = (l - ow + sw > bw) ? bw - ow - 32 : l - ow + sw;
					}
                    
				}
      
				o.css({left: 0 > l ? 0 : l, top: 0 > t ? 0 : t });

			}
		);

	}
    
});

$.fn.extend(
    {
	    fw_init:                 $.oFW.fw_init,
		fw_init_win:             $.oFW.fw_init_win,
		fw_init_win_button:      $.oFW.fw_init_win_button,
        fw_open:                 $.oFW.fw_open,
        fw_close:                $.oFW.fw_close,
		fw_set_win_pos:          $.oFW.fw_set_win_pos
	}
);

})(jQuery);
/**
 * Entry-summary toggle
 * 
 * Copyright (c) 2007 CSC
 * Dual licensed under the MIT (MIT-LICENSE.txt) 
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * @description Create a entry-summary toggle
 * @param All parameters are optional
 * @author rz <roman@plotinka.ru>
 * @version 2.2.0
 */
(function($) {
if ('undefined' == typeof $.oHFeed) {
	$.oHFeed = {};
}

$.extend($.oHFeed, {
    conf: {
		is_animate:      1,
		hide_not_active: 1,
		hide_announce:   0,
		target:         '#entry-summary-scene'
	},
	
	active: -1,
	
	hfeed_entry_show: function(i) {
	
		var target   = $( $.oHFeed.conf['target'] ), 
		    active   = $('#hentry' + $.oHFeed.active), 
			current  = $('#hentry' + i),
			summary  = $('#entry-summary-' + i),
			asummary = $('#entry-summary-' + $.oHFeed.active);
			
		if ( $.oHFeed.conf['is_animate'] ) {
		
			if ( 0 != target.length ) {
				
                if ( 'none' == target.css('display') || i != $.oHFeed.active ) {
				
					if ( $.oHFeed.conf['hide_not_active'] && 'none' != target.css('display') ) {
						active.DropInUp(400);
					}
					
	                if ( 'none' != target.css('display') ) {
					
						target.DropOutDown(400, 
						    function() { 
							
							    if ( $.oHFeed.conf['hide_not_active'] ) {
								    current.DropOutUp(500);
								}
								
								asummary.empty().prepend( $(this).html() ); 
								
								$(this).empty().prepend( summary.html() ).DropInDown('500', 
									function() {
										$.oHFeed.active = i;
										summary.empty(); 
										
										//$.oHFeed.hfeed_fw_fix(target); // ???????????
									}
								);
						    }
						);
					
					} else {
					
						if ( $.oHFeed.conf['hide_not_active'] ) {
							current.DropOutUp(500);
						}
						
						target.empty().prepend( summary.html() ).DropInDown('600', 
							function() {
								$.oHFeed.active = i;
								
								summary.empty();

								//$.oHFeed.hfeed_fw_fix(target); //??????????????
							}
						);

					}

				
				} else {
				
					if ( $.oHFeed.conf['hide_not_active'] ) {
						active.DropInUp(400);
					}
					
					asummary.empty().prepend( target.html() );
					
					target.DropOutDown(500, 
					    function() {
						    $(this).empty();	
					    }
					);
					
				}
				

			} else {
			
                if ( 'none' == summary.css('display') ) {
				
					if ( $.oHFeed.conf['hide_announce'] ) {
						current.find('*[@class^=entry]').hide();
					}
							
					summary.DropInUp(900, 
						function() {
						    if ( i != $.oHFeed.active && 'none' != asummary.css('display') && $.oHFeed.conf['hide_not_active'] ) {
								if ( $.oHFeed.conf['hide_announce'] ) {
								    active.find('*[@class^=entry]').show();
								}
							    asummary.DropOutRight(450);
							}
							
							$.oHFeed.active = i;
							
						}
					);
					
				} else {
					
					if ( $.oHFeed.conf['hide_announce'] ) {
					    current.find('*[@class^=entry]').show();
					}
				    summary.DropOutRight(450);
					$.oHFeed.active = i;
					
				}

			}
			
		} else {
		    
			if ( 0 != target.length ) {
			
				if ( $.oHFeed.conf['hide_not_active'] ) {
					current.hide();
				}
				

				if ( 'none' == target.css('display') || i != $.oHFeed.active ) {
				
					if ( $.oHFeed.conf['hide_not_active'] && i != $.oHFeed.active ) {
						active.show();
					}
					
				    target.empty().html( summary.html() ).show();
					summary.empty();

					//$.oHFeed.hfeed_fw_fix(target); //??????????????
								

				} else {
				
				    asummary.empty().prepend( target.html() ); 
					
					target.empty().hide();
					
					if ( $.oHFeed.conf['hide_not_active'] ) {
						active.show();
					}
				}

				$.oHFeed.active = i;
				
			} else {
				
				if ( 'none' == summary.css('display') ) {
					if ( $.oHFeed.conf['hide_announce'] ) {
					    current.find('*[@class^=entry]').hide().end().find('address').hide();
					}
				    summary.show().find('address').show();
				} else {
					if ( $.oHFeed.conf['hide_announce'] ) {
					    current.find('*[@class^=entry]').show().end().find('address').show();
					}
				    summary.hide();
				}
				
				if ( i != $.oHFeed.active && $.oHFeed.conf['hide_not_active'] ) {
					if ( $.oHFeed.conf['hide_announce'] ) {
					    active.find('*[@class^=entry]').show().end().find('address').show();
					}
				    asummary.hide();
				}
				
				$.oHFeed.active = i;
					
			}
			
		}
		
	 // [bug] fix fw position
		if ( 0 != target.length && 'none' != target.css('display') ) {
			target.fw_set_win_pos();
		} else if ( 'none' != summary.css('display') ) {
		    current.fw_set_win_pos();
		}


		return false;
	},
	
	hfeed_navbar_init: function(options) {
	    
	    if ( 0 == this.length ) {
		    return false;
		}
		
		var _self = $(this);
		
		options = options || {};
		
		$.extend($.oHFeed.conf, options);
		
		_self.find('div.zentry').each( 
		    function(i) {
			    var zentry = $(this);
				zentry
				    .attr('id', 'zentry-' + i)
				    .find('img.entry-thumbnail, a.internal-link')
					.click( 
						function() {
							$.oHFeed.hfeed_entry_show(i);
							zentry.hfeed_navbar_entry_show(i);
							$.oHFeed.hfeed_fix(i);
							return false;							
						}
					);
					
		    } 
		);

		return this;
	},
	
	hfeed_navbar_entry_show: function(i) {
		
	    var zentry = (null == i) ? this : $('#zentry-' + i);
		
	    if ( 0 == zentry.length ) {
		    return false;
		}
		
		if ( -1 == zentry.attr('class').indexOf('selected') ) {
			zentry.parent().find('div.selected').removeClass('selected').css('z-index', 1);
			zentry.addClass('selected').css('z-index', 500);
		} else {
			zentry.parent().find('div.selected').removeClass('selected').css('z-index', 1);
		}
		
		return this;
	},
	
	hfeed_fix: function(i) {
	    if ( null == i ) {
		    return false;
		}

		$('#entry-summary-scene a[@rel="bookmark"]')
			.livequery(
				function() { 
				    $(this).bind(
					    'click',
					    function() {
							$.oHFeed.hfeed_entry_show(i);
							$(this).unbind('click');
							return false; 
						}
					);
				}
			);
			
		return false;
	},
	
	hfeed_set_link_toggle: function(HF, i, sLength) {

	    for ( i; i < sLength; i++ ) {
		
		    if ( !HF[i] ) {
			    break;
			}
				
			var entry = $(HF[i]).attr('id', 'hentry' + i);
			
			entry.find('div.entry-summary').attr('id', 'entry-summary-' + i);
			
			entry.find('a[@rel="bookmark"]')
				.filter('#entry-summary-' + i + ' a')
				.addClass('internal-link')
				.bind(
					'click', 
					function(i) { 
					    return function() {
		
							$.oHFeed.hfeed_entry_show(i);
							$.oHFeed.hfeed_navbar_entry_show(i);
							$.oHFeed.hfeed_fix(i);
							
							return false; 
							
						}
					}(i)
				);
				
		}

	},
	
	hfeed_init: function(options) {
	    
	    if ( 0 == this.length ) {
		    return false;
		}

		options = options || {};
		
		$.extend($.oHFeed.conf, options);

	    var HF      = $(this).find('div.hentry'), 
		    sLength = HF.length, 
			iOffset = i = 0, 
			iNeedle = 15, 
			iCol    = parseInt(sLength / iNeedle), 
			iRem    = sLength - iCol * iNeedle;
        
		iCol += iRem ? 1 : 0;
		
	    (function() {
			if ( i ) {
			
			    if ( iCol ) {
				
					$.oHFeed.hfeed_set_link_toggle(HF, iOffset, iOffset + iNeedle);
					setTimeout(arguments.callee, 0);
					
					iOffset = iOffset + iNeedle;
					iCol--;
					
				}
			
			} else {
				i++;
				setTimeout(arguments.callee, 0);
			}
		})();
		
		return this;
	}
});

$.fn.extend(
    {
	    hfeed_init:              $.oHFeed.hfeed_init,
	    hfeed_navbar_init:       $.oHFeed.hfeed_navbar_init,
		hfeed_navbar_entry_show: $.oHFeed.hfeed_navbar_entry_show
	}
);

})(jQuery);
/*
 * Metadata - jQuery plugin for parsing metadata from elements
 *
 * Copyright (c) 2006 John Resig, Yehuda Katz, JпїЅГ¶rn Zaefferer, Paul McLanahan
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.metadata.js 3640 2007-10-11 18:34:38Z pmclanahan $
 *
 */

/**
 * Sets the type of metadata to use. Metadata is encoded in JSON, and each property
 * in the JSON will become a property of the element itself.
 *
 * There are three supported types of metadata storage:
 *
 *   attr:  Inside an attribute. The name parameter indicates *which* attribute.
 *          
 *   class: Inside the class attribute, wrapped in curly braces: { }
 *   
 *   elem:  Inside a child element (e.g. a script tag). The
 *          name parameter indicates *which* element.
 *          
 * The metadata for an element is loaded the first time the element is accessed via jQuery.
 *
 * As a result, you can define the metadata type, use $(expr) to load the metadata into the elements
 * matched by expr, then redefine the metadata type and run another $(expr) for other elements.
 * 
 * @name $.metadata.setType
 *
 * @example <p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p>
 * @before $.metadata.setType("class")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from the class attribute
 * 
 * @example <p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p>
 * @before $.metadata.setType("attr", "data")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a "data" attribute
 * 
 * @example <p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a p</p>
 * @before $.metadata.setType("elem", "script")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a nested script element
 * 
 * @param String type The encoding type
 * @param String name The name of the attribute to be used to get metadata (optional)
 * @cat Plugins/Metadata
 * @descr Sets the type of encoding to be used when loading metadata for the first time
 * @type undefined
 * @see metadata()
 */

;(function($) {

$.extend({
	metadata : {
		defaults : {
			type: 'class',
			name: 'metadata',
			cre: /({.*})/,
			single: 'metadata'
		},
		setType: function( type, name ){
			this.defaults.type = type;
			this.defaults.name = name;
		},
		get: function( elem, opts ){
			var settings = $.extend({},this.defaults,opts);
			// check for empty string in single property
			if ( !settings.single.length ) settings.single = 'metadata';
			
			var data = $.data(elem, settings.single);
			// returned cached data if it already exists
			if ( data ) return data;
			
			data = "{}";
			
			if ( settings.type == "class" ) {
				var m = settings.cre.exec( elem.className );
				if ( m )
					data = m[1];
			} else if ( settings.type == "elem" ) {
				if( !elem.getElementsByTagName ) return;
				var e = elem.getElementsByTagName(settings.name);
				if ( e.length )
					data = $.trim(e[0].innerHTML);
			} else if ( elem.getAttribute != undefined ) {
				var attr = elem.getAttribute( settings.name );
				if ( attr )
					data = attr;
			}
			
			if ( data.indexOf( '{' ) <0 )
			data = "{" + data + "}";
			
			data = eval("(" + data + ")");
			
			$.data( elem, settings.single, data );
			return data;
		}
	}
});

/**
 * Returns the metadata object for the first member of the jQuery object.
 *
 * @name metadata
 * @descr Returns element's metadata object
 * @param Object opts An object contianing settings to override the defaults
 * @type jQuery
 * @cat Plugins/Metadata
 */
$.fn.metadata = function( opts ){
	return $.metadata.get( this[0], opts );
};

})(jQuery);
/**
 * Viewer
 *
 * @name Viewer
 * @description Create a plugin for image zooming
 * @param All parameters are optional
 * @param Array img_ext ['png', 'jpg', 'jpeg', 'gif']
 * @param Bool hide_on_content_click  Hides photo when cliked on zoomed item (true by default)
 * @param Integer zoom_speed_in Speed in miliseconds of the zooming-in animation (no animation if 0) 
 * @param Integer zoom_speed_out Speed in miliseconds of the zooming-out animation (no animation if 0) 
 * @param Integer frame_width Default width for iframed and inline content 
 * @param Integer frame_height Default height for iframed and inline content 
 * @param Bool overlay_show If true, shows the overlay (false by default) 
 * @param Float overlay_opacity Opacity of overlay (from 0 to 1) 
 * @param Function item_load_callback Custom function to get group items  
 * @example $("#gallery a").iviewer({ 'zoom_speed_in': 0, 'zoom_speed_out': 0, 'overlay_show': true });
 * @cat Plugins/Interface
 * @author rz
 * @version 1.0.0
 * @requires jQuery v1.2.x or later
 *
 */

;(function($) {

	var imgPreloader = new Image/*, 
		loadingTimer, 
		loadingFrame = 1*/;
		
		
	$.oViewer = {
	
		aThumb: [],
		
		iSelected: 0,
		bAnimated: false,
		bOpened: false,
		
		conf: {
		    img_ext:                ['png', 'jpg', 'jpeg', 'gif'],
            video_ext:              ['flv'],
            flash_ext:              ['swf'],
			hide_on_content_click:	true,
			zoom_speed_in:		    500,
			zoom_speed_out:		    500,
			frame_width:		    600,
			frame_height:		    400,
			overlay_show:		    true,
			overlay_opacity:	    0.6,
			item_load_callback:	    null
		},
		
		init: function(options) { 
		
            var oSelf = $(this);
			
            if ( !oSelf.length ) {
			    return false;
			}
			
			oSelf.settings = $.extend({}, $.oViewer.conf, options || {});		

			$.oViewer.add_event(oSelf);
			
			return oSelf;
		
	    },

		add_event: function(oLink) { //<div id="iviewer-decorate"></div>     <div class="shadow-bg"></div>
        // <div class="shadow-left"><div></div>  </div><div class="shadow-right"><div></div></div><div class="shadow-top"><div></div></div>
		

        
		    $('body').prepend('<div id="iviewer"><div id="iviewer-wrap"><div id="iviewer-inner"><span id="iviewer-close">&nbsp;</span><span id="iviewer-navbar">&nbsp;</span><div id="iviewer-content">&nbsp;</div></div><dfn class="caption" id="iviewer-title">&nbsp;</dfn><div class="shadow-l"><div></div></div><div class="shadow-r"><div></div></div><div class="shadow-t"><div></div></div></div><div id="iviewer-preloader"></div></div>');
			
		 // open
			oLink.each(
			    function() {
					var oSelf = $(this), 
					    options = $.metadata ? $.extend({}, oLink.settings, oSelf.metadata()) : oLink.settings;

					oSelf.unbind('click').click(
					    function() {
						
							$.oViewer.open(this, options);
							return false;
							
					    }
					);
			    }
			);
			
		 // close
			$("#iviewer-close").click($.oViewer.close);
			
		},
		
		open: function(el, options) {
		
			if ( $.oViewer.bAnimated ) {
			    return false;
			}
			
			if ( options.overlay_show ) {
			
				$("#iviewer").prepend('<div id="iviewer-overlay"></div>');
				$("#iviewer-overlay").css({'width': $(document).width(), 'height': $(document).height(), 'opacity': options.overlay_opacity}).click($.oViewer.close);

				if ( $.browser.msie ) {
                
                    $("#iviewer-overlay").css({'width': $(window).width()});
					$("#iviewer").prepend('<iframe id="iviewer-overlayframe" scrolling="no" frameborder="0"></iframe>');
					$("#iviewer-overlayframe").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': 0});
				}
				
			}

			
			
			$.oViewer.iSelected = 0;
			$.oViewer.aThumb	= [];
			
			$.oViewer._get_thumb_array(el, options);
			
			$.oViewer.show_photo($.oViewer.iSelected);
		},
		
		close: function() {
		
		 // if not close
			if ( $.oViewer.bAnimated ) {
			    return false;
			}

			$(imgPreloader).unbind('load');
			$(document).unbind('keydown');

			$("#iviewer-preloader, #iviewer-title, #iviewer-close, #iviewer-decorate").hide();

			$("#iviewer-navbar").empty();
			
		
			$.oViewer.bOpened	= false;

			if ($.oViewer.aThumb[$.oViewer.iSelected].o.zoom_speed_out > 0) {
				var oPhoto = {
					'top':		$.oViewer.aThumb[$.oViewer.iSelected].osize.pos.top - 18,
					'left':		$.oViewer.aThumb[$.oViewer.iSelected].osize.pos.left - 18,
					'height':	$.oViewer.aThumb[$.oViewer.iSelected].osize.height,
					'width':	$.oViewer.aThumb[$.oViewer.iSelected].osize.width,
					'opacity':	'hide'
				};

				$.oViewer.bAnimated = true;

				$("#iviewer-wrap").animate(oPhoto, $.oViewer.aThumb[$.oViewer.iSelected].o.zoom_speed_out, function() {
					$("#iviewer-content").hide().empty();
					$("#iviewer-overlay, #iviewer-overlayframe").remove();
					$.oViewer.bAnimated = false;
				});

			} else {
				$("#iviewer-wrap").hide();
				$("#iviewer-content").hide().empty();
				$("#iviewer-overlay, #iviewer-overlayframe").fadeOut("fast").remove();
			}
		},
		
		reset: function() {
		
		    $('#iviewer-navbar').empty();
			$('#iviewer-wrap').stop();
			$('#iviewer-title').hide();
			
			$(document).unbind('keydown');
			
		},
		
	    animate_photo: function(val) {
		
			$.oViewer.preload_neighbor_images();

			var oViewer = $('#iviewer-wrap'),
			    aPagesize	= $.oViewer._get_page_size(), 
			    aPhotosize	= $.oViewer._get_max_size(aPagesize[0] - 50, aPagesize[1] - 100, $.oViewer.aThumb[$.oViewer.iSelected].o.frame_width, $.oViewer.aThumb[$.oViewer.iSelected].o.frame_height);
				
				//Vitaliy бордер у изображения
				//ToDo сделать нормальный пересчет
				aPhotosize[0] += 4; aPhotosize[1] += 4;
				
			if ( $.browser.msie && 6 == parseInt($.browser.version) ) {
			
				aPhotosize[0] = aPhotosize[0] + $.oViewer._get_prop_value(oViewer, 'paddingLeft') + $.oViewer._get_prop_value(oViewer, 'paddingRight');
				aPhotosize[1] = aPhotosize[1] + $.oViewer._get_prop_value(oViewer, 'paddingTop') + $.oViewer._get_prop_value(oViewer, 'paddingBottom');
				
			}
			
			/*
			ie6
			612 401
			
			ie7
			562 302
			
			сафари
			562 302
			
			firefox 
			562 302
			*/
			
			var	oPhoto = {
					'left':		aPagesize[2] + Math.round((aPagesize[0] - aPhotosize[0]) / 2) - 20, 
					'top':		aPagesize[3] + Math.round((aPagesize[1] - aPhotosize[1]) / 2) - 40, 
					'width':	aPhotosize[0] + 'px', 
					'height':	aPhotosize[1] + 'px'	
				};

         // Opened
			if ( $.oViewer.bOpened ) {

				$('#iviewer-content').fadeOut('normal', 
				    function() {
					
						$('#iviewer-content').empty();
						
						if ( $.browser.msie && 6 == parseInt($.browser.version) ) {

                            var iW = oViewer.width() + $.oViewer._get_prop_value(oViewer, 'paddingRight') + $.oViewer._get_prop_value(oViewer, 'paddingLeft'), 
                                iH = oViewer.height() + $.oViewer._get_prop_value(oViewer, 'paddingTop') + $.oViewer._get_prop_value(oViewer, 'paddingBottom'),
                                oP = {};
                                
                            if ( iW != parseInt(oPhoto.width) ) {
                                oP.width = oPhoto.width;
                            }
                            if ( iH != parseInt(oPhoto.height) ) {
                                oP.height = oPhoto.height;
                            }
                            
                            oPhoto = $.extend({
                                'left': oPhoto.left,
                                'top': oPhoto.top
                            }, oP);
                            
						}
                        
						
						oViewer.animate(oPhoto, 'normal', 
						    function() {
							
								$('#iviewer-content')
								    .append($(val))
									.fadeIn('normal');
								
								$.oViewer.update();
								
						    }
						);

				    }
				);

			} else {
			
				$.oViewer.bOpened = true;

				$("#iviewer-content").empty();

             // animate
				if ( $.oViewer.aThumb[$.oViewer.iSelected].o.zoom_speed_in > 0 ) {
				
					$.oViewer.bAnimated = true;
					oPhoto.opacity	    = 'show';

					oViewer.css(
					    {
							'top':		$.oViewer.aThumb[$.oViewer.iSelected].osize.pos.top - 18,
							'left':		$.oViewer.aThumb[$.oViewer.iSelected].osize.pos.left - 18,
							'height':	$.oViewer.aThumb[$.oViewer.iSelected].osize.height,
							'width':	$.oViewer.aThumb[$.oViewer.iSelected].osize.width
					    }
					);

					$("#iviewer-content").append($(val)).show();

					oViewer.animate(oPhoto, $.oViewer.aThumb[$.oViewer.iSelected].o.zoom_speed_in, 
						function() {
							$.oViewer.bAnimated = false;
							$.oViewer.update();
						}
					);

				} else {

					$("#iviewer-content").append($(val)).show();
					oViewer.css(oPhoto).width(parseInt(oPhoto.width)).height(parseInt(oPhoto.height)).show();
/*				
					console.log( 'Height: ' + parseInt(oPhoto.height) + oViewer.height() + ' ' + oViewer.css('height') );
					console.log( 'Width: ' + parseInt(oPhoto.width) + oViewer.width() + ' ' + oViewer.css('width') );
*/
					$.oViewer.update();
					
				}
			}
		
		
		},
 		
		show_photo: function(n) {
		
			$.oViewer.iSelected = n;
			$.oViewer.show_preloader();
			$.oViewer.reset();
			
			var sImgSrc = $.oViewer.aThumb[n].url;
			
		    switch($.oViewer._get_type(n)) {
			    case 'images': {
				
					$(imgPreloader)
					    .unbind('load')
						.bind('load', 
						    function() {
							
							    $("#iviewer-preloader").hide();
								
								$.oViewer.aThumb[n].o.frame_width  = imgPreloader.width;
								$.oViewer.aThumb[n].o.frame_height = imgPreloader.height;

								$.oViewer.animate_photo('<img id="iviewer-img" width="' + imgPreloader.width + '" height="' + imgPreloader.height + '" alt="" src="' + imgPreloader.src + '" />');
                                
					        }
						).attr({'src': sImgSrc + '?rand=' + Math.floor(Math.random() * 999999999)} );
				
				}
				break;
			    case 'block': {
				
					var target = window.location.href.split('#')[0]; 
					target = sImgSrc.replace(target,'');
					
					$.oViewer.animate_photo('<div id="iviewer-block">' + $(target).html() + '</div>');
					
					$("#iviewer-preloader").hide();
				
				}
				break;
			    case 'video': {
				
					$.oViewer.animate_photo("<div id='player'>&nbsp;</div><script type='text/javascript'>swfobject.embedSWF( '/img/default/videoplayer/player.swf', 'player', '560', '348', '8', {}, { 'fsfile' : '" + (sImgSrc.match( new RegExp('\http:\/\/[^\/]*(.+)$', 'i') )[1]) + "', 'imageid': '' }, { 'wmode': 'opaque', 'bgcolor': '#f7f5ef' }, { 'menu': false } );</script>");
					
					$("#iviewer-preloader").hide();
				
				}
				break;
			    case 'iframe': {
				
				    $.oViewer.animate_photo('<iframe id="iviewer-iframe" onload="$.oViewer.show_iframe()" name="iviewer-iframe' + Math.round(Math.random() * 1000) + '" frameborder="0" hspace="0" src="' + sImgSrc + '"></iframe>');
					
				}
				break;
				default: {
				    return false;
				}
			}
			
		},
		
		show_iframe: function() {
		
			$("#iviewer-preloader").hide();
			$("#iviewer-iframe").show();
			
		},
		
		show_preloader: function() {
		
		    var aPagesize = $.oViewer._get_page_size();
			
		    $("#iviewer-preloader")
			    .css({'left': ((aPagesize[0] - 154) / 2 + aPagesize[2]), 'top': ((aPagesize[1] - 37) / 2 + aPagesize[3])})
				.show()
				.bind('click', $.oViewer.close);
/*
			clearInterval(loadingTimer);

			var aPagesize = $.oViewer._get_page_size();

			$("#iviewer-preloader")
			    .css({'left': ((aPagesize[0] - 40) / 2 + aPagesize[2]), 'top': ((aPagesize[1] - 40) / 2 + aPagesize[3])})
				.show()
				.bind('click', $.oViewer.close);

			loadingTimer = setInterval(
			
				function() {
				
					if ( !$("#iviewer-preloader").is(':visible') ) {
						clearInterval(loadingTimer);
						return;
					}

					$("#iviewer-preloader > div").css('top', (loadingFrame * -40) + 'px');

					loadingFrame = (loadingFrame + 1) % 12;
					
				}, 
				
			66);
*/
			
		},

		update: function() {
			$("#iviewer-decorate, #iviewer-close").show();

			if ( undefined !== $.oViewer.aThumb[$.oViewer.iSelected].title && $.oViewer.aThumb[$.oViewer.iSelected].title !== '' ) {
			
				$('#iviewer-title').html($.oViewer.aThumb[$.oViewer.iSelected].title).show();
				
			}

			if ( $.oViewer.aThumb[$.oViewer.iSelected].o.hide_on_content_click ) {
				$("#iviewer-content").click($.oViewer.close);
			} else {
				$("#iviewer-content").unbind('click');
			}

			if ( 0 != $.oViewer.iSelected ) {
			
				$("#iviewer-navbar").append('<a id="iviewer-llink" href="javascript:;"><span></span></a>');

				$('#iviewer-llink').click(
				    function() {
						$.oViewer.show_photo($.oViewer.iSelected - 1); 
						return false;
				    }
				);
				
			}

			if ( $.oViewer.iSelected != ($.oViewer.aThumb.length - 1) ) {
			
				$("#iviewer-navbar").append('<a id="iviewer-rlink" href="javascript:;"><span></span></a>');
				
				$('#iviewer-rlink').click(
				    function(){
					    $.oViewer.show_photo($.oViewer.iSelected + 1); 
						return false;
				    }
				);
				
			}

			$(document).keydown(
			    function(event) {
					if ( 27 == event.keyCode ) {
		            	$.oViewer.close();

					} else if ( 37 == event.keyCode && 0 != $.oViewer.iSelected ) {
		            	$.oViewer.show_photo($.oViewer.iSelected - 1);

					} else if ( 39 == event.keyCode  && $.oViewer.iSelected != ($.oViewer.aThumb.length - 1) ) {
		            	$.oViewer.show_photo($.oViewer.iSelected + 1);
					}
			    }
			);
			
		},
	
		preload_neighbor_images: function() {
		
			if ( ($.oViewer.aThumb.length - 1) > $.oViewer.iSelected ) {
				var next = new Image();
				next.src = $.oViewer.aThumb[$.oViewer.iSelected + 1].url;
			}

			if ( $.oViewer.iSelected > 0 ) {
				var prev = new Image();
				prev.src = $.oViewer.aThumb[$.oViewer.iSelected - 1].url;
			}
			
		},
		
		_get_thumb_array: function(el, options) {
		
			if ( $.isFunction(options.item_load_callback) ) {
			   	
			    options.item_load_callback.apply(this);
				
				var oImg  = $(el).children('img:first').length ? $(el).children('img:first') : $(el), 
				    oAttr = {'width': oImg.width(), 'height': oImg.height(), 'pos': $.oViewer._get_thumb_pos(oImg)}
				
				$.each(
				    $.oViewer.aThumb, 
				    function(i, v) {
					
						$.oViewer.aThumb[i].o = $.extend({}, options, v.o);
						
						if ( options.zoom_speed_in > 0 || options.zoom_speed_out > 0 ) {
							$.oViewer.aThumb[i].osize = oAttr;
						}
						
					}
				);

			} else {
			
			 // single
				if ( !el.rel || '' == el.rel ) {
				
					var oImg, 
					    oAttr = {url: el.href, title: el.title, o: options};

					if ( options.zoom_speed_in > 0 || options.zoom_speed_out > 0 ) {
						oImg = $(el).children('img:first').length ? $(el).children('img:first') : $(el);
						oAttr.osize = {'width': oImg.width(), 'height': oImg.height(), 'pos': $.oViewer._get_thumb_pos(oImg)}
					}

					$.oViewer.aThumb.push(oAttr);
					
			 // group
				} else {
				
					var oGroup = $('a[@rel=' + el.rel + ']').get();
					
					$.each(
					    oGroup, 
					    function(i, v) {
						    
		   					var oImg,
							    oAttr = {url: v.href, title: v.title, o: ( $.metadata ? $.extend({}, options, $(v).metadata()) : options )};
		   					if ( options.zoom_speed_in > 0 || options.zoom_speed_out > 0 ) {
                                
								oImg = $(v).children('img:first').length ? $(v).children('img:first') : $(el);
								oAttr.osize = {'width': oImg.width(), 'height': oImg.height(), 'pos': $.oViewer._get_thumb_pos(oImg)}
							}

							if ( v.href == el.href ) {
							    $.oViewer.iSelected = i;
							}

							$.oViewer.aThumb.push(oAttr);
							
							
						}
					);

				}
			}
			
			return $.oViewer.aThumb;
		
		},
		
		_get_type: function(n) {
		
			var sImgSrc = $.oViewer.aThumb[n].url, 
			    iType   = 0;

			if (sImgSrc.match( new RegExp('\.' + $.oViewer.aThumb[n].o['img_ext'].join('|') + '$', 'i') )) {
			
			    return 'images';
				
			} else if (sImgSrc.match( new RegExp('\.' + $.oViewer.aThumb[n].o['video_ext'].join('|') + '$', 'i') )) {
			
                return 'video';
                
			} else if (sImgSrc.match( new RegExp('\.' + $.oViewer.aThumb[n].o['flash_ext'].join('|') + '$', 'i') )) {
                
                return 'flash';
                
			} else if ( sImgSrc.match(/#/) ) {

				return 'block';

			} else {
			
			    return 'iframe';

			}
			
		},
		
		_get_prop_value: function (el, prop) {
			return parseInt($.curCSS(el.jquery ? el[0] : el, prop, true)) || 0;
		},
		
		_get_thumb_pos: function(el) {
			var oPos = el.offset();

			oPos.top	+= $.oViewer._get_prop_value(el, 'paddingTop');
			oPos.top	+= $.oViewer._get_prop_value(el, 'borderTopWidth');

	 		oPos.left += $.oViewer._get_prop_value(el, 'paddingLeft');
			oPos.left += $.oViewer._get_prop_value(el, 'borderLeftWidth');

			return oPos;
		},
		
		_get_page_scroll: function() {
			var xScroll, yScroll;

			if ( self.pageYOffset ) {
				yScroll = self.pageYOffset;
				xScroll = self.pageXOffset;
			} else if ( document.documentElement && document.documentElement.scrollTop ) {
				yScroll = document.documentElement.scrollTop;
				xScroll = document.documentElement.scrollLeft;
			} else if ( document.body ) {
				yScroll = document.body.scrollTop;
				xScroll = document.body.scrollLeft;	
			}

			return [xScroll, yScroll]; 
		},

		_get_page_size: function() {
			var scroll = $.oViewer._get_page_scroll();

			return [$(window).width(), $(window).height(), scroll[0], scroll[1]];
		},

		_get_max_size: function(maxWidth, maxHeight, imageWidth, imageHeight) {
			var r = Math.min(Math.min(maxWidth, imageWidth) / imageWidth, Math.min(maxHeight, imageHeight) / imageHeight);

			return [Math.round(r * imageWidth), Math.round(r * imageHeight)];
		}
	
	}
	
	$.fn.iviewer = $.oViewer.init;
	
})(jQuery);
/**
 * Preview Box
 *
 * @name PreviewBox
 * @description Create a box of preview
 * @param All parameters are optional
 * @example $('#preview-box').preview_box_init({
 *                  'preview_empty_image': '/image/n.gif',
 *                  'preview_page_container_id': '#preview-page'});
 *
 * @cat Plugins/Interface
 * @author Serge Fyodorov
 * @version 1.0.0
 * @depends ui.core.js
 *
 * @todo optimize if posible
 */
;(function($) {

    $.PreviewBox = function(container, options) {
        $.extend($.PreviewBox.conf, options || {});

    // Init object params
        this.oPreloader          = null;
        this.oBoxPreloader       = null; // Preloader 2
        this.oPreviewImages      = null;
        this.oPreviewLinks       = null;
        this.currentPageNumber   = 1;
        this.oPreviewContainer   = $(container);
        this.previewLoadInterval = undefined;

        this.ajaxRequestIndex    = 0;
        this.ajaxPreviewCount    = 0;
        
        this.oTooltips           = $('dfn.tooltip', container);
        
    // Set needed params
        this.init();
    };

    // Config
    $.PreviewBox.conf = {
        'preview_page_container_id':  '#preview-page',
        'preview_page_current_id':    'preview-current-page',
        'preview_preloader_image':    '/img/default/preloader.gif',
        'preview_empty_image':        '/img/n.gif',
        'preview_cover_class':        'preview-cover',

        'previewbox_preloader_image': '/img/default/preloader2.gif'
    };

    // Object Init
    $.PreviewBox.prototype.init = function() {

    // 1. Get preloader image
        if (false == this.setPreloader()) {
            return false;
        }
    // 2. Get first page on first visit
        this.getFirstVisitPage();

    // 3. Set link click handle
        if (false == this.setPageClickHandler()) {
            return false;
        }

        return true;
    };

    $.PreviewBox.prototype.getFirstVisitPage = function() {
        var url = window.location.toString();
        var arr = url.match(/\/pg([\d]+)\/{0,1}/);

        if (null != arr && 'undefined' != typeof arr && 'undefined' != typeof arr[1]) {
            this.currentPageNumber = arr[1];
        }
    };

    // Get object with needed params
    $.PreviewBox.prototype.LoadPreviewPage = function(pageUrl, pageNumber, pageObject) {

        if (this.currentPageNumber == pageNumber) {
            return false;
        }

        this.currentPageNumber = pageNumber;

        this.getAjaxJson(pageUrl);

        $('#' + $.PreviewBox.conf['preview_page_current_id']).removeAttr('id');
        $(pageObject).attr('id', $.PreviewBox.conf['preview_page_current_id']);

        return true;
    };

    $.PreviewBox.prototype.generateImgTags = function(count) {
        var tmp     = $('.' + $.PreviewBox.conf['preview_cover_class'], this.oPreviewContainer)[0];
        var example = $(tmp).clone();
        
        $(example).removeAttr('id')
                  .removeClass()
                  .addClass($.PreviewBox.conf['preview_cover_class']);

        var link = null;
        if ($(example).is('a')) {
            link = $(example);
        } else {
            link = $('a', example);
        }

        var img  = $('img', link);

        link[0].href  = '';
        link[0].title = '';
        img[0].alt    = '';
        img[0].src    = $.PreviewBox.conf['preview_empty_image'];

        var i = 0;
        for (i; i < count; ++i) {
            $(example).clone().prependTo(this.oPreviewContainer);
        }

        return true;
    };
    
    $.PreviewBox.prototype.updatePreviewBox = function(data) {
        if (false == this.getPreviewImages()) {
            return false;
        }

        if (null == data || 'undefined' == typeof data) {
            return false;
        }

        var previewCount = this.oPreviewImages.length;

        if (previewCount < this.ajaxPreviewCount) {
            var count = this.ajaxPreviewCount - previewCount

            if (false != this.generateImgTags(count)) {
                this.setPreviewSrc(data);
                return true;
            }
        } else {
            this.setPreviewSrc(data);
            return true;
        }

        return false;
    };

    $.PreviewBox.prototype.setPreviewSrc = function(data) {
        // 1. Get the object with previews
        if (false == this.getPreviewImages()) {
            return false;
        }

        var i = 0;
        var c = 0;
        var o = this;
        var maxPreviewImages = this.oPreviewImages.length;

        if (maxPreviewImages < this.ajaxPreviewCount) {
            this.generateImgTags(this.ajaxPreviewCount - maxPreviewImages);
        }

        if (typeof this.previewLoadInterval != 'undefined') {
            clearInterval(this.previewLoadInterval);
        }

        this.previewLoadInterval = setInterval(function() {
            // Preview images
            var oPpreview   = $(o.oPreviewImages).get(i);
            var sPreviewSrc = $.PreviewBox.conf['preview_empty_image'];
            var sPreviewAlt = '';

            // Preview Links
            var oLink       = $(o.oPreviewLinks).get(i);
            var sLinkHref   = '#';

            if ('undefined' != typeof data[i]
                    && 'undefined' != typeof data[i].src) {
                sPreviewSrc = data[i].src;
            }

            if ('undefined' != typeof data[i]
                    && 'undefined' != typeof data[i].alt) {
                sPreviewAlt = data[i].alt;
            }

            if ('undefined' != typeof data[i]
                    && 'undefined' != typeof data[i].href) {
                sLinkHref = data[i].href;
            }
            
            

            var posTop  = $(oPpreview).offset().top
                        - $(o.oPreviewContainer).offset().top
                        + ($(oPpreview).height() - $(o.oPreloader)[0].height) / 2;

            var posLeft = $(oPpreview).offset().left
                        - $(o.oPreviewContainer).offset().left
                        + ($(oPpreview).width() - $(o.oPreloader)[0].width) / 2;

            posTop  = Math.floor(posTop);
            posLeft = Math.floor(posLeft);

            var previewUid   = 'p' + posLeft + '-' + posTop;
            var preloaderUid = 'pp' + posLeft + '-' + posTop;

            var preloaderClone      = $(o.oPreloader).clone();
            $(preloaderClone)[0].id = preloaderUid;

            preloaderClone.addClass('preview-loader')
                          .css({'left': posLeft, 'top': posTop})
                          .appendTo($(o.oPreviewContainer));

            $(oPpreview).css('opacity', 0).bind('load', function() {
                var o2 = this;
var tmo = setTimeout(function() {
                //var id = '#p' + $(this)[0].id;
                var id = '#p' + $(o2)[0].id;

                $(o.oPreviewContainer).children(id).remove();

                //$(this).removeAttr('id').unbind('load').fadeTo(150, 1, function(){
                $(o2).removeAttr('id').unbind('load').fadeTo(150, 1, function(){
                    ++c;

                    if (c >= maxPreviewImages) {
                        c = 0;
                    }
                });
    clearInterval(tmo);
}, 50);

            });

            $(oPpreview)[0].id  = previewUid;
            $(oPpreview)[0].src = sPreviewSrc;
            $(oPpreview)[0].alt = sPreviewAlt;

            $(oLink)[0].href    = sLinkHref;
            //$(oLink)[0].title   = sPreviewAlt;
            
            if (o.oTooltips[i]) {
                $(o.oTooltips[i]).html(sPreviewAlt);
            }

            if (sPreviewSrc == $.PreviewBox.conf['preview_empty_image']) {
                $(oPpreview).css('cursor', 'default').unbind('click').bind('click', function() {
                    return false;
                });
            } else {
                $(oPpreview).css('cursor', 'pointer').unbind('click');
            }

            if (i >= maxPreviewImages - 1 && typeof o.previewLoadInterval != 'undefined') {
                clearInterval(o.previewLoadInterval);
            }

            ++i;
        }, 5);

        return true;
    };

    $.PreviewBox.prototype.getPreviewImages = function() {
        if ('object' != typeof this.oPreviewContainer
                || null == this.oPreviewContainer) {
            return false;
        }

        this.oPreviewLinks  = $('a', this.oPreviewContainer);
        this.oPreviewImages = $('img', this.oPreviewLinks);

        return true;
    };

    $.PreviewBox.prototype.setPreloader = function() {
        if (null == $.PreviewBox.conf['preview_preloader_image']
                || '' == $.PreviewBox.conf['preview_preloader_image']) {

            return false;
        }

        var o = this;

        var image = new Image();
        //image.height = 17;
        //image.width  = 17;
        image.src = $.PreviewBox.conf['preview_preloader_image'];
        $(image).bind('load', function() {
            $(this).unbind('load');
            o.oPreloader = $(this);
        });

        // Preloader 2
        if (null == $.PreviewBox.conf['previewbox_preloader_image']
                || '' == $.PreviewBox.conf['previewbox_preloader_image']) {

            return false;
        }

        var image2 = new Image();
        image2.src = $.PreviewBox.conf['previewbox_preloader_image'];
        $(image2).bind('load', function(){
            $(this).unbind('load');
            o.oBoxPreloader = $(this);
        });

        return true;
    };

    $.PreviewBox.prototype.setPageClickHandler = function() {
        if (null == $.PreviewBox.conf['preview_page_container_id']
                || '' == $.PreviewBox.conf['preview_page_container_id']) {
            return false;
        }

        var o           = this;
        var linksPrefix = '';
        var containerId = $.PreviewBox.conf['preview_page_container_id'];

        $('a', containerId).each(function(index) {
            var pageNum   = 0;
            var pageLink  = $(this).attr('href');
            var arr       = pageLink.match(/\/pg([\d]+)\//);

            if (null != arr && 'undefined' != typeof arr && 'undefined' != typeof arr[1]) {
                pageNum = arr[1];
            }

            if (0 != pageNum) {
                $(this).bind('click', function() {
                    o.LoadPreviewPage(pageLink, pageNum, this);
                    return false;
                });
            }
        });

        return true;
    };

    $.PreviewBox.prototype.getAjaxJson = function(url, params) {
        this.ajaxPreviewCount = 0;

        if (!params) {
            params = {};
        }

        var o = this;
        if (0 == this.ajaxRequestIndex) {

            var w = $(this.oPreviewContainer).width();
            var h = $(this.oPreviewContainer).height();

            $('.box-preloader', this.oPreviewContainer).remove();

            /*$('<div class="box-preloader"></div>').width(w).height(h).css({
                'background': '#fff',
                'left': 0,
                'opacity': .91,
                'position': 'absolute',
                'top': 0,
                'z-index': 1000
            }).appendTo($(this.oPreviewContainer));*/

            //var posX = Math.ceil((w - $(this.oBoxPreloader)[0].width) / 2);
            var posY = Math.floor((h - $(this.oBoxPreloader)[0].height) / 2 - 20);

            // :TODO: 20081126: May be make clone() ..?
            $('<div class="box-preloader"></div>').width(w).height(h).css({
                'background': '#fff url("'
                    + $.PreviewBox.conf['previewbox_preloader_image']
                    + '") 51% ' + posY + 'px no-repeat',
                'left': 0,
                'position': 'absolute',
                'top': 0,
                'z-index': 1000
            }).appendTo($(this.oPreviewContainer));

        }

        this.ajaxRequestIndex = this.currentPageNumber;

        params['ajax_is_request'] = 1;
        // :TODO: 20081126: May be get?)
        $.post(url, params, function(json) {

var tmo = setTimeout(function() {
            var oJSON = eval('(' + json + ')');

            if ('pb' + o.ajaxRequestIndex != oJSON.request_id && 'undefined' != typeof oJSON.request_id) {
                return false
            }
            
            o.ajaxRequestIndex = 0;
            o.ajaxPreviewCount = oJSON.preview_count;

            $('.box-preloader', o.oPreviewContainer).remove();
            o.updatePreviewBox(oJSON.preview);
}, 500);

        });
    };

    $.fn.extend({
        preview_box_init: function(options) {
            new $.PreviewBox(this, options);

            return this;
        }
    });

})(jQuery);
/**
 * Bubble tooltip.
 * 
 * @param Object Key/value pairs for overriding properties in TooltipGroup constructor.
 * @param Object Key/value pairs for overriding properties in oConfig.
 *
 * @example $('.mod-gallery').bubble_tooltip_init({nOffsetX: -20, nDelayShow: 0});
 * 
 * @cat Plugins/Interface
 * @author Aleksey Pushkaryov
 * @version 1.0.3
 *
 * @todo To change structure of plugin. It must be more understandable.
 */
;(function($) {
    /**
     * This constructor represents a group that contains
     * a tooltip and related hover element.
     */
    function TooltipGroup() {
        //--------------------------------------
        // Public properties
        //--------------------------------------
        this.nOffsetX      = 4;
        this.nOffsetY      = -4;
        this.nDelayShow    = 100;
        this.nDelayHide    = 600;
        this.bAbove        = true;
        this.bOnLeft       = true;
        this.bMoveUp       = true;
        this.bTtHover      = true;
        this.bAppendTtInBody = false; // sometimes may be useful
        this.oHover;
        this.oTooltip;
        this.onShow;
        //--------------------------------------
        // Public methods
        //--------------------------------------
        this.init = function() {
            if (!this.oHover || !this.oTooltip) {
                return;
            }
            $(this.bTtHover ? [this.oTooltip, this.oHover] : this.oHover)
                .mouseover(mouseover).mouseout(mouseout);
            if (this.bAppendTtInBody) {
                $("body").append(this.oTooltip);
            }
        }
        
        this.forceHide = function() {
            delTimerShow();
            delTimerHide();
            hide();
        }
        
        //======================================================================
        
        //--------------------------------------
        // Private properties
        //--------------------------------------
        var _nMoveRange = 10,
            _this = this, // link to "this" for private methods
            _nStartX,
            _nStartY,
            _nTimerShow,
            _nTimerHide,
            _bNeedShow = false;
        //--------------------------------------
        // Private methods
        //--------------------------------------
        function mouseover() {
            _bNeedShow = true;
            delTimerHide();
            if ("none" != $(_this.oTooltip).css("display") || "" == $(_this.oTooltip).html()) {
                return;
            }
            _nTimerShow = setTimeout(function() {
                var hov = _this.oHover, tt = _this.oTooltip;
                _nTimerShow = null;
                _this.onShow(_this);
                $(tt).css({display: "block", opacity: 0});
                
                _nStartX = $(hov)[_this.bAppendTtInBody ? "offset" : "position"]().left
                    + (_this.bOnLeft ? 0 : hov.offsetWidth) + _this.nOffsetX;
                
                _nStartY = $(hov)[_this.bAppendTtInBody ? "offset" : "position"]().top
                    + (_this.bAbove ? -tt.offsetHeight : hov.offsetHeight)
                    + _this.nOffsetY + _nMoveRange * (_this.bMoveUp ? 1 : -1);
                
                $(tt).css({left: _nStartX, top: _nStartY}).stop()
                    .animate(
                        {top: _nStartY - _nMoveRange * (_this.bMoveUp ? 1 : -1), opacity: 1},
                        200, "swing"
                    );
            }, _this.nDelayShow);
        }
        function mouseout() {
            delTimerShow();
            _nTimerHide = setTimeout(hide, _this.nDelayHide);
        }
        function hide() {
            _bNeedShow = false;
            _nTimerHide = null;
            if ("none" == $(_this.oTooltip).css("display")) {
                return;
            }
            $(_this.oTooltip)
                .stop()
                .animate(
                    {top: _nStartY - _nMoveRange * (_this.bMoveUp ? 1 : -1) * 2, opacity: 0},
                    200, "swing",
                    function() {
                        $(this).css({display: "none"});
                        if (_bNeedShow) {
                            mouseover();
                        }
                    }
                );
        }
        function delTimerShow() {
            if (_nTimerShow) {
                clearTimeout(_nTimerShow);
                _nTimerShow = null;
            }
        }
        function delTimerHide() {
            if (_nTimerHide) {
                clearTimeout(_nTimerHide);
                _nTimerHide = null;
            }
        }
    }
    
    $.fn.extend({
        bubble_tooltip_init: function(oOverrideTG, oOverrideConfig) {
            var oConfig = {
                    sFindGroup:   "li",
                    sFindHover:   "a",
                    sFindTooltip: "dfn.tooltip"
                },
                oLastShowed;
            
            
            $.extend(oConfig, oOverrideConfig || {});
            
            // Parents
            this.each(function() {
                // Tooltip groups
                $(oConfig.sFindGroup, this).each(function() {
                    var tg = new TooltipGroup();
                    tg.oHover = $(oConfig.sFindHover, this)[0];
                    tg.oTooltip = $(oConfig.sFindTooltip, this)[0];
                    tg.onShow = function(tg) {
                        if (oLastShowed) {
                            oLastShowed.forceHide();
                        }
                        oLastShowed = tg;
                    }
                    $.extend(tg, oOverrideTG || {});
                    tg.init();
                });
            });
            return this;
        }
    });
})(jQuery);
;(function($) {
 // Внутренняя 
	$.eready('.grid2, .grid3', function() {
	    $('.grid2, .grid3')
			/*.hfeed_init({
			    is_animate: 0, 
				hide_not_active: 0, 
				hide_announce: 1, 
				target: '#'
			})*/
			.fw_init();
	});
	
	$.eready('ul.ui-tabs-nav', 
	    function() {
		    $('ul.ui-tabs-nav').tabs();
		}
	);
	
    $(document).ready(
        function() {
		
	     // Preview Box
	        $('#preview-container').preview_box_init(
				{
                    'preview_page_container_id':  '.obj-page',
                    'preview_cover_class':        'img-border1',
                    'preview_page_current_id':    'current-page',
		            'preview_empty_image':        '/img/n.gif',
		            'preview_preloader_image':    '/img/default/loader.gif',
		            'previewbox_preloader_image': '/img/default/loader2.gif'
		        }
			).bubble_tooltip_init(
                {nDelayShow: 0, nDelayHide: 0, bAppendTtInBody: $.browser.opera, bTtHover: false}
            );
			
			$('#preview-container a.img-border1').iviewer({
				'zoom_speed_in':	0, 
				'zoom_speed_out':	0,
				'hide_on_content_click': true
			});
		
           return false;

        }
    );
    
})(jQuery);
/*
 * jQuery blockUI plugin
 * Version 2.06 (05/12/2008)
 */

;(function($) {
	
if (/1\.(0|1|2)\.(0|1|2)/.test($.fn.jquery) || /^1.1/.test($.fn.jquery)) {
    alert('blockUI requires jQuery v1.2.3 or later!  You are using v' + $.fn.jquery);
    return;
}

// global $ methods for blocking/unblocking the entire page
$.blockUI   = function(opts) { install(window, opts); };
$.unblockUI = function(opts) { remove(window, opts); };

// plugin method for blocking element content
$.fn.block = function(opts) {
    return this.each(function() {
        if ($.css(this,'position') == 'static')
            this.style.position = 'relative';
        if ($.browser.msie) 
            this.style.zoom = 1; // force 'hasLayout'
        install(this, opts);
    });
};

// plugin method for unblocking element content
$.fn.unblock = function(opts) {
    return this.each(function() {
        remove(this, opts);
    });
};

$.blockUI.version = 2.06; // 2nd generation blocking at no extra cost!

// override these in your code to change the default behavior and style
$.blockUI.defaults = {
    // message displayed when blocking (use null for no message)
    message:  '<h1>Please wait...</h1>',
    
    // styles for the message when blocking; if you wish to disable
    // these and use an external stylesheet then do this in your code:
    // $.blockUI.defaults.css = {};
    css: { 
        padding:        0,
        margin:         0,
        width:          '30%', 
        top:            '40%', 
        left:           '35%', 
        textAlign:      'center', 
        color:          '#000', 
        border:         '3px solid #aaa',
        backgroundColor:'#fff',
        cursor:         'wait'
    },
    
    // styles for the overlay
    overlayCSS:  { 
        backgroundColor:'#000', 
        opacity:        '0.6' 
    },
    
    // z-index for the blocking overlay
    baseZ: 1000,
    
    // set these to true to have the message automatically centered
    centerX: true, // <-- only effects element blocking (page block controlled via css above)
    centerY: true,
    
    // allow body element to be stetched in ie6; this makes blocking look better
    // on "short" pages.  disable if you wish to prevent changes to the body height
    allowBodyStretch: true,
    
    // be default blockUI will supress tab navigation from leaving blocking content;
    constrainTabKey: true,
    
    // fadeOut time in millis; set to 0 to disable fadeout on unblock
    fadeOut:  400,
    
    // if true, focus will be placed in the first available input field when
    // page blocking
    focusInput: true,
    
    // suppresses the use of overlay styles on FF/Linux (due to significant performance issues with opacity)
    applyPlatformOpacityRules: true
};

// private data and functions follow...

var ie6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent);
var pageBlock = null;
var pageBlockEls = [];

function install(el, opts) {
    var full = (el == window);
    var msg = opts && opts.message !== undefined ? opts.message : undefined;
    opts = $.extend({}, $.blockUI.defaults, opts || {});
    opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {});
    var css = $.extend({}, $.blockUI.defaults.css, opts.css || {});
    msg = msg === undefined ? opts.message : msg;

    // remove the current block (if there is one)
    if (full && pageBlock) 
        remove(window, {fadeOut:0}); 
    
    // if an existing element is being used as the blocking content then we capture
    // its current place in the DOM (and current display style) so we can restore
    // it when we unblock
    if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) {
        var node = msg.jquery ? msg[0] : msg;
        var data = {};
        $(el).data('blockUI.history', data);
        data.el = node;
        data.parent = node.parentNode;
        data.display = node.style.display;
        data.position = node.style.position;
        data.parent.removeChild(node);
    }
    
    var z = opts.baseZ;
    
    // blockUI uses 3 layers for blocking, for simplicity they are all used on every platform;
    // layer1 is the iframe layer which is used to supress bleed through of underlying content
    // layer2 is the overlay layer which has opacity and a wait cursor
    // layer3 is the message content that is displayed while blocking

    var lyr1 = ($.browser.msie) ? $('<iframe class="blockUI" style="z-index:'+ z++ +';border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="javascript:false;"></iframe>')
                                : $('<div class="blockUI" style="display:none"></div>');
    var lyr2 = $('<div class="blockUI" style="z-index:'+ z++ +';cursor:wait;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>');
    var lyr3 = full ? $('<div class="blockUI blockMsg blockPage" style="z-index:'+z+';position:fixed"></div>')
                    : $('<div class="blockUI blockMsg blockElement" style="z-index:'+z+';display:none;position:absolute"></div>');

    // if we have a message, style it
    if (msg) {
        lyr3.css(css);
	}

    // style the overlay
    if (!opts.applyPlatformOpacityRules || !($.browser.mozilla && /Linux/.test(navigator.platform))) {
        lyr2.css(opts.overlayCSS);
	}
    lyr2.css('position', full ? 'fixed' : 'absolute');
    
    // make iframe layer transparent in IE
    if ($.browser.msie) 
        lyr1.css('opacity','0.0');

    $([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el);
    
    // ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling)
    var expr = $.browser.msie && (!$.boxModel || $('object,embed', full ? null : el).length > 0);
    if (ie6 || expr) {
	
	    // bug: horizontal scrolling in ie
	    if (0 != parseInt(lyr3.css('height'), 10)) {
	        lyr3.css('width', 'auto');
		}
		
        // give body 100% height
        if (full && opts.allowBodyStretch && $.boxModel) {
            $('html,body').css('height','100%');
		}

        // fix ie6 issue when blocked element has a border width
        if ((ie6 || !$.boxModel) && !full) {
            var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth');
            var fixT = t ? '(0 - '+t+')' : 0;
            var fixL = l ? '(0 - '+l+')' : 0;
        }
		
        // simulate fixed position
        $.each([lyr1,lyr2,lyr3], function(i,o) {
            var s = o[0].style;
            s.position = 'absolute';
            if (i < 2) {
/* 
             // bug: don't work in ie
                full ? s.setExpression('height','document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + "px"')
                     : s.setExpression('height','this.parentNode.offsetHeight + "px"');
*/
				full ? s.height = (parseInt(document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop, 10) + parseInt(document.documentElement.clientHeight || document.body.clientHeight, 10)) + "px" : (this.parentNode.offsetHeight) + "px";
                full ? s.setExpression('width','jQuery.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"')
                     : s.setExpression('width','this.parentNode.offsetWidth + "px"');
                if (fixL) s.setExpression('left', fixL);
                if (fixT) s.setExpression('top', fixT);
            } else if (opts.centerY) {
                if (full) {
				    s.setExpression('top','(parseInt(document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop, 10) + parseInt(document.documentElement.clientHeight || document.body.clientHeight, 10) / 2 - parseInt($(this)[0].offsetHeight, 10)/ 2) + "px"');				
				}
                s.marginTop = 0;
            }
        });
    }

    // show the message
    lyr3.append(msg).show();
    if (msg && (msg.jquery || msg.nodeType)) {
        $(msg).show();
	}
    
	
    // bind key and mouse events
    bind(1, el, opts);
        
    if (full) {
        pageBlock = lyr3[0];
        pageBlockEls = $(':input:enabled:visible',pageBlock);
        if (opts.focusInput)
            setTimeout(focus, 20);
    }
    else
        center(lyr3[0], opts.centerX, opts.centerY);
};

// remove the block
function remove(el, opts) {
    var full = el == window;
    var data = $(el).data('blockUI.history');
    opts = $.extend(true, {}, $.blockUI.defaults, opts);
    bind(0, el, opts); // unbind events
    var els = full ? $('body').children().filter('.blockUI') : $('.blockUI', el);
    
    if (full) 
        pageBlock = pageBlockEls = null;

    if (opts.fadeOut) {
        els.fadeOut(opts.fadeOut);
        setTimeout(function() { reset(els,data); }, opts.fadeOut);
    }
    else
        reset(els, data);
};

// move blocking element back into the DOM where it started
function reset(els,data) {
    els.each(function(i,o) {
        // remove via DOM calls so we don't lose event handlers
        if (this.parentNode) 
            this.parentNode.removeChild(this);
    });
    if (data && data.el) {
        data.el.style.display = data.display;
        data.el.style.position = data.position;
        data.parent.appendChild(data.el);
        $(data.el).removeData('blockUI.history');
    }
};

// bind/unbind the handler
function bind(b, el, opts) {
    var full = el == window, $el = $(el);
    
    // don't bother unbinding if there is nothing to unbind
    if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked'))) 
        return;
    if (!full) 
        $el.data('blockUI.isBlocked', b);
        
    // bind anchors and inputs for mouse and key events
    var events = 'mousedown mouseup keydown keypress click';
    b ? $(document).bind(events, opts, handler) : $(document).unbind(events, handler);

// former impl...
//    var $e = $('a,:input');
//    b ? $e.bind(events, opts, handler) : $e.unbind(events, handler);
};

// event handler to suppress keyboard/mouse events when blocking
function handler(e) {
    // allow tab navigation (conditionally)
    if (e.keyCode && e.keyCode == 9) {
        if (pageBlock && e.data.constrainTabKey) {
            var els = pageBlockEls;
            var fwd = !e.shiftKey && e.target == els[els.length-1];
            var back = e.shiftKey && e.target == els[0];
            if (fwd || back) {
                setTimeout(function(){focus(back)},10);
                return false;
            }
        }
    }
    // allow events within the message content
    if ($(e.target).parents('div.blockMsg').length > 0)
        return true;
        
    // allow events for content that is not being blocked
    return $(e.target).parents().children().filter('div.blockUI').length == 0;
};

function focus(back) {
    if (!pageBlockEls) 
        return;
    var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0];
    if (e) 
        e.focus();
};

function center(el, x, y) {
    var p = el.parentNode, s = el.style;
    var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth');
    var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth');
    if (x) s.left = l > 0 ? (l+'px') : '0';
    if (y) s.top  = t > 0 ? (t+'px') : '0';
};

function sz(el, p) { 
    return parseInt($.css(el,p))||0; 
};

})(jQuery);

/**
 * Circle animation
 *
 * @name Circle
 * @description Create an animation of blocks by changing their css-properties
 * @param All parameters are optional
 * @example $('.grid').circle_init({ 'duration': 500 });
 *
 * @cat Plugins/Interface
 * @author Olga Koryakova
 * @version 1.0.0
 */

;(function($) {
		   
    $.oCircle = function(options) {
		$.extend($.oCircle.conf, options || {});
		
		this.oContainer = ($.oCircle.conf['circle_container']) ? $( $.oCircle.conf['circle_container'] ) : {};
		this.oSwitcher  = ($.oCircle.conf['circle_switcher'])  ? $( $.oCircle.conf['circle_switcher'] )  : {};
		
		this.aProperties = [];
		this.sCurrentId  = 1;
		this.sTargetId;
		
		this.init();
	}
	
	// configuration settings
	$.oCircle.conf = {
		'circle_container'   : '.column2',       // container block with 'position: relative'
		'circle_switcher'    : '.grid-switcher', // switcher
		
		'target_id_prefix'   : '#block',
		'target_class_prefix': 'grid-block',     // prefix of classes that will be changing
		'bg_class_prefix'    : 'grid-bg',        // blocks with background
		
		'duration'           : 300,              // duration of block animation
		'duration2'          : 300,              // duration of background animation
		'count'              : 6                 // total number of blocks
	};
	
	// initialization
	$.oCircle.prototype.init = function() {	
		var oSelf = this;
		
		this.oContainer.find('a[@href^=' + $.oCircle.conf['target_id_prefix'] + ']').bind(
		    'click',
			function() {
			    oSelf.setClickHandler($($(this).attr('href')));
				return false;
			}
		);
	}
	
	/**
	 * @name setClickHandler
	 * @description Set a handler for 'click' event
	 * @param oTarget -a block that must become upper
	 * @return none
	 */
	$.oCircle.prototype.setClickHandler = function(oTarget) {
		var oSelf      = this,
			iClassNum  = oSelf.getLastSymbols(oTarget.attr('class'), 1),
			iStep      = iClassNum - 1,
			iDir;
		
		// define current and target block's identifier
		oSelf.sCurrentId = oSelf.oContainer.find('div[@class=' + $.oCircle.conf['target_class_prefix'] + '1]').attr('id');
		oSelf.sTargetId  = oTarget.attr('id');
			
		// choose a direction of movement
		if (iStep > Math.round($.oCircle.conf['count'] / 2)) {
			iStep = ($.oCircle.conf['count'] - iStep);
			iDir = 1;
		} else {
			iDir = -1;
		}
			
		if (iClassNum != 1) { // if link is not active yet
		
		    oSelf.aProperties = oSelf.getStyleProperties();
		
			// set active link in switcher
			oSelf.oSwitcher.find('a[@href=#' + oSelf.sCurrentId + ']').removeClass('active');
			oSelf.oSwitcher.find('a[@href=#' + oSelf.sTargetId + ']').addClass('active');
			
			// unbind links
			oSelf.oContainer.find('a[@href^=' + $.oCircle.conf['target_id_prefix'] + ']').unbind('click');
			
			// move blocks		
			oSelf.oContainer.find('div[@class^=' + $.oCircle.conf['target_class_prefix'] + ']').each(function(i) {
				var oBlock  = $(this),
					iOldNum = oSelf.getLastSymbols(oBlock.attr('class'), 1),
					iNewNum = oSelf.getNumber(iOldNum + iDir);		
					
				oSelf.startMotion(oBlock, iNewNum, iStep - 1, iDir, i);
				
			});
		
		}
	}
	
	/**
	 * @name startMotion
	 * @description Start movement of blocks (make just 1 step)
	 * @param [object] oBlock - a block that should be moved
	 *        [int]    iNum   - a number of result class
	 *        [int]    iCount - remaining number of steps
	 *        [int]    iDir   - direction of motion (1 - clockwise, -1 - anticlockwise)
	 * @return none
	 */
	$.oCircle.prototype.startMotion = function(oBlock, iNum, iCount, iDir, i) {
		var oSelf = this;

        if ((1 == iDir && 1 == iNum) || (-1 == iDir && $.oCircle.conf['count'] == iNum)) {
		// if first and last classes change places
			oBlock.fadeOut(
			    $.oCircle.conf['duration'] / 2,
				function() {
					oBlock.removeClass().addClass($.oCircle.conf['target_class_prefix'] + iNum).css(oSelf.aProperties[iNum]).fadeIn($.oCircle.conf['duration'] / 2);
					oSelf.getNextStep(oBlock, iNum, iCount, iDir, i);
				}
			);
			
		} else {

			oBlock.animate(
				oSelf.aProperties[iNum], 
				$.oCircle.conf['duration'], 
				'linear',
				function() {
					oBlock.removeClass().addClass($.oCircle.conf['target_class_prefix'] + iNum);
					oSelf.getNextStep(oBlock, iNum, iCount, iDir, i);
				}
			);
		
		}
	}
	
	/**
	 * @name getNextStep
	 * @description Define what to do the next step
	 * @param [object] oBlock - a block that should be moved
	 *        [int]    iNum   - a number of result class
	 *        [int]    iCount - remaining number of steps
	 *        [int]    iDir   - direction of motion (1 - clockwise, -1 - anticlockwise)
	 * @return none
	 */
	$.oCircle.prototype.getNextStep = function(oBlock, iNum, iCount, iDir, i) {
		var oSelf = this,
		    iNewNum = oSelf.getNumber(iNum + iDir);
		
		if (iCount) { // continue motion
			oSelf.startMotion(oBlock, iNewNum, iCount - 1, iDir, i);
		} else { // stop motion
		
			// set 'left' and 'width' properties in percents
			oBlock.css({
				'left' : oSelf.getProperty(oBlock.css('left'), 'percent'),
				'width': oSelf.getProperty(oBlock.css('width'), 'percent')
			});
			
			if (i == $.oCircle.conf['count'] - 1) { // if all of blocks are moved already
			
			    // change background
				$('.grid').find('div[@class^=' + $.oCircle.conf['bg_class_prefix'] + oSelf.getLastSymbols(oSelf.sCurrentId, 1) + ']').
					fadeOut($.oCircle.conf['duration2'], function() {							
						$('.' + $.oCircle.conf['bg_class_prefix'] + oSelf.getLastSymbols(oSelf.sTargetId, 1)).css('display', 'block').fadeIn($.oCircle.conf['duration2']);
					});
				
				// bind links
				oSelf.oContainer.find('a[@href^=' + $.oCircle.conf['target_id_prefix'] + ']').bind(
					'click',
					function() {
						oSelf.setClickHandler($($(this).attr('href')));
						return false;
					}
				);
			}
		}
	}
	
	
	/**
	 * @name getStyleProperties
	 * @description Get style properties of blocks and put them into array
	 * @param none
	 * @return An array of objects with css-properties
	 */
	$.oCircle.prototype.getStyleProperties = function() {		
		var oSelf = this,
		    aParams = [];
		
		this.oContainer.find('div[@class^=' + $.oCircle.conf['target_class_prefix'] + ']').each(function() {
			var oBlock = $(this),
				iNum   = oSelf.getLastSymbols(oBlock.attr('class'), 1);
			
			aParams[iNum] = {
				'top'  : oSelf.getProperty(oBlock.css('top')),
				'left' : oSelf.getProperty(oBlock.css('left'), ($.browser.safari) ? 'percent' : ''),
				'width': oSelf.getProperty(oBlock.css('width'), ($.browser.safari) ? 'percent' : '')
			};																							 
		});
		
		return aParams;
	}
	
	/**
	 * @name getLastSymbols
	 * @description Get substring with some last symbols of a given string
	 * @param [string] str    - a given string
	 *        [int]    iCount - number of symbols
	 *        [string] sMode  - optional, possible value: 'string'
	 * @return [mixed] string or number (depend on sMode, default: number)
	 */
	$.oCircle.prototype.getLastSymbols = function(str, iCount, sMode) {
		switch (sMode) {
			case 'string': {
				return str.substr(str.length - iCount, iCount);
			}
			break;
			default: {
				return parseInt(str.substr(str.length - iCount, iCount));
			}
		}
	}
	
	/**
	 * @name getNumber
	 * @description Get number of class in the range from 1 to count of classes
	 * @param [int] iNum - number of class
	 * @return [int] result number
	 */
	$.oCircle.prototype.getNumber = function(iNum) {
		if (iNum < 1) {
			return $.oCircle.conf['count'];
		} else if (iNum > $.oCircle.conf['count']) {
			return 1;
		} else {
			return iNum;
		}
	}
	
	/**
	 * @name getProperty
	 * @description Get css-property in necessary units
	 * @param [string] sProperty - a given property
	 *        [string] sMode  - optional, possible value: 'percent'
	 * @return [string] css-property in percents or in pixels (default in pixels)
	 */
	$.oCircle.prototype.getProperty = function(sProperty, sMode) {
		var sUnit = ('%' == this.getLastSymbols(sProperty, 1, 'string')) ? '%' : 'px';
		
		switch (sMode) { 
			case 'percent': {
				if ('%' == sUnit) {
					return parseInt(sProperty) + '%';
				} else {
					return Math.round(parseInt(sProperty) * 100 / this.oContainer.width()) + '%';
				}
			}
			break;
			default: { // in pixels
				if ('%' == sUnit) {
					return Math.round(parseInt(sProperty) * this.oContainer.width() / 100) + 'px';
				} else {
					return parseInt(sProperty) + 'px';
				}
			}
		}
	}
	
			
		
    $.fn.extend({
		circle_init: function(options) {
			new $.oCircle(options);
		}
	});
	
})(jQuery);
;(function($) {
 // Главная 
	$.eready('.grid', function() {
		
	    $('.grid').circle_init();
		
	});
})(jQuery);
/*
 * jQuery UI Effects 1.6b
 *
 * Copyright (c) 2008 Aaron Eisenberger (aaronchi@gmail.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 * 
 * http://docs.jquery.com/UI/Effects/
 */
;(function($) {

$.effects = $.effects || {}; //Add the 'effects' scope

$.extend($.effects, {
	save: function(el, set) {
		for(var i=0;i<set.length;i++) {
			if(set[i] !== null) $.data(el[0], "ec.storage."+set[i], el[0].style[set[i]]);
		}
	},
	restore: function(el, set) {
		for(var i=0;i<set.length;i++) {
			if(set[i] !== null) el.css(set[i], $.data(el[0], "ec.storage."+set[i]));
		}
	},
	setMode: function(el, mode) {
		if (mode == 'toggle') mode = el.is(':hidden') ? 'show' : 'hide'; // Set for toggle
		return mode;
	},
	getBaseline: function(origin, original) { // Translates a [top,left] array into a baseline value
		// this should be a little more flexible in the future to handle a string & hash
		var y, x;
		switch (origin[0]) {
			case 'top': y = 0; break;
			case 'middle': y = 0.5; break;
			case 'bottom': y = 1; break;
			default: y = origin[0] / original.height;
		};
		switch (origin[1]) {
			case 'left': x = 0; break;
			case 'center': x = 0.5; break;
			case 'right': x = 1; break;
			default: x = origin[1] / original.width;
		};
		return {x: x, y: y};
	},
	createWrapper: function(el) {
		if (el.parent().attr('id') == 'fxWrapper')
			return el;
		var props = {width: el.outerWidth({margin:true}), height: el.outerHeight({margin:true}), 'float': el.css('float')};
		el.wrap('<div id="fxWrapper" style="font-size:100%;background:transparent;border:none;margin:0;padding:0"></div>');
		var wrapper = el.parent();
		if (el.css('position') == 'static'){
			wrapper.css({position: 'relative'});
			el.css({position: 'relative'});
		} else {
			var top = el.css('top'); if(isNaN(parseInt(top))) top = 'auto';
			var left = el.css('left'); if(isNaN(parseInt(left))) left = 'auto';
			wrapper.css({ position: el.css('position'), top: top, left: left, zIndex: el.css('z-index') }).show();
			el.css({position: 'relative', top:0, left:0});
		}
		wrapper.css(props);
		return wrapper;
	},
	removeWrapper: function(el) {
		if (el.parent().attr('id') == 'fxWrapper')
			return el.parent().replaceWith(el);
		return el;
	},
	setTransition: function(el, list, factor, val) {
		val = val || {};
		$.each(list,function(i, x){
			unit = el.cssUnit(x);
			if (unit[0] > 0) val[x] = unit[0] * factor + unit[1];
		});
		return val;
	},
	animateClass: function(value, duration, easing, callback) {

		var cb = (typeof easing == "function" ? easing : (callback ? callback : null));
		var ea = (typeof easing == "object" ? easing : null);

		return this.each(function() {

			var offset = {}; var that = $(this); var oldStyleAttr = that.attr("style") || '';
			if(typeof oldStyleAttr == 'object') oldStyleAttr = oldStyleAttr["cssText"]; /* Stupidly in IE, style is a object.. */
			if(value.toggle) { that.hasClass(value.toggle) ? value.remove = value.toggle : value.add = value.toggle; }

			//Let's get a style offset
			var oldStyle = $.extend({}, (document.defaultView ? document.defaultView.getComputedStyle(this,null) : this.currentStyle));
			if(value.add) that.addClass(value.add); if(value.remove) that.removeClass(value.remove);
			var newStyle = $.extend({}, (document.defaultView ? document.defaultView.getComputedStyle(this,null) : this.currentStyle));
			if(value.add) that.removeClass(value.add); if(value.remove) that.addClass(value.remove);

			// The main function to form the object for animation
			for(var n in newStyle) {
				if( typeof newStyle[n] != "function" && newStyle[n] /* No functions and null properties */
				&& n.indexOf("Moz") == -1 && n.indexOf("length") == -1 /* No mozilla spezific render properties. */
				&& newStyle[n] != oldStyle[n] /* Only values that have changed are used for the animation */
				&& (n.match(/color/i) || (!n.match(/color/i) && !isNaN(parseInt(newStyle[n],10)))) /* Only things that can be parsed to integers or colors */
				&& (oldStyle.position != "static" || (oldStyle.position == "static" && !n.match(/left|top|bottom|right/))) /* No need for positions when dealing with static positions */
				) offset[n] = newStyle[n];
			}

			that.animate(offset, duration, ea, function() { // Animate the newly constructed offset object
				// Change style attribute back to original. For stupid IE, we need to clear the damn object.
				if(typeof $(this).attr("style") == 'object') { $(this).attr("style")["cssText"] = ""; $(this).attr("style")["cssText"] = oldStyleAttr; } else $(this).attr("style", oldStyleAttr);
				if(value.add) $(this).addClass(value.add); if(value.remove) $(this).removeClass(value.remove);
				if(cb) cb.apply(this, arguments);
			});

		});
	}
});

//Extend the methods of jQuery
$.fn.extend({
	//Save old methods
	_show: $.fn.show,
	_hide: $.fn.hide,
	__toggle: $.fn.toggle,
	_addClass: $.fn.addClass,
	_removeClass: $.fn.removeClass,
	_toggleClass: $.fn.toggleClass,
	// New ec methods
	effect: function(fx,o,speed,callback) {
		return $.effects[fx] ? $.effects[fx].call(this, {method: fx, options: o || {}, duration: speed, callback: callback }) : null;
	},
	show: function() {
		if(!arguments[0] || (arguments[0].constructor == Number || /(slow|normal|fast)/.test(arguments[0])))
			return this._show.apply(this, arguments);
		else {
			var o = arguments[1] || {}; o['mode'] = 'show';
			return this.effect.apply(this, [arguments[0], o, arguments[2] || o.duration, arguments[3] || o.callback]);
		}
	},
	hide: function() {
		if(!arguments[0] || (arguments[0].constructor == Number || /(slow|normal|fast)/.test(arguments[0])))
			return this._hide.apply(this, arguments);
		else {
			var o = arguments[1] || {}; o['mode'] = 'hide';
			return this.effect.apply(this, [arguments[0], o, arguments[2] || o.duration, arguments[3] || o.callback]);
		}
	},
	toggle: function(){
		if(!arguments[0] || (arguments[0].constructor == Number || /(slow|normal|fast)/.test(arguments[0])) || (arguments[0].constructor == Function))
			return this.__toggle.apply(this, arguments);
		else {
			var o = arguments[1] || {}; o['mode'] = 'toggle';
			return this.effect.apply(this, [arguments[0], o, arguments[2] || o.duration, arguments[3] || o.callback]);
		}
	},
	addClass: function(classNames,speed,easing,callback) {
		return speed ? $.effects.animateClass.apply(this, [{ add: classNames },speed,easing,callback]) : this._addClass(classNames);
	},
	removeClass: function(classNames,speed,easing,callback) {
		return speed ? $.effects.animateClass.apply(this, [{ remove: classNames },speed,easing,callback]) : this._removeClass(classNames);
	},
	toggleClass: function(classNames,speed,easing,callback) {
		return speed ? $.effects.animateClass.apply(this, [{ toggle: classNames },speed,easing,callback]) : this._toggleClass(classNames);
	},
	morph: function(remove,add,speed,easing,callback) {
		return $.effects.animateClass.apply(this, [{ add: add, remove: remove },speed,easing,callback]);
	},
	switchClass: function() {
		return this.morph.apply(this, arguments);
	},
	// helper functions
	cssUnit: function(key) {
		var style = this.css(key), val = [];
		$.each( ['em','px','%','pt'], function(i, unit){
			if(style.indexOf(unit) > 0)
				val = [parseFloat(style), unit];
		});
		return val;
	}
});

/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

// We override the animation for all of these color styles
jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
				if ( fx.state == 0 ) {
						fx.start = getColor( fx.elem, attr );
						fx.end = getRGB( fx.end );
				}

				fx.elem.style[attr] = "rgb(" + [
						Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
						Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
						Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
				].join(",") + ")";
		}
});

// Color Conversion functions from highlightFade
// By Blair Mitchelmore
// http://jquery.offput.ca/highlightFade/

// Parse strings looking for color tuples [255,255,255]
function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
				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))
				return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
				return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
				return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
				return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Look for rgba(0, 0, 0, 0) == transparent in Safari 3
		if (result = /rgba\(0, 0, 0, 0\)/.exec(color))
				return colors['transparent']

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
}

function getColor(elem, attr) {
		var color;

		do {
				color = jQuery.curCSS(elem, attr);

				// Keep going until we find an element that has color, or we hit the body
				if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
						break;

				attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
};

// Some named colors to work with
// From Interface by Stefan Petre
// http://interface.eyecon.ro/

var colors = {
	aqua:[0,255,255],
	azure:[240,255,255],
	beige:[245,245,220],
	black:[0,0,0],
	blue:[0,0,255],
	brown:[165,42,42],
	cyan:[0,255,255],
	darkblue:[0,0,139],
	darkcyan:[0,139,139],
	darkgrey:[169,169,169],
	darkgreen:[0,100,0],
	darkkhaki:[189,183,107],
	darkmagenta:[139,0,139],
	darkolivegreen:[85,107,47],
	darkorange:[255,140,0],
	darkorchid:[153,50,204],
	darkred:[139,0,0],
	darksalmon:[233,150,122],
	darkviolet:[148,0,211],
	fuchsia:[255,0,255],
	gold:[255,215,0],
	green:[0,128,0],
	indigo:[75,0,130],
	khaki:[240,230,140],
	lightblue:[173,216,230],
	lightcyan:[224,255,255],
	lightgreen:[144,238,144],
	lightgrey:[211,211,211],
	lightpink:[255,182,193],
	lightyellow:[255,255,224],
	lime:[0,255,0],
	magenta:[255,0,255],
	maroon:[128,0,0],
	navy:[0,0,128],
	olive:[128,128,0],
	orange:[255,165,0],
	pink:[255,192,203],
	purple:[128,0,128],
	violet:[128,0,128],
	red:[255,0,0],
	silver:[192,192,192],
	white:[255,255,255],
	yellow:[255,255,0],
	transparent: [255,255,255]
};
	
/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 * 
 * Open source under the BSD License. 
 * 
 * Copyright В© 2008 George McGinley Smith
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

/*
 *
 * TERMS OF USE - EASING EQUATIONS
 * 
 * Open source under the BSD License. 
 * 
 * Copyright В© 2001 Robert Penner
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
 */

})(jQuery);

/*
 * jQuery UI Resizable
 *
 * Copyright (c) 2008 Paul Bakaus
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 * 
 * http://docs.jquery.com/UI/Resizables
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.resizable", $.extend({}, $.ui.mouse, {
	init: function() {

		var self = this, o = this.options;

		var elpos = this.element.css('position');
		
		this.originalElement = this.element;
		
		// simulate .ui-resizable { position: relative; }
		this.element.addClass("ui-resizable").css({ position: /static/.test(elpos) ? 'relative' : elpos });
		
		$.extend(o, {
			_aspectRatio: !!(o.aspectRatio),
			helper: o.helper || o.ghost || o.animate ? o.helper || 'proxy' : null,
			knobHandles: o.knobHandles === true ? 'ui-resizable-knob-handle' : o.knobHandles
		});
		
		//Default Theme
		var aBorder = '1px solid #DEDEDE';
		
		o.defaultTheme = {
			'ui-resizable': { display: 'block' },
			'ui-resizable-handle': { position: 'absolute', background: '#F2F2F2', fontSize: '0.1px' },
			'ui-resizable-n': { cursor: 'n-resize', height: '4px', left: '0px', right: '0px', borderTop: aBorder },
			'ui-resizable-s': { cursor: 's-resize', height: '4px', left: '0px', right: '0px', borderBottom: aBorder },
			'ui-resizable-e': { cursor: 'e-resize', width: '4px', top: '0px', bottom: '0px', borderRight: aBorder },
			'ui-resizable-w': { cursor: 'w-resize', width: '4px', top: '0px', bottom: '0px', borderLeft: aBorder },
			'ui-resizable-se': { cursor: 'se-resize', width: '4px', height: '4px', borderRight: aBorder, borderBottom: aBorder },
			'ui-resizable-sw': { cursor: 'sw-resize', width: '4px', height: '4px', borderBottom: aBorder, borderLeft: aBorder },
			'ui-resizable-ne': { cursor: 'ne-resize', width: '4px', height: '4px', borderRight: aBorder, borderTop: aBorder },
			'ui-resizable-nw': { cursor: 'nw-resize', width: '4px', height: '4px', borderLeft: aBorder, borderTop: aBorder }
		};
		
		o.knobTheme = {
			'ui-resizable-handle': { background: '#F2F2F2', border: '1px solid #808080', height: '8px', width: '8px' },
			'ui-resizable-n': { cursor: 'n-resize', top: '0px', left: '45%' },
			'ui-resizable-s': { cursor: 's-resize', bottom: '0px', left: '45%' },
			'ui-resizable-e': { cursor: 'e-resize', right: '0px', top: '45%' },
			'ui-resizable-w': { cursor: 'w-resize', left: '0px', top: '45%' },
			'ui-resizable-se': { cursor: 'se-resize', right: '0px', bottom: '0px' },
			'ui-resizable-sw': { cursor: 'sw-resize', left: '0px', bottom: '0px' },
			'ui-resizable-nw': { cursor: 'nw-resize', left: '0px', top: '0px' },
			'ui-resizable-ne': { cursor: 'ne-resize', right: '0px', top: '0px' }
		};
		
		o._nodeName = this.element[0].nodeName;
		
		//Wrap the element if it cannot hold child nodes
		if(o._nodeName.match(/canvas|textarea|input|select|button|img/i)) {
			var el = this.element;
			
			//Opera fixing relative position
			if (/relative/.test(el.css('position')) && $.browser.opera)
				el.css({ position: 'relative', top: 'auto', left: 'auto' });
			
			//Create a wrapper element and set the wrapper to the new current internal element
			el.wrap(
				$('<div class="ui-wrapper"	style="overflow: hidden;"></div>').css( {
					position: el.css('position'),
					width: el.outerWidth(),
					height: el.outerHeight(),
					top: el.css('top'),
					left: el.css('left')
				})
			);
			
			var oel = this.element; this.element = this.element.parent();
			
			// store instance on wrapper
			this.element.data('resizable', this); 
			
			//Move margins to the wrapper
			this.element.css({ marginLeft: oel.css("marginLeft"), marginTop: oel.css("marginTop"),
				marginRight: oel.css("marginRight"), marginBottom: oel.css("marginBottom")
			});
			
			oel.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0});
			
			//Prevent Safari textarea resize
			if ($.browser.safari && o.preventDefault) oel.css('resize', 'none');
			
			o.proportionallyResize = oel.css({ position: 'static', zoom: 1, display: 'block' });
			
			// avoid IE jump
			this.element.css({ margin: oel.css('margin') });
			
			// fix handlers offset
			this._proportionallyResize();
		}
		
		if(!o.handles) o.handles = !$('.ui-resizable-handle', this.element).length ? "e,s,se" : { n: '.ui-resizable-n', e: '.ui-resizable-e', s: '.ui-resizable-s', w: '.ui-resizable-w', se: '.ui-resizable-se', sw: '.ui-resizable-sw', ne: '.ui-resizable-ne', nw: '.ui-resizable-nw' };
		if(o.handles.constructor == String) {
			
			o.zIndex = o.zIndex || 1000;
			
			if(o.handles == 'all') o.handles = 'n,e,s,w,se,sw,ne,nw';
			
			var n = o.handles.split(","); o.handles = {};
			
			// insertions are applied when don't have theme loaded
			var insertionsDefault = {
				handle: 'position: absolute; display: none; overflow:hidden;',
				n: 'top: 0pt; width:100%;',
				e: 'right: 0pt; height:100%;',
				s: 'bottom: 0pt; width:100%;',
				w: 'left: 0pt; height:100%;',
				se: 'bottom: 0pt; right: 0px;',
				sw: 'bottom: 0pt; left: 0px;',
				ne: 'top: 0pt; right: 0px;',
				nw: 'top: 0pt; left: 0px;'
			};
			
			for(var i = 0; i < n.length; i++) {
				var handle = $.trim(n[i]), dt = o.defaultTheme, hname = 'ui-resizable-'+handle, loadDefault = !$.ui.css(hname) && !o.knobHandles, userKnobClass = $.ui.css('ui-resizable-knob-handle'), 
							allDefTheme = $.extend(dt[hname], dt['ui-resizable-handle']), allKnobTheme = $.extend(o.knobTheme[hname], !userKnobClass ? o.knobTheme['ui-resizable-handle'] : {});
				
				// increase zIndex of sw, se, ne, nw axis
				var applyZIndex = /sw|se|ne|nw/.test(handle) ? { zIndex: ++o.zIndex } : {};
				
				var defCss = (loadDefault ? insertionsDefault[handle] : ''), 
					axis = $(['<div class="ui-resizable-handle ', hname, '" style="', defCss, insertionsDefault.handle, '"></div>'].join('')).css( applyZIndex );
				o.handles[handle] = '.ui-resizable-'+handle;
				
				this.element.append(
					//Theme detection, if not loaded, load o.defaultTheme
					axis.css( loadDefault ? allDefTheme : {} )
						// Load the knobHandle css, fix width, height, top, left...
						.css( o.knobHandles ? allKnobTheme : {} ).addClass(o.knobHandles ? 'ui-resizable-knob-handle' : '').addClass(o.knobHandles)
				);
			}
			
			if (o.knobHandles) this.element.addClass('ui-resizable-knob').css( !$.ui.css('ui-resizable-knob') ? { /*border: '1px #fff dashed'*/ } : {} );
		}
		
		this._renderAxis = function(target) {
			target = target || this.element;
			
			for(var i in o.handles) {
				if(o.handles[i].constructor == String) 
					o.handles[i] = $(o.handles[i], this.element).show();
				
				if (o.transparent)
					o.handles[i].css({opacity:0});
				
				//Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls)
				if (this.element.is('.ui-wrapper') && 
					o._nodeName.match(/textarea|input|select|button/i)) {
					
					var axis = $(o.handles[i], this.element), padWrapper = 0;
					
					//Checking the correct pad and border
					padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth();
					
					//The padding type i have to apply...
					var padPos = [ 'padding', 
						/ne|nw|n/.test(i) ? 'Top' :
						/se|sw|s/.test(i) ? 'Bottom' : 
						/^e$/.test(i) ? 'Right' : 'Left' ].join(""); 
					
					if (!o.transparent)
						target.css(padPos, padWrapper);
					
					this._proportionallyResize();
				}
				if(!$(o.handles[i]).length) continue;
			}
		};
		
		this._renderAxis(this.element);
		o._handles = $('.ui-resizable-handle', self.element);
		
		if (o.disableSelection)
			o._handles.each(function(i, e) { $.ui.disableSelection(e); });
		
		//Matching axis name
		o._handles.mouseover(function() {
			if (!o.resizing) {
				if (this.className) 
					var axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);
				//Axis, default = se
				self.axis = o.axis = axis && axis[1] ? axis[1] : 'se';
			}
		});
		
		//If we want to auto hide the elements
		if (o.autoHide) {
			o._handles.hide();
			$(self.element).addClass("ui-resizable-autohide").hover(function() {
				$(this).removeClass("ui-resizable-autohide");
				o._handles.show();
			},
			function(){
				if (!o.resizing) {
					$(this).addClass("ui-resizable-autohide");
					o._handles.hide();
				}
			});
		}
		
		this.mouseInit();
	},
	plugins: {},
	ui: function() {
		return {
			originalElement: this.originalElement,
			element: this.element,
			helper: this.helper,
			position: this.position,
			size: this.size,
			options: this.options,
			originalSize: this.originalSize,
			originalPosition: this.originalPosition
		};
	},
	propagate: function(n,e) {
		$.ui.plugin.call(this, n, [e, this.ui()]);
		if (n != "resize") this.element.triggerHandler(["resize", n].join(""), [e, this.ui()], this.options[n]);
	},
	destroy: function() {
		var el = this.element, wrapped = el.children(".ui-resizable").get(0);
		
		this.mouseDestroy();
		
		var _destroy = function(exp) {
			$(exp).removeClass("ui-resizable ui-resizable-disabled")
				.removeData("resizable").unbind(".resizable").find('.ui-resizable-handle').remove();
		};
		
		_destroy(el);
		
		if (el.is('.ui-wrapper') && wrapped) {
			el.parent().append(
				$(wrapped).css({
					position: el.css('position'),
					width: el.outerWidth(),
					height: el.outerHeight(),
					top: el.css('top'),
					left: el.css('left')
				})
			).end().remove();
			
			_destroy(wrapped);
		}
	},
	mouseStart: function(e) {
		if(this.options.disabled) return false;
		
		var handle = false;
		for(var i in this.options.handles) {
			if($(this.options.handles[i])[0] == e.target) handle = true;
		}
		if (!handle) return false;
		
		var o = this.options, iniPos = this.element.position(), el = this.element, 
			num = function(v) { return parseInt(v, 10) || 0; }, ie6 = $.browser.msie && $.browser.version < 7;
		o.resizing = true;
		o.documentScroll = { top: $(document).scrollTop(), left: $(document).scrollLeft() };
		
		// bugfix #1749
		if (el.is('.ui-draggable') || (/absolute/).test(el.css('position'))) {
			
			// sOffset decides if document scrollOffset will be added to the top/left of the resizable element
			var sOffset = $.browser.msie && !o.containment && (/absolute/).test(el.css('position')) && !(/relative/).test(el.parent().css('position'));
			var dscrollt = sOffset ? o.documentScroll.top : 0, dscrolll = sOffset ? o.documentScroll.left : 0;
			
			el.css({ position: 'absolute', top: (iniPos.top + dscrollt), left: (iniPos.left + dscrolll) });
		}
		
		//Opera fixing relative position
		if ($.browser.opera && /relative/.test(el.css('position')))
			el.css({ position: 'relative', top: 'auto', left: 'auto' });
		
		this._renderProxy();
		
		var curleft = num(this.helper.css('left')), curtop = num(this.helper.css('top'));
		
		if (o.containment) {
			curleft += $(o.containment).scrollLeft()||0;
			curtop += $(o.containment).scrollTop()||0;
		}
		
		//Store needed variables
		this.offset = this.helper.offset();
		this.position = { left: curleft, top: curtop };
		this.size = o.helper || ie6 ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
		this.originalSize = o.helper || ie6 ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
		this.originalPosition = { left: curleft, top: curtop };
		this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() };
		this.originalMousePosition = { left: e.pageX, top: e.pageY };
		
		//Aspect Ratio
		o.aspectRatio = (typeof o.aspectRatio == 'number') ? o.aspectRatio : ((this.originalSize.height / this.originalSize.width)||1);
		
		if (o.preserveCursor)
			$('body').css('cursor', this.axis + '-resize');
			
		this.propagate("start", e);
		return true;
	},
	mouseDrag: function(e) {
		
		//Increase performance, avoid regex
		var el = this.helper, o = this.options, props = {},
			self = this, smp = this.originalMousePosition, a = this.axis;
		
		var dx = (e.pageX-smp.left)||0, dy = (e.pageY-smp.top)||0;
		var trigger = this._change[a];
		if (!trigger) return false;
		
		// Calculate the attrs that will be change
		var data = trigger.apply(this, [e, dx, dy]), ie6 = $.browser.msie && $.browser.version < 7, csdif = this.sizeDiff;
		
		if (o._aspectRatio || e.shiftKey)
			data = this._updateRatio(data, e);
		
		data = this._respectSize(data, e);
		
		// plugins callbacks need to be called first
		this.propagate("resize", e);
		
		el.css({
			top: this.position.top + "px", left: this.position.left + "px", 
			width: this.size.width + "px", height: this.size.height + "px"
		});
		
		if (!o.helper && o.proportionallyResize)
			this._proportionallyResize();
		
		this._updateCache(data);
		
		// calling the user callback at the end
		this.element.triggerHandler("resize", [e, this.ui()], this.options["resize"]);
		
		return false;
	},
	mouseStop: function(e) {
		
		this.options.resizing = false;
		var o = this.options, num = function(v) { return parseInt(v, 10) || 0; }, self = this;
		
		if(o.helper) {
			var pr = o.proportionallyResize, ista = pr && (/textarea/i).test(pr.get(0).nodeName), 
						soffseth = ista && $.ui.hasScroll(pr.get(0), 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height,
							soffsetw = ista ? 0 : self.sizeDiff.width;
			
			var s = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) },
				left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null, 
				top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null;
			
			if (!o.animate)
				this.element.css($.extend(s, { top: top, left: left }));
			
			if (o.helper && !o.animate) this._proportionallyResize();
		}
		
		if (o.preserveCursor)
			$('body').css('cursor', 'auto');
		
		this.propagate("stop", e);
		
		if (o.helper) this.helper.remove();
		
		return false;
	},
	_updateCache: function(data) {
		var o = this.options;
		this.offset = this.helper.offset();
		if (data.left) this.position.left = data.left;
		if (data.top) this.position.top = data.top;
		if (data.height) this.size.height = data.height;
		if (data.width) this.size.width = data.width;
	},
	_updateRatio: function(data, e) {
		var o = this.options, cpos = this.position, csize = this.size, a = this.axis;
		
		if (data.height) data.width = (csize.height / o.aspectRatio);
		else if (data.width) data.height = (csize.width * o.aspectRatio);
		
		if (a == 'sw') {
			data.left = cpos.left + (csize.width - data.width);
			data.top = null;
		}
		if (a == 'nw') { 
			data.top = cpos.top + (csize.height - data.height);
			data.left = cpos.left + (csize.width - data.width);
		}
		
		return data;
	},
	_respectSize: function(data, e) {
		
		var el = this.helper, o = this.options, pRatio = o._aspectRatio || e.shiftKey, a = this.axis, 
				ismaxw = data.width && o.maxWidth && o.maxWidth < data.width, ismaxh = data.height && o.maxHeight && o.maxHeight < data.height,
					isminw = data.width && o.minWidth && o.minWidth > data.width, isminh = data.height && o.minHeight && o.minHeight > data.height;
		
		if (isminw) data.width = o.minWidth;
		if (isminh) data.height = o.minHeight;
		if (ismaxw) data.width = o.maxWidth;
		if (ismaxh) data.height = o.maxHeight;
		
		var dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height;
		var cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a);
		
		if (isminw && cw) data.left = dw - o.minWidth;
		if (ismaxw && cw) data.left = dw - o.maxWidth;
		if (isminh && ch)	data.top = dh - o.minHeight;
		if (ismaxh && ch)	data.top = dh - o.maxHeight;
		
		// fixing jump error on top/left - bug #2330
		var isNotwh = !data.width && !data.height;
		if (isNotwh && !data.left && data.top) data.top = null;
		else if (isNotwh && !data.top && data.left) data.left = null;
		
		return data;
	},
	_proportionallyResize: function() {
		var o = this.options;
		if (!o.proportionallyResize) return;
		var prel = o.proportionallyResize, el = this.helper || this.element;
		
		if (!o.borderDif) {
			var b = [prel.css('borderTopWidth'), prel.css('borderRightWidth'), prel.css('borderBottomWidth'), prel.css('borderLeftWidth')],
				p = [prel.css('paddingTop'), prel.css('paddingRight'), prel.css('paddingBottom'), prel.css('paddingLeft')];
			
			o.borderDif = $.map(b, function(v, i) {
				var border = parseInt(v,10)||0, padding = parseInt(p[i],10)||0;
				return border + padding; 
			});
		}
		prel.css({
			height: (el.height() - o.borderDif[0] - o.borderDif[2]) + "px",
			width: (el.width() - o.borderDif[1] - o.borderDif[3]) + "px"
		});
	},
	_renderProxy: function() {
		var el = this.element, o = this.options;
		this.elementOffset = el.offset();
		
		if(o.helper) {
			this.helper = this.helper || $('<div style="overflow:hidden;"></div>');
			
			// fix ie6 offset
			var ie6 = $.browser.msie && $.browser.version < 7, ie6offset = (ie6 ? 1 : 0),
			pxyoffset = ( ie6 ? 2 : -1 );
			
			this.helper.addClass(o.helper).css({
				width: el.outerWidth() + pxyoffset,
				height: el.outerHeight() + pxyoffset,
				position: 'absolute',
				left: this.elementOffset.left - ie6offset +'px',
				top: this.elementOffset.top - ie6offset +'px',
				zIndex: ++o.zIndex
			});
			
			this.helper.appendTo("body");
			
			if (o.disableSelection)
				$.ui.disableSelection(this.helper.get(0));
			
		} else {
			this.helper = el; 
		}
	},
	_change: {
		e: function(e, dx, dy) {
			return { width: this.originalSize.width + dx };
		},
		w: function(e, dx, dy) {
			var o = this.options, cs = this.originalSize, sp = this.originalPosition;
			return { left: sp.left + dx, width: cs.width - dx };
		},
		n: function(e, dx, dy) {
			var o = this.options, cs = this.originalSize, sp = this.originalPosition;
			return { top: sp.top + dy, height: cs.height - dy };
		},
		s: function(e, dx, dy) {
			return { height: this.originalSize.height + dy };
		},
		se: function(e, dx, dy) {
			return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [e, dx, dy]));
		},
		sw: function(e, dx, dy) {
			return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [e, dx, dy]));
		},
		ne: function(e, dx, dy) {
			return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [e, dx, dy]));
		},
		nw: function(e, dx, dy) {
			return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [e, dx, dy]));
		}
	}
}));

$.extend($.ui.resizable, {
	defaults: {
		cancel: ":input",
		distance: 1,
		delay: 0,
		preventDefault: true,
		transparent: false,
		minWidth: 10,
		minHeight: 10,
		aspectRatio: false,
		disableSelection: true,
		preserveCursor: true,
		autoHide: false,
		knobHandles: false
	}
});

/*
 * Resizable Extensions
 */

$.ui.plugin.add("resizable", "containment", {
	
	start: function(e, ui) {
		var o = ui.options, self = $(this).data("resizable"), el = self.element;
		var oc = o.containment,	ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc;
		if (!ce) return;
		
		self.containerElement = $(ce);
		
		if (/document/.test(oc) || oc == document) {
			self.containerOffset = { left: 0, top: 0 };
			self.containerPosition = { left: 0, top: 0 };
			
			self.parentData = { 
				element: $(document), left: 0, top: 0, 
				width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight
			};
		}
		
				
		// i'm a node, so compute top, left, right, bottom
		else{
			self.containerOffset = $(ce).offset();
			self.containerPosition = $(ce).position();
			self.containerSize = { height: $(ce).innerHeight(), width: $(ce).innerWidth() };
		
			var co = self.containerOffset, ch = self.containerSize.height,	cw = self.containerSize.width, 
						width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw ), height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch);
		
			self.parentData = { 
				element: ce, left: co.left, top: co.top, width: width, height: height
			};
		}
	},
	
	resize: function(e, ui) {
		var o = ui.options, self = $(this).data("resizable"), 
				ps = self.containerSize, co = self.containerOffset, cs = self.size, cp = self.position,
				pRatio = o._aspectRatio || e.shiftKey, cop = { top:0, left:0 }, ce = self.containerElement;
		
		if (ce[0] != document && /static/.test(ce.css('position')))
			cop = self.containerPosition;
		
		if (cp.left < (o.helper ? co.left : cop.left)) {
			self.size.width = self.size.width + (o.helper ? (self.position.left - co.left) : (self.position.left - cop.left));
			if (pRatio) self.size.height = self.size.width * o.aspectRatio;
			self.position.left = o.helper ? co.left : cop.left;
		}
		
		if (cp.top < (o.helper ? co.top : 0)) {
			self.size.height = self.size.height + (o.helper ? (self.position.top - co.top) : self.position.top);
			if (pRatio) self.size.width = self.size.height / o.aspectRatio;
			self.position.top = o.helper ? co.top : 0;
		}
		
		var woset = (o.helper ? self.offset.left - co.left : (self.position.left - cop.left)) + self.sizeDiff.width, 
					hoset = (o.helper ? self.offset.top - co.top : self.position.top) + self.sizeDiff.height;
		
		if (woset + self.size.width >= self.parentData.width) {
			self.size.width = self.parentData.width - woset;
			if (pRatio) self.size.height = self.size.width * o.aspectRatio;
		}
		
		if (hoset + self.size.height >= self.parentData.height) {
			self.size.height = self.parentData.height - hoset;
			if (pRatio) self.size.width = self.size.height / o.aspectRatio;
		}
	},
	
	stop: function(e, ui){
		var o = ui.options, self = $(this).data("resizable"), cp = self.position,
				co = self.containerOffset, cop = self.containerPosition, ce = self.containerElement;
		
		var helper = $(self.helper), ho = helper.offset(), w = helper.innerWidth(), h = helper.innerHeight();
		
		
		if (o.helper && !o.animate && /relative/.test(ce.css('position')))
			$(this).css({ left: (ho.left - co.left), top: (ho.top - co.top), width: w, height: h });
		
		if (o.helper && !o.animate && /static/.test(ce.css('position')))
			$(this).css({ left: cop.left + (ho.left - co.left), top: cop.top + (ho.top - co.top), width: w, height: h });
		
	}
});

$.ui.plugin.add("resizable", "grid", {
	
	resize: function(e, ui) {
		var o = ui.options, self = $(this).data("resizable"), cs = self.size, os = self.originalSize, op = self.originalPosition, a = self.axis, ratio = o._aspectRatio || e.shiftKey;
		o.grid = typeof o.grid == "number" ? [o.grid, o.grid] : o.grid;
		var ox = Math.round((cs.width - os.width) / (o.grid[0]||1)) * (o.grid[0]||1), oy = Math.round((cs.height - os.height) / (o.grid[1]||1)) * (o.grid[1]||1);
		
		if (/^(se|s|e)$/.test(a)) {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
		}
		else if (/^(ne)$/.test(a)) {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
			self.position.top = op.top - oy;
		}
		else if (/^(sw)$/.test(a)) {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
			self.position.left = op.left - ox;
		}
		else {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
			self.position.top = op.top - oy;
			self.position.left = op.left - ox;
		}
	}
	
});

$.ui.plugin.add("resizable", "animate", {
	
	stop: function(e, ui) {
		var o = ui.options, self = $(this).data("resizable");
		
		var pr = o.proportionallyResize, ista = pr && (/textarea/i).test(pr.get(0).nodeName), 
						soffseth = ista && $.ui.hasScroll(pr.get(0), 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height,
							soffsetw = ista ? 0 : self.sizeDiff.width;
		
		var style = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) },
					left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null, 
						top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null; 
		
		self.element.animate(
			$.extend(style, top && left ? { top: top, left: left } : {}), { 
				duration: o.animateDuration || "slow", easing: o.animateEasing || "swing", 
				step: function() {
					
					var data = {
						width: parseInt(self.element.css('width'), 10),
						height: parseInt(self.element.css('height'), 10),
						top: parseInt(self.element.css('top'), 10),
						left: parseInt(self.element.css('left'), 10)
					};
					
					if (pr) pr.css({ width: data.width, height: data.height });
					
					// propagating resize, and updating values for each animation step
					self._updateCache(data);
					self.propagate("animate", e);
					
				}
			}
		);
	}
	
});

$.ui.plugin.add("resizable", "ghost", {
	
	start: function(e, ui) {
		var o = ui.options, self = $(this).data("resizable"), pr = o.proportionallyResize, cs = self.size;
		
		if (!pr) self.ghost = self.element.clone();
		else self.ghost = pr.clone();
		
		self.ghost.css(
			{ opacity: .25, display: 'block', position: 'relative', height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 }
		)
		.addClass('ui-resizable-ghost').addClass(typeof o.ghost == 'string' ? o.ghost : '');
		
		self.ghost.appendTo(self.helper);
		
	},
	
	resize: function(e, ui){
		var o = ui.options, self = $(this).data("resizable"), pr = o.proportionallyResize;
		
		if (self.ghost) self.ghost.css({ position: 'relative', height: self.size.height, width: self.size.width });
		
	},
	
	stop: function(e, ui){
		var o = ui.options, self = $(this).data("resizable"), pr = o.proportionallyResize;
		if (self.ghost && self.helper) self.helper.get(0).removeChild(self.ghost.get(0));
	}
	
});

$.ui.plugin.add("resizable", "alsoResize", {
	
	start: function(e, ui) {
		var o = ui.options, self = $(this).data("resizable"), 
		
		_store = function(exp) {
			$(exp).each(function() {
				$(this).data("resizable-alsoresize", {
					width: parseInt($(this).width(), 10), height: parseInt($(this).height(), 10),
					left: parseInt($(this).css('left'), 10), top: parseInt($(this).css('top'), 10)
				});
			});
		};
		
		if (typeof(o.alsoResize) == 'object') {
			if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0];	_store(o.alsoResize); }
			else { $.each(o.alsoResize, function(exp, c) { _store(exp); }); }
		}else{
			_store(o.alsoResize);
		} 
	},
	
	resize: function(e, ui){
		var o = ui.options, self = $(this).data("resizable"), os = self.originalSize, op = self.originalPosition;
		
		var delta = { 
			height: (self.size.height - os.height) || 0, width: (self.size.width - os.width) || 0,
			top: (self.position.top - op.top) || 0, left: (self.position.left - op.left) || 0
		},
		
		_alsoResize = function(exp, c) {
			$(exp).each(function() {
				var start = $(this).data("resizable-alsoresize"), style = {}, css = c && c.length ? c : ['width', 'height', 'top', 'left'];
				
				$.each(css || ['width', 'height', 'top', 'left'], function(i, prop) {
					var sum = (start[prop]||0) + (delta[prop]||0);
					if (sum && sum >= 0)
						style[prop] = sum || null;
				});
				$(this).css(style);
			});
		};
		
		if (typeof(o.alsoResize) == 'object') {
			$.each(o.alsoResize, function(exp, c) { _alsoResize(exp, c); });
		}else{
			_alsoResize(o.alsoResize);
		}
	},
	
	stop: function(e, ui){
		$(this).removeData("resizable-alsoresize-start");
	}
});

})(jQuery);

/*
 * jQuery UI Draggable
 *
 * Copyright (c) 2008 Paul Bakaus
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 * 
 * http://docs.jquery.com/UI/Draggables
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.draggable", $.extend({}, $.ui.mouse, {
	init: function() {
		
		if (this.options.helper == 'original' && !(/^(?:r|a|f)/).test(this.element.css("position")))
			this.element[0].style.position = 'relative';
		
		(this.options.cssNamespace && this.element.addClass(this.options.cssNamespace+"-draggable"));
		(this.options.disabled && this.element.addClass('ui-draggable-disabled'));
		
		this.mouseInit();
		
	},
	mouseStart: function(e) {
		
		var o = this.options;
		
		if (this.helper || o.disabled || $(e.target).is('.ui-resizable-handle'))
			return false;
		
		//Check if we have a valid handle
		var handle = !this.options.handle || !$(this.options.handle, this.element).length ? true : false;
		$(this.options.handle, this.element).find("*").andSelf().each(function() {
			if(this == e.target) handle = true;
		});
		if (!handle) return false;
		
		if($.ui.ddmanager)
			$.ui.ddmanager.current = this;
		
		//Create and append the visible helper
		this.helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [e])) : (o.helper == 'clone' ? this.element.clone() : this.element);
		if(!this.helper.parents('body').length) this.helper.appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo));
		if(this.helper[0] != this.element[0] && !(/(fixed|absolute)/).test(this.helper.css("position"))) this.helper.css("position", "absolute");
		
		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */
		
		this.margins = {																				//Cache the margins
			left: (parseInt(this.element.css("marginLeft"),10) || 0),
			top: (parseInt(this.element.css("marginTop"),10) || 0)
		};		
		
		this.cssPosition = this.helper.css("position");													//Store the helper's css position
		this.offset = this.element.offset();															//The element's absolute position on the page
		this.offset = {																					//Substract the margins from the element's absolute offset
			top: this.offset.top - this.margins.top,
			left: this.offset.left - this.margins.left
		};
		
		this.offset.click = {																			//Where the click happened, relative to the element
			left: e.pageX - this.offset.left,
			top: e.pageY - this.offset.top
		};

		this.scrollTopParent = function(el) {
			do { if(/auto|scroll/.test(el.css('overflow')) || (/auto|scroll/).test(el.css('overflow-y'))) return el; el = el.parent(); } while (el[0].parentNode);
			return $(document);
		}(this.helper);
		this.scrollLeftParent = function(el) {
			do { if(/auto|scroll/.test(el.css('overflow')) || (/auto|scroll/).test(el.css('overflow-x'))) return el; el = el.parent(); } while (el[0].parentNode);
			return $(document);
		}(this.helper);
		
		this.offsetParent = this.helper.offsetParent(); var po = this.offsetParent.offset();			//Get the offsetParent and cache its position
		if(this.offsetParent[0] == document.body && $.browser.mozilla) po = { top: 0, left: 0 };		//Ugly FF3 fix
		this.offset.parent = {																			//Store its position plus border
			top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
			left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
		};
		
		var p = this.element.position();																//This is a relative to absolute position minus the actual position calculation - only used for relative positioned helpers
		this.offset.relative = this.cssPosition == "relative" ? {
			top: p.top - (parseInt(this.helper.css("top"),10) || 0) + (this.scrollTopParent[0].scrollTop || 0),
			left: p.left - (parseInt(this.helper.css("left"),10) || 0) + (this.scrollLeftParent[0].scrollLeft || 0)
		} : { top: 0, left: 0 };
		
		this.originalPosition = this.generatePosition(e);												//Generate the original position
		this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() };//Cache the helper size
		
		if(o.cursorAt) {
			if(o.cursorAt.left != undefined) this.offset.click.left = o.cursorAt.left + this.margins.left;
			if(o.cursorAt.right != undefined) this.offset.click.left = this.helperProportions.width - o.cursorAt.right + this.margins.left;
			if(o.cursorAt.top != undefined) this.offset.click.top = o.cursorAt.top + this.margins.top;
			if(o.cursorAt.bottom != undefined) this.offset.click.top = this.helperProportions.height - o.cursorAt.bottom + this.margins.top;
		}
		
		
		/*
		 * - Position constraining -
		 * Here we prepare position constraining like grid and containment.
		 */	
		
		if(o.containment) {
			if(o.containment == 'parent') o.containment = this.helper[0].parentNode;
			if(o.containment == 'document' || o.containment == 'window') this.containment = [
				0 - this.offset.relative.left - this.offset.parent.left,
				0 - this.offset.relative.top - this.offset.parent.top,
				$(o.containment == 'document' ? document : window).width() - this.offset.relative.left - this.offset.parent.left - this.helperProportions.width - this.margins.left - (parseInt(this.element.css("marginRight"),10) || 0),
				($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.offset.relative.top - this.offset.parent.top - this.helperProportions.height - this.margins.top - (parseInt(this.element.css("marginBottom"),10) || 0)
			];
			
			if(!(/^(document|window|parent)$/).test(o.containment)) {
				var ce = $(o.containment)[0];
				var co = $(o.containment).offset();
				
				this.containment = [
					co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) - this.offset.relative.left - this.offset.parent.left,
					co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) - this.offset.relative.top - this.offset.parent.top,
					co.left+Math.max(ce.scrollWidth,ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - this.offset.relative.left - this.offset.parent.left - this.helperProportions.width - this.margins.left - (parseInt(this.element.css("marginRight"),10) || 0),
					co.top+Math.max(ce.scrollHeight,ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - this.offset.relative.top - this.offset.parent.top - this.helperProportions.height - this.margins.top - (parseInt(this.element.css("marginBottom"),10) || 0)
				];
			}
		}
		
		//Call plugins and callbacks
		this.propagate("start", e);
		
		this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() };//Recache the helper size
		if ($.ui.ddmanager && !o.dropBehaviour) $.ui.ddmanager.prepareOffsets(this, e);
		
		this.helper.addClass("ui-draggable-dragging");
		this.mouseDrag(e); //Execute the drag once - this causes the helper not to be visible before getting its correct position
		return true;
	},
	convertPositionTo: function(d, pos) {

		if(!pos) pos = this.position;
		var mod = d == "absolute" ? 1 : -1;

		return {
			top: (
				pos.top																	// the calculated relative position
				+ this.offset.relative.top	* mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.top * mod											// The offsetParent's offset without borders (offset + border)
				- (this.cssPosition == "fixed" || (this.cssPosition == "absolute" && this.offsetParent[0] == document.body) ? 0 : (this.scrollTopParent[0].scrollTop || 0)) * mod	// The offsetParent's scroll position, not if the element is fixed
				+ (this.cssPosition == "fixed" ? $(document).scrollTop() : 0) * mod
				+ this.margins.top * mod												//Add the margin (you don't want the margin counting in intersection methods)
			),
			left: (
				pos.left																// the calculated relative position
				+ this.offset.relative.left	* mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.left * mod											// The offsetParent's offset without borders (offset + border)
				- (this.cssPosition == "fixed" || (this.cssPosition == "absolute" && this.offsetParent[0] == document.body) ? 0 : (this.scrollLeftParent[0].scrollLeft || 0)) * mod	// The offsetParent's scroll position, not if the element is fixed
				+ (this.cssPosition == "fixed" ? $(document).scrollLeft() : 0) * mod
				+ this.margins.left * mod												//Add the margin (you don't want the margin counting in intersection methods)
			)
		};
	},
	generatePosition: function(e) {

		var o = this.options;
		var position = {
			top: (
				e.pageY																	// The absolute mouse position
				- this.offset.click.top													// Click offset (relative to the element)
				- this.offset.relative.top												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.top												// The offsetParent's offset without borders (offset + border)
				+ (this.cssPosition == "fixed" || (this.cssPosition == "absolute" && this.offsetParent[0] == document.body) ? 0 : (this.scrollTopParent[0].scrollTop || 0))	// The offsetParent's scroll position, not if the element is fixed
				- (this.cssPosition == "fixed" ? $(document).scrollTop() : 0)
			),
			left: (
				e.pageX																	// The absolute mouse position
				- this.offset.click.left												// Click offset (relative to the element)
				- this.offset.relative.left												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.left												// The offsetParent's offset without borders (offset + border)
				+ (this.cssPosition == "fixed" || (this.cssPosition == "absolute" && this.offsetParent[0] == document.body) ? 0 : (this.scrollLeftParent[0].scrollLeft || 0))	// The offsetParent's scroll position, not if the element is fixed
				- (this.cssPosition == "fixed" ? $(document).scrollLeft() : 0)
			)
		};
	
		if(!this.originalPosition) return position;										//If we are not dragging yet, we won't check for options
		
		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */
		if(this.containment) {
			if(position.left < this.containment[0]) position.left = this.containment[0];
			if(position.top < this.containment[1]) position.top = this.containment[1];
			if(position.left > this.containment[2]) position.left = this.containment[2];
			if(position.top > this.containment[3]) position.top = this.containment[3];
		}
		
		if(o.grid) {
			var top = this.originalPosition.top + Math.round((position.top - this.originalPosition.top) / o.grid[1]) * o.grid[1];
			position.top = this.containment ? (!(top < this.containment[1] || top > this.containment[3]) ? top : (!(top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
			
			var left = this.originalPosition.left + Math.round((position.left - this.originalPosition.left) / o.grid[0]) * o.grid[0];
			position.left = this.containment ? (!(left < this.containment[0] || left > this.containment[2]) ? left : (!(left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
		}
		
		return position;
	},
	mouseDrag: function(e) {
	
		//Compute the helpers position
		this.position = this.generatePosition(e);
		this.positionAbs = this.convertPositionTo("absolute");
		
		//Call plugins and callbacks and use the resulting position if something is returned		
		this.position = this.propagate("drag", e) || this.position;
	
		if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px';
		if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px';
		if($.ui.ddmanager) $.ui.ddmanager.drag(this, e);
		
		return false;
	},
	mouseStop: function(e) {
		
		//If we are using droppables, inform the manager about the drop
		var dropped = false;
		if ($.ui.ddmanager && !this.options.dropBehaviour)
			var dropped = $.ui.ddmanager.drop(this, e);		
		
		if((this.options.revert == "invalid" && !dropped) || (this.options.revert == "valid" && dropped) || this.options.revert === true) {
			var self = this;
			$(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10) || 500, function() {
				self.propagate("stop", e);
				self.clear();
			});
		} else {
			this.propagate("stop", e);
			this.clear();
		}
		
		return false;
	},
	clear: function() {
		this.helper.removeClass("ui-draggable-dragging");
		if(this.options.helper != 'original' && !this.cancelHelperRemoval) this.helper.remove();
		//if($.ui.ddmanager) $.ui.ddmanager.current = null;
		this.helper = null;
		this.cancelHelperRemoval = false;
	},
	
	// From now on bulk stuff - mainly helpers
	plugins: {},
	uiHash: function(e) {
		return {
			helper: this.helper,
			position: this.position,
			absolutePosition: this.positionAbs,
			options: this.options			
		};
	},
	propagate: function(n,e) {
		$.ui.plugin.call(this, n, [e, this.uiHash()]);
		if(n == "drag") this.positionAbs = this.convertPositionTo("absolute"); //The absolute position has to be recalculated after plugins
		return this.element.triggerHandler(n == "drag" ? n : "drag"+n, [e, this.uiHash()], this.options[n]);
	},
	destroy: function() {
		if(!this.element.data('draggable')) return;
		this.element.removeData("draggable").unbind(".draggable").removeClass('ui-draggable-dragging ui-draggable-disabled');
		this.mouseDestroy();
	}
}));

$.extend($.ui.draggable, {
	defaults: {
		appendTo: "parent",
		axis: false,
		cancel: ":input",
		delay: 0,
		distance: 1,
		helper: "original",
		scope: "default",
		cssNamespace: "ui"
	}
});

$.ui.plugin.add("draggable", "cursor", {
	start: function(e, ui) {
		var t = $('body');
		if (t.css("cursor")) ui.options._cursor = t.css("cursor");
		t.css("cursor", ui.options.cursor);
	},
	stop: function(e, ui) {
		if (ui.options._cursor) $('body').css("cursor", ui.options._cursor);
	}
});

$.ui.plugin.add("draggable", "zIndex", {
	start: function(e, ui) {
		var t = $(ui.helper);
		if(t.css("zIndex")) ui.options._zIndex = t.css("zIndex");
		t.css('zIndex', ui.options.zIndex);
	},
	stop: function(e, ui) {
		if(ui.options._zIndex) $(ui.helper).css('zIndex', ui.options._zIndex);
	}
});

$.ui.plugin.add("draggable", "opacity", {
	start: function(e, ui) {
		var t = $(ui.helper);
		if(t.css("opacity")) ui.options._opacity = t.css("opacity");
		t.css('opacity', ui.options.opacity);
	},
	stop: function(e, ui) {
		if(ui.options._opacity) $(ui.helper).css('opacity', ui.options._opacity);
	}
});

$.ui.plugin.add("draggable", "iframeFix", {
	start: function(e, ui) {
		$(ui.options.iframeFix === true ? "iframe" : ui.options.iframeFix).each(function() {					
			$('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>')
			.css({
				width: this.offsetWidth+"px", height: this.offsetHeight+"px",
				position: "absolute", opacity: "0.001", zIndex: 1000
			})
			.css($(this).offset())
			.appendTo("body");
		});
	},
	stop: function(e, ui) {
		$("div.DragDropIframeFix").each(function() { this.parentNode.removeChild(this); }); //Remove frame helpers	
	}
});



$.ui.plugin.add("draggable", "scroll", {
	start: function(e, ui) {
		var o = ui.options;
		var i = $(this).data("draggable");
		o.scrollSensitivity	= o.scrollSensitivity || 20;
		o.scrollSpeed		= o.scrollSpeed || 20;
		
		i.overflowY = function(el) {
			do { if(/auto|scroll/.test(el.css('overflow')) || (/auto|scroll/).test(el.css('overflow-y'))) return el; el = el.parent(); } while (el[0].parentNode);
			return $(document);
		}(this);
		i.overflowX = function(el) {
			do { if(/auto|scroll/.test(el.css('overflow')) || (/auto|scroll/).test(el.css('overflow-x'))) return el; el = el.parent(); } while (el[0].parentNode);
			return $(document);
		}(this);
		
		if(i.overflowY[0] != document && i.overflowY[0].tagName != 'HTML') i.overflowYOffset = i.overflowY.offset();
		if(i.overflowX[0] != document && i.overflowX[0].tagName != 'HTML') i.overflowXOffset = i.overflowX.offset();
		
	},
	drag: function(e, ui) {
		
		var o = ui.options, scrolled = false;
		var i = $(this).data("draggable");
		
		if(i.overflowY[0] != document && i.overflowY[0].tagName != 'HTML') {
			if((i.overflowYOffset.top + i.overflowY[0].offsetHeight) - e.pageY < o.scrollSensitivity)
				i.overflowY[0].scrollTop = scrolled = i.overflowY[0].scrollTop + o.scrollSpeed;
			if(e.pageY - i.overflowYOffset.top < o.scrollSensitivity)
				i.overflowY[0].scrollTop = scrolled = i.overflowY[0].scrollTop - o.scrollSpeed;
							
		} else {
			if(e.pageY - $(document).scrollTop() < o.scrollSensitivity)
				scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
			if($(window).height() - (e.pageY - $(document).scrollTop()) < o.scrollSensitivity)
				scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
		}
		
		if(i.overflowX[0] != document && i.overflowX[0].tagName != 'HTML') {
			if((i.overflowXOffset.left + i.overflowX[0].offsetWidth) - e.pageX < o.scrollSensitivity)
				i.overflowX[0].scrollLeft = scrolled = i.overflowX[0].scrollLeft + o.scrollSpeed;
			if(e.pageX - i.overflowXOffset.left < o.scrollSensitivity)
				i.overflowX[0].scrollLeft = scrolled = i.overflowX[0].scrollLeft - o.scrollSpeed;
		} else {
			if(e.pageX - $(document).scrollLeft() < o.scrollSensitivity)
				scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
			if($(window).width() - (e.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
				scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
		}
		
		if(scrolled !== false)
			$.ui.ddmanager.prepareOffsets(i, e);
		
	}
});


$.ui.plugin.add("draggable", "snap", {
	start: function(e, ui) {
		
		var inst = $(this).data("draggable");
		inst.snapElements = [];

		$(ui.options.snap.constructor != String ? ( ui.options.snap.items || ':data(draggable)' ) : ui.options.snap).each(function() {
			var $t = $(this); var $o = $t.offset();
			if(this != inst.element[0]) inst.snapElements.push({
				item: this,
				width: $t.outerWidth(), height: $t.outerHeight(),
				top: $o.top, left: $o.left
			});
		});
		
	},
	drag: function(e, ui) {
	
		var inst = $(this).data("draggable");
		var d = ui.options.snapTolerance || 20;

		var x1 = ui.absolutePosition.left, x2 = x1 + inst.helperProportions.width,
			y1 = ui.absolutePosition.top, y2 = y1 + inst.helperProportions.height;
		
		for (var i = inst.snapElements.length - 1; i >= 0; i--){
			
			var l = inst.snapElements[i].left, r = l + inst.snapElements[i].width, 
				t = inst.snapElements[i].top, b = t + inst.snapElements[i].height;
		
			//Yes, I know, this is insane ;)
			if(!((l-d < x1 && x1 < r+d && t-d < y1 && y1 < b+d) || (l-d < x1 && x1 < r+d && t-d < y2 && y2 < b+d) || (l-d < x2 && x2 < r+d && t-d < y1 && y1 < b+d) || (l-d < x2 && x2 < r+d && t-d < y2 && y2 < b+d))) {
				if(inst.snapElements[i].snapping) (inst.options.snap.release && inst.options.snap.release.call(inst.element, null, $.extend(inst.uiHash(), { snapItem: inst.snapElements[i].item })));
				inst.snapElements[i].snapping = false;
				continue;
			}
		
			if(ui.options.snapMode != 'inner') {
				var ts = Math.abs(t - y2) <= d;
				var bs = Math.abs(b - y1) <= d;
				var ls = Math.abs(l - x2) <= d;
				var rs = Math.abs(r - x1) <= d;
				if(ts) ui.position.top = inst.convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top;
				if(bs) ui.position.top = inst.convertPositionTo("relative", { top: b, left: 0 }).top;
				if(ls) ui.position.left = inst.convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left;
				if(rs) ui.position.left = inst.convertPositionTo("relative", { top: 0, left: r }).left;
			}
			
			var first = (ts || bs || ls || rs);
			
			if(ui.options.snapMode != 'outer') {
				var ts = Math.abs(t - y1) <= d;
				var bs = Math.abs(b - y2) <= d;
				var ls = Math.abs(l - x1) <= d;
				var rs = Math.abs(r - x2) <= d;
				if(ts) ui.position.top = inst.convertPositionTo("relative", { top: t, left: 0 }).top;
				if(bs) ui.position.top = inst.convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top;
				if(ls) ui.position.left = inst.convertPositionTo("relative", { top: 0, left: l }).left;
				if(rs) ui.position.left = inst.convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left;
			}
			
			if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first))
				(inst.options.snap.snap && inst.options.snap.snap.call(inst.element, null, $.extend(inst.uiHash(), { snapItem: inst.snapElements[i].item })));
			inst.snapElements[i].snapping = (ts || bs || ls || rs || first);
			
		};

	}
});

$.ui.plugin.add("draggable", "connectToSortable", {
	start: function(e,ui) {
	
		var inst = $(this).data("draggable");
		inst.sortables = [];
		$(ui.options.connectToSortable).each(function() {
			if($.data(this, 'sortable')) {
				var sortable = $.data(this, 'sortable');
				inst.sortables.push({
					instance: sortable,
					shouldRevert: sortable.options.revert
				});
				sortable.refreshItems();	//Do a one-time refresh at start to refresh the containerCache	
				sortable.propagate("activate", e, inst);
			}
		});

	},
	stop: function(e,ui) {
		
		//If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
		var inst = $(this).data("draggable");
		
		$.each(inst.sortables, function() {
			if(this.instance.isOver) {
				this.instance.isOver = 0;
				inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
				this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)
				if(this.shouldRevert) this.instance.options.revert = true; //revert here
				this.instance.mouseStop(e);
				
				//Also propagate receive event, since the sortable is actually receiving a element
				this.instance.element.triggerHandler("sortreceive", [e, $.extend(this.instance.ui(), { sender: inst.element })], this.instance.options["receive"]);

				this.instance.options.helper = this.instance.options._helper;
			} else {
				this.instance.propagate("deactivate", e, inst);
			}

		});
		
	},
	drag: function(e,ui) {

		var inst = $(this).data("draggable"), self = this;
		
		var checkPos = function(o) {
				
			var l = o.left, r = l + o.width,
				t = o.top, b = t + o.height;

			return (l < (this.positionAbs.left + this.offset.click.left) && (this.positionAbs.left + this.offset.click.left) < r
					&& t < (this.positionAbs.top + this.offset.click.top) && (this.positionAbs.top + this.offset.click.top) < b);				
		};
		
		$.each(inst.sortables, function(i) {

			if(checkPos.call(inst, this.instance.containerCache)) {

				//If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
				if(!this.instance.isOver) {
					this.instance.isOver = 1;

					//Now we fake the start of dragging for the sortable instance,
					//by cloning the list group item, appending it to the sortable and using it as inst.currentItem
					//We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
					this.instance.currentItem = $(self).clone().appendTo(this.instance.element).data("sortable-item", true);
					this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
					this.instance.options.helper = function() { return ui.helper[0]; };
				
					e.target = this.instance.currentItem[0];
					this.instance.mouseCapture(e, true);
					this.instance.mouseStart(e, true, true);

					//Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
					this.instance.offset.click.top = inst.offset.click.top;
					this.instance.offset.click.left = inst.offset.click.left;
					this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
					this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;
					
					inst.propagate("toSortable", e);
				
				}
				
				//Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
				if(this.instance.currentItem) this.instance.mouseDrag(e);
				
			} else {
				
				//If it doesn't intersect with the sortable, and it intersected before,
				//we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
				if(this.instance.isOver) {
					this.instance.isOver = 0;
					this.instance.cancelHelperRemoval = true;
					this.instance.options.revert = false; //No revert here
					this.instance.mouseStop(e, true);
					this.instance.options.helper = this.instance.options._helper;
					
					//Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
					this.instance.currentItem.remove();
					if(this.instance.placeholder) this.instance.placeholder.remove();
					
					inst.propagate("fromSortable", e);
				}
				
			};

		});

	}
});

$.ui.plugin.add("draggable", "stack", {
	start: function(e,ui) {
		var group = $.makeArray($(ui.options.stack.group)).sort(function(a,b) {
			return (parseInt($(a).css("zIndex"),10) || ui.options.stack.min) - (parseInt($(b).css("zIndex"),10) || ui.options.stack.min);
		});
		
		$(group).each(function(i) {
			this.style.zIndex = ui.options.stack.min + i;
		});
		
		this[0].style.zIndex = ui.options.stack.min + group.length;
	}
});

})(jQuery);

/*
 * jQuery UI Effects Transfer
 *
 * Copyright (c) 2008 Aaron Eisenberger (aaronchi@gmail.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 * 
 * http://docs.jquery.com/UI/Effects/Transfer
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.transfer = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this);
		
		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode
		var target = $(o.options.to); // Find Target
		var position = el.offset();
		var transfer = $('<div class="ui-effects-transfer"></div>').appendTo(document.body);
		if(o.options.className) transfer.addClass(o.options.className);
		
		// Set target css
		transfer.addClass(o.options.className);
		transfer.css({
			top: position.top,
			left: position.left,
			height: el.outerHeight() - parseInt(transfer.css('borderTopWidth')) - parseInt(transfer.css('borderBottomWidth')),
			width: el.outerWidth() - parseInt(transfer.css('borderLeftWidth')) - parseInt(transfer.css('borderRightWidth')),
			position: 'absolute'
		});
		
		// Animation
        var display = target.css('display'), visibility = target.css('visibility');
        if ( 'none' == display ) {
            target.show();
            //target.css('visibility', 'hidden');
        }
        
		position = target.offset();
        
        if ( 'none' == display ) {
            target.hide();
            //target.css('visibility', visibility);
        }
        
		animation = {
			top: position.top,
			left: position.left,
			height: target.outerHeight() - parseInt(transfer.css('borderTopWidth')) - parseInt(transfer.css('borderBottomWidth')),
			width: target.outerWidth() - parseInt(transfer.css('borderLeftWidth')) - parseInt(transfer.css('borderRightWidth'))
		};
		
		// Animate
		transfer.animate(animation, o.duration, o.options.easing, function() {
			transfer.remove(); // Remove div
			if(o.callback) o.callback.apply(el[0], arguments); // Callback
			el.dequeue();
		}); 
		
	});
	
};

})(jQuery);

/**
 * Panoramic Window
 *
 * @name PanoramicWin
 * @description Create a panoramic window
 * @param All parameters are optional
 * @example $('.obj-panorama').panoramic_win_init({'duration': 1000});
 *
 * @cat Plugins/Interface
 * @author Olga Koryakova
 * @version 1.0.0
 * @depends ui.core.js, ui.draggable.js
 */
 
;(function($) {
		   
    $.oPanoramicWin = function(options) {
		$.extend($.oPanoramicWin.conf, options || {});
		
		this.oContainer = ($.oPanoramicWin.conf['panoramic_container']) ? $( $.oPanoramicWin.conf['panoramic_container'] ) : {};
		this.oTarget    = ($.oPanoramicWin.conf['panoramic_target'])    ? $( $.oPanoramicWin.conf['panoramic_target'] )    : {};
		this.oPlayer    = ($.oPanoramicWin.conf['panoramic_player'])    ? $( $.oPanoramicWin.conf['panoramic_player'] )    : {};
		this.oCloseBtn  = ($.oPanoramicWin.conf['button_close'])        ? $( $.oPanoramicWin.conf['button_close'] )        : {};
		this.oLeftBtn   = ($.oPanoramicWin.conf['button_left'])         ? $( $.oPanoramicWin.conf['button_left'] )         : {};
		this.oRightBtn  = ($.oPanoramicWin.conf['button_right'])        ? $( $.oPanoramicWin.conf['button_right'] )        : {};
		this.oUpBtn     = ($.oPanoramicWin.conf['button_up'])           ? $( $.oPanoramicWin.conf['button_up'] )           : {};
		this.oDownBtn   = ($.oPanoramicWin.conf['button_down'])         ? $( $.oPanoramicWin.conf['button_down'] )         : {};
		
		this.oContainment      = null; // container that bounds area for dragging
		this.iHorizontalOffset = 0;
		this.iVerticalOffset   = 0;
		
		this.init();
	}
	
	// configuration settings
	$.oPanoramicWin.conf = {
		'panoramic_container' : '#pwin',        // window itself
		'panoramic_target'    : '.pwin-target', // draggable block
		'panoramic_player'    : '.pwin-player', // container for videoplayer
		
		'button_close'  : '.pwin-close',
		'button_left'   : '.pwin-arr-left',
		'button_right'  : '.pwin-arr-right',
		'button_up'     : '.pwin-arr-up',
		'button_down'   : '.pwin-arr-down',
		
		'folder_video'  : 'images/panorama/video/', // folder for video
		'folder_image'  : 'panorama/preview/',      // folder for video preview
		'folder_image2' : 'panorama/img/',          // folder for small images
		
		'offset_x'    : false, // if these two parameters are false, image will be centering
		'offset_y'    : false,
		
		'duration'      : 5000 // speed of animation
	};
	
	// initialization
	$.oPanoramicWin.prototype.init = function() {
		
		var oSelf = this;
	
	    // switch link
		$('a[@href=' + $.oPanoramicWin.conf['panoramic_container'] + ']').bind('click',
			function() {
				oSelf.oContainer.toggle();
				oSelf.setDefaultProperties();
				
				return false;				
			}
		).addClass('fwlink');
		
		// set handlers for buttons
		this.setButtonHandlers();
		
		// start drag the target
		this.oTarget.draggable({
			axis: 'x',
			cancel: 'area',
			distance: 0,
			containment: '#ui-draggable-containment'
		});
		
		// video player	
		this.oTarget.find('li').find('img').bind(
			'mouseover',
			function() {
				$(this).fadeTo('slow', 1);
			}
		).bind(
			'mouseout',
			function() {
				$(this).fadeTo('slow', 0);
			}
		).bind(
		    'click', 
			function() {
				var aParam = $(this).parent().attr('href').split('#'),
				    iNum   = (aParam[1]) ? parseInt(aParam[1]) : 0,
					iMode  = (aParam[2]) ? parseInt(aParam[2]) : 0;
				
			    oSelf.setVideo(aParam[0], iNum, iMode);
				return false;
		    }
		).fadeTo('fast', 0);
	
	}
	
	$.oPanoramicWin.prototype.setVideo = function(sPath, iNum, iMode) {
		var oSelf = this;
		
		switch (iMode) {
			case 1: { // flash
				swfobject.embedSWF( sPath + $.oPanoramicWin.conf['folder_video'] + iNum + '.swf', 'player', '560', '348', '8', {}, {}, { 'wmode': 'opaque', 'bgcolor': '#999999' }, { 'menu': false } );
			}
			break;
			default: { // video
		        swfobject.embedSWF( sPath + 'img/default/videoplayer/player.swf', 'player', '560', '348', '8', {}, { 'fsfile' : $.oPanoramicWin.conf['folder_video'] + iNum + '.flv', 'imageid': $.oPanoramicWin.conf['folder_image'] + iNum + '.jpg' }, { 'wmode': 'opaque', 'bgcolor': '#f7f5ef' }, { 'menu': false } );
			}
		}
		
		
		// unbind buttons
		this.oTarget.draggable('disable');
		this.oCloseBtn.unbind('click');
		this.oLeftBtn.unbind('mousedown');
		this.oRightBtn.unbind('mousedown');
		this.oUpBtn.unbind('mousedown');
		this.oDownBtn.unbind('mousedown');
		
		this.oPlayer.css({
					
		    'display': 'block',
			'left'   : Math.round(oSelf.oContainer.width() / 2 - oSelf.oPlayer.width() / 2),
			'top'    : Math.round(oSelf.oContainer.height() / 2 - oSelf.oPlayer.height() / 2)
			
		}).find('a').bind('click',
		
		    function() {
		        oSelf.oPlayer.hide();
				oSelf.oTarget.draggable('enable');
				oSelf.setButtonHandlers();
			}
			
		);
		
	}
	
	
	$.oPanoramicWin.prototype.setButtonHandlers = function() {
		var oSelf = this;
		
		// close button
		this.oCloseBtn.bind('click',
		    function() {
				oSelf.oContainer.hide();
			}
		);
		
		// right button
		this.oRightBtn.bind('mousedown',
			function() {
				oSelf.setTargetOffset(oSelf.iHorizontalOffset, 'horizontal');
			}
	    ).bind('mouseup',
		    function() {
				oSelf.oTarget.stop();
			}
		).bind('mouseout',
		    function() {
				oSelf.oTarget.stop();
			}
		);
		
		// left button
		this.oLeftBtn.bind('mousedown',
			function() {
				oSelf.setTargetOffset(0, 'horizontal');
			}
		).bind('mouseup',
		    function() {
				oSelf.oTarget.stop();
			}
		).bind('mouseout',
		    function() {
				oSelf.oTarget.stop();
			}
		);
		
		// up button
		this.oUpBtn.bind('mousedown',
			function() {
				oSelf.setTargetOffset(0, 'vertical');
			}
		).bind('mouseup',
		    function() {
				oSelf.oTarget.stop();
			}
		).bind('mouseout',
		    function() {
				oSelf.oTarget.stop();
			}
		);
		
		// down button
		this.oDownBtn.bind('mousedown',
			function() {
				oSelf.setTargetOffset(oSelf.iVerticalOffset, 'vertical');
			}
		).bind('mouseup',
		    function() {
				oSelf.oTarget.stop();
			}
		).bind('mouseuout',
		    function() {
				oSelf.oTarget.stop();
			}
		);
	}
	
	
	$.oPanoramicWin.prototype.setDefaultProperties = function() {
		var oSelf = this;
		
		// place the container at the center of the screen
		oSelf.oContainer.css({ 
		    'left': Math.round(($(window).width() / 2 - oSelf.oContainer.width() / 2)), 
			'top' : Math.round(($(window).height() / 2 - oSelf.oContainer.height() / 2)) 
		});
		
		// set correct width and height for a target
		oSelf.oTarget.width(oSelf.oTarget.find('img').width()).height(oSelf.oTarget.find('img').height()); // for FireFox
		
		// horizontal and vertical offset
		if (0 == oSelf.iHorizontalOffset) {
			oSelf.iHorizontalOffset = oSelf.oTarget.parent().width() - oSelf.oTarget.width();
		}
		if (0 == oSelf.iVerticalOffset) {
			oSelf.iVerticalOffset = oSelf.oTarget.parent().height() - oSelf.oTarget.height();
		}
		
		// set the position of target block (or centering it)	
		oSelf.oTarget.css({
		    'left': (false === $.oPanoramicWin.conf['offset_x']) ? Math.round(oSelf.iHorizontalOffset / 2) : $.oPanoramicWin.conf['offset_x'],
			'top' : (false === $.oPanoramicWin.conf['offset_y']) ? Math.round(oSelf.iVerticalOffset / 2)   : $.oPanoramicWin.conf['offset_y']
		});			
		
		// define a containment block for a target
		if (null == oSelf.oContainment) {
			oSelf.oTarget.before('<div id="ui-draggable-containment"></div>');
			
			oSelf.oContainment = $('#ui-draggable-containment');
			oSelf.oContainment.css({ 
				'height'  : (2 * oSelf.oTarget.height() - oSelf.oTarget.parent().height()), 
				'left'    : oSelf.iHorizontalOffset,
				'position': 'absolute', 
				'top'     : oSelf.iVerticalOffset, 
				'width'   : (2 * oSelf.oTarget.width() - oSelf.oTarget.parent().width()), 
				'z-index' : 0 
			});
			
		}
	}
	
	
	
	$.oPanoramicWin.prototype.setTargetOffset = function(iOffset, mode) {
		
		switch (mode) {
			case 'horizontal': {			
				this.oTarget.animate({
					left: iOffset
					}, $.oPanoramicWin.conf['duration']
				);
			}
			break;
			case 'vertical': {
				this.oTarget.animate({
					top: iOffset
					}, $.oPanoramicWin.conf['duration']
				);			
			}
			break;
			default: {
				
			}
		}
		
	}
	
	
	$.fn.extend({
		panoramic_win_init: function(options) {
			new $.oPanoramicWin(options);
		}
	});
	
})(jQuery);
;(function($) {
    // Научная деятельность
    
	// panorama
	$.eready('.grid-science-header',
		function() {
			$('.grid-science-header').panoramic_win_init({ 'offset_y': -104 });
			$('.pwin-target').bubble_tooltip_init({
                'nOffsetX'  : -5,
                'nOffsetY'  : -5,
				'nDelayHide': 0,
				'bOnLeft'   : false
			});
			
			$('.grid-science-button a').hover(function() {
			    $(this).parent().find('span').addClass('grid-science-button-bg');
		    }, function() {
				$(this).parent().find('span').removeClass('grid-science-button-bg');
			});
		}
	);
})(jQuery);
;(function($) {
 // Внутренняя 
	$.eready('.grid2, .grid3', function() {
	    $('.grid2, .grid3')
			.fw_init();
	});
	
	$.eready('ul.ui-tabs-nav', 
	    function() {
		    $('ul.ui-tabs-nav').tabs();
		}
	);
	
    $(document).ready(
        function() {
		
	     // Preview Box
	        $('#preview-container').preview_box_init(
				{
                    'preview_page_container_id':  '.obj-page',
                    'preview_cover_class':        'img-border1',
                    'preview_page_current_id':    'current-page',
		            'preview_empty_image':        '/img/n.gif',
		            'preview_preloader_image':    '/img/default/loader.gif',
		            'previewbox_preloader_image': '/img/default/loader2.gif'
		        }
			).bubble_tooltip_init(
                {nDelayShow: 0, nDelayHide: 0, bAppendTtInBody: $.browser.opera, bTtHover: false}
            );
			
			$('#preview-container a.img-border1').iviewer({
				'zoom_speed_in':	0, 
				'zoom_speed_out':	0, 
				'hide_on_content_click': false
			});
		
           return false;

        }
    );
    
})(jQuery);
/*
 * jQuery UI Slider
 *
 * Copyright (c) 2008 Paul Bakaus
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 * 
 * http://docs.jquery.com/UI/Slider
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.fn.unwrap = $.fn.unwrap || function(expr) {
  return this.each(function(){
     $(this).parents(expr).eq(0).after(this).remove();
  });
};

$.widget("ui.slider", {
	plugins: {},
	ui: function(e) {
		return {
			options: this.options,
			handle: this.currentHandle,
			value: this.options.axis != "both" || !this.options.axis ? Math.round(this.value(null,this.options.axis == "vertical" ? "y" : "x")) : {
				x: Math.round(this.value(null,"x")),
				y: Math.round(this.value(null,"y"))
			},
			range: this.getRange()
		};
	},
	propagate: function(n,e) {
		$.ui.plugin.call(this, n, [e, this.ui()]);
		this.element.triggerHandler(n == "slide" ? n : "slide"+n, [e, this.ui()], this.options[n]);
	},
	destroy: function() {
		
		this.element
			.removeClass("ui-slider ui-slider-disabled")
			.removeData("slider")
			.unbind(".slider");
		
		if(this.handle && this.handle.length) {
			this.handle
				.unwrap("a");
			this.handle.each(function() {
				$(this).data("mouse").mouseDestroy();
			});
		}
		
		this.generated && this.generated.remove();
		
	},
	setData: function(key, value) {
		$.widget.prototype.setData.apply(this, arguments);
		if (/min|max|steps/.test(key)) {
			this.initBoundaries();
		}
		
		if(key == "range") {
			value ? this.handle.length == 2 && this.createRange() : this.removeRange();
		}
		
	},

	init: function() {
		
		var self = this;
		this.element.addClass("ui-slider");
		this.initBoundaries();
		
		// Initialize mouse and key events for interaction
		this.handle = $(this.options.handle, this.element);
		if (!this.handle.length) {
			self.handle = self.generated = $(self.options.handles || [0]).map(function() {
				var handle = $("<div/>").addClass("ui-slider-handle").appendTo(self.element);
				if (this.id)
					handle.attr("id", this.id);
				return handle[0];
			});
		}
		
		
		var handleclass = function(el) {
			this.element = $(el);
			this.element.data("mouse", this);
			this.options = self.options;
			
			this.element.bind("mousedown", function() {
				if(self.currentHandle) this.blur(self.currentHandle);
				self.focus(this,1);
			});
			
			this.mouseInit();
		};
		
		$.extend(handleclass.prototype, $.ui.mouse, {
			mouseStart: function(e) { return self.start.call(self, e, this.element[0]); },
			mouseStop: function(e) { return self.stop.call(self, e, this.element[0]); },
			mouseDrag: function(e) { return self.drag.call(self, e, this.element[0]); },
			mouseCapture: function() { return true; },
			trigger: function(e) { this.mouseDown(e); }
		});
		
		
		$(this.handle)
			.each(function() {
				new handleclass(this);
			})
			.wrap('<a href="javascript:void(0)" style="outline:none;border:none;"></a>')
			.parent()
				.bind('focus', function(e) { self.focus(this.firstChild); })
				.bind('blur', function(e) { self.blur(this.firstChild); })
				.bind('keydown', function(e) { if(!self.options.noKeyboard) self.keydown(e.keyCode, this.firstChild); })
		;
		
		// Bind the click to the slider itself
		this.element.bind('mousedown.slider', function(e) {
			self.click.apply(self, [e]);
			self.currentHandle.data("mouse").trigger(e);
			self.firstValue = self.firstValue + 1; //This is for always triggering the change event
		});
		
		// Move the first handle to the startValue
		$.each(this.options.handles || [], function(index, handle) {
			self.moveTo(handle.start, index, true);
		});
		if (!isNaN(this.options.startValue))
			this.moveTo(this.options.startValue, 0, true);

		this.previousHandle = $(this.handle[0]); //set the previous handle to the first to allow clicking before selecting the handle
		if(this.handle.length == 2 && this.options.range) this.createRange();
	},
	initBoundaries: function() {
		
		var element = this.element[0], o = this.options;
		this.actualSize = { width: this.element.outerWidth() , height: this.element.outerHeight() };			
		
		$.extend(o, {
			axis: o.axis || (element.offsetWidth < element.offsetHeight ? 'vertical' : 'horizontal'),
			max: !isNaN(parseInt(o.max,10)) ? { x: parseInt(o.max, 10), y: parseInt(o.max, 10) } : ({ x: o.max && o.max.x || 100, y: o.max && o.max.y || 100 }),
			min: !isNaN(parseInt(o.min,10)) ? { x: parseInt(o.min, 10), y: parseInt(o.min, 10) } : ({ x: o.min && o.min.x || 0, y: o.min && o.min.y || 0 })
		});
		//Prepare the real maxValue
		o.realMax = {
			x: o.max.x - o.min.x,
			y: o.max.y - o.min.y
		};
		//Calculate stepping based on steps
		o.stepping = {
			x: o.stepping && o.stepping.x || parseInt(o.stepping, 10) || (o.steps ? o.realMax.x/(o.steps.x || parseInt(o.steps, 10) || o.realMax.x) : 0),
			y: o.stepping && o.stepping.y || parseInt(o.stepping, 10) || (o.steps ? o.realMax.y/(o.steps.y || parseInt(o.steps, 10) || o.realMax.y) : 0)
		};
	},

	
	keydown: function(keyCode, handle) {
		var k = keyCode;
		if(/(33|34|35|36|37|38|39|40)/.test(k)) {
			var o = this.options, xpos, ypos;
			if (/(35|36)/.test(k)) {
				xpos = (k == 35) ? o.max.x : o.min.x;
				ypos = (k == 35) ? o.max.y : o.min.y;
			} else {
				var oper = /(34|37|40)/.test(k) ? "-=" : "+=";
				var step = /(37|38|39|40)/.test(k) ? "oneStep" : "pageStep";
				xpos = oper + this[step]("x");
				ypos = oper + this[step]("y");
			}
			this.moveTo({
				x: xpos,
				y: ypos
			}, handle);
		}
	},
	focus: function(handle,hard) {
		this.currentHandle = $(handle).addClass('ui-slider-handle-active');
		if (hard)
			this.currentHandle.parent()[0].focus();
	},
	blur: function(handle) {
		$(handle).removeClass('ui-slider-handle-active');
		if(this.currentHandle && this.currentHandle[0] == handle) { this.previousHandle = this.currentHandle; this.currentHandle = null; };
	},
	click: function(e) {
		// This method is only used if:
		// - The user didn't click a handle
		// - The Slider is not disabled
		// - There is a current, or previous selected handle (otherwise we wouldn't know which one to move)
		
		var pointer = [e.pageX,e.pageY];
		
		var clickedHandle = false;
		this.handle.each(function() {
			if(this == e.target)
				clickedHandle = true;
		});
		if (clickedHandle || this.options.disabled || !(this.currentHandle || this.previousHandle))
			return;

		// If a previous handle was focussed, focus it again
		if (!this.currentHandle && this.previousHandle)
			this.focus(this.previousHandle, true);
		
		// propagate only for distance > 0, otherwise propagation is done my drag
		this.offset = this.element.offset();

		this.moveTo({
			y: this.convertValue(e.pageY - this.offset.top - this.currentHandle[0].offsetHeight/2, "y"),
			x: this.convertValue(e.pageX - this.offset.left - this.currentHandle[0].offsetWidth/2, "x")
		}, null, !this.options.distance);
	},
	


	createRange: function() {
		if(this.rangeElement) return;
		this.rangeElement = $('<div></div>')
			.addClass('ui-slider-range')
			.css({ position: 'absolute' })
			.appendTo(this.element);
		this.updateRange();
	},
	removeRange: function() {
		this.rangeElement.remove();
		this.rangeElement = null;
	},
	updateRange: function() {
			var prop = this.options.axis == "vertical" ? "top" : "left";
			var size = this.options.axis == "vertical" ? "height" : "width";
			this.rangeElement.css(prop, (parseInt($(this.handle[0]).css(prop),10) || 0) + this.handleSize(0, this.options.axis == "vertical" ? "y" : "x")/2);
			this.rangeElement.css(size, (parseInt($(this.handle[1]).css(prop),10) || 0) - (parseInt($(this.handle[0]).css(prop),10) || 0));
	},
	getRange: function() {
		return this.rangeElement ? this.convertValue(parseInt(this.rangeElement.css(this.options.axis == "vertical" ? "height" : "width"),10), this.options.axis == "vertical" ? "y" : "x") : null;
	},

	handleIndex: function() {
		return this.handle.index(this.currentHandle[0]);
	},
	value: function(handle, axis) {
		if(this.handle.length == 1) this.currentHandle = this.handle;
		if(!axis) axis = this.options.axis == "vertical" ? "y" : "x";

		var curHandle = $(handle != undefined && handle !== null ? this.handle[handle] || handle : this.currentHandle);
		
		if(curHandle.data("mouse").sliderValue) {
			return parseInt(curHandle.data("mouse").sliderValue[axis],10);
		} else {
			return parseInt(((parseInt(curHandle.css(axis == "x" ? "left" : "top"),10) / (this.actualSize[axis == "x" ? "width" : "height"] - this.handleSize(handle,axis))) * this.options.realMax[axis]) + this.options.min[axis],10);
		}

	},
	convertValue: function(value,axis) {
		return this.options.min[axis] + (value / (this.actualSize[axis == "x" ? "width" : "height"] - this.handleSize(null,axis))) * this.options.realMax[axis];
	},
	
	translateValue: function(value,axis) {
		return ((value - this.options.min[axis]) / this.options.realMax[axis]) * (this.actualSize[axis == "x" ? "width" : "height"] - this.handleSize(null,axis));
	},
	translateRange: function(value,axis) {
		if (this.rangeElement) {
			if (this.currentHandle[0] == this.handle[0] && value >= this.translateValue(this.value(1),axis))
				value = this.translateValue(this.value(1,axis) - this.oneStep(axis), axis);
			if (this.currentHandle[0] == this.handle[1] && value <= this.translateValue(this.value(0),axis))
				value = this.translateValue(this.value(0,axis) + this.oneStep(axis), axis);
		}
		if (this.options.handles) {
			var handle = this.options.handles[this.handleIndex()];
			if (value < this.translateValue(handle.min,axis)) {
				value = this.translateValue(handle.min,axis);
			} else if (value > this.translateValue(handle.max,axis)) {
				value = this.translateValue(handle.max,axis);
			}
		}
		return value;
	},
	translateLimits: function(value,axis) {
		if (value >= this.actualSize[axis == "x" ? "width" : "height"] - this.handleSize(null,axis))
			value = this.actualSize[axis == "x" ? "width" : "height"] - this.handleSize(null,axis);
		if (value <= 0)
			value = 0;
		return value;
	},
	handleSize: function(handle,axis) {
		return $(handle != undefined && handle !== null ? this.handle[handle] : this.currentHandle)[0]["offset"+(axis == "x" ? "Width" : "Height")];	
	},
	oneStep: function(axis) {
		return this.options.stepping[axis] || 1;
	},
	pageStep: function(axis) {
		return /* this.options.paging[axis] ||*/ 10;
	},


	start: function(e, handle) {
	
		var o = this.options;
		if(o.disabled) return false;

		// Prepare the outer size
		this.actualSize = { width: this.element.outerWidth() , height: this.element.outerHeight() };
	
		// This is a especially ugly fix for strange blur events happening on mousemove events
		if (!this.currentHandle)
			this.focus(this.previousHandle, true); 

		this.offset = this.element.offset();
		
		this.handleOffset = this.currentHandle.offset();
		this.clickOffset = { top: e.pageY - this.handleOffset.top, left: e.pageX - this.handleOffset.left };
		
		this.firstValue = this.value();
		
		this.propagate('start', e);
		this.drag(e, handle);
		return true;
					
	},
	stop: function(e) {
		this.propagate('stop', e);
		if (this.firstValue != this.value())
			this.propagate('change', e);
		// This is a especially ugly fix for strange blur events happening on mousemove events
		this.focus(this.currentHandle, true);
		return false;
	},
	drag: function(e, handle) {

		var o = this.options;
		var position = { top: e.pageY - this.offset.top - this.clickOffset.top, left: e.pageX - this.offset.left - this.clickOffset.left};
		if(!this.currentHandle) this.focus(this.previousHandle, true); //This is a especially ugly fix for strange blur events happening on mousemove events

		position.left = this.translateLimits(position.left, "x");
		position.top = this.translateLimits(position.top, "y");
		
		if (o.stepping.x) {
			var value = this.convertValue(position.left, "x");
			value = Math.round(value / o.stepping.x) * o.stepping.x;
			position.left = this.translateValue(value, "x");	
		}
		if (o.stepping.y) {
			var value = this.convertValue(position.top, "y");
			value = Math.round(value / o.stepping.y) * o.stepping.y;
			position.top = this.translateValue(value, "y");	
		}
		
		position.left = this.translateRange(position.left, "x");
		position.top = this.translateRange(position.top, "y");

		if(o.axis != "vertical") this.currentHandle.css({ left: position.left });
		if(o.axis != "horizontal") this.currentHandle.css({ top: position.top });
		
		//Store the slider's value
		this.currentHandle.data("mouse").sliderValue = {
			x: Math.round(this.convertValue(position.left, "x")) || 0,
			y: Math.round(this.convertValue(position.top, "y")) || 0
		};
		
		if (this.rangeElement)
			this.updateRange();
		this.propagate('slide', e);
		return false;
	},
	
	moveTo: function(value, handle, noPropagation) {

		var o = this.options;

		// Prepare the outer size
		this.actualSize = { width: this.element.outerWidth() , height: this.element.outerHeight() };

		//If no handle has been passed, no current handle is available and we have multiple handles, return false
		if (handle == undefined && !this.currentHandle && this.handle.length != 1)
			return false; 
		
		//If only one handle is available, use it
		if (handle == undefined && !this.currentHandle)
			handle = 0;
		
		if (handle != undefined)
			this.currentHandle = this.previousHandle = $(this.handle[handle] || handle);


		if(value.x !== undefined && value.y !== undefined) {
			var x = value.x, y = value.y;
		} else {
			var x = value, y = value;
		}

		if(x !== undefined && x.constructor != Number) {
			var me = /^\-\=/.test(x), pe = /^\+\=/.test(x);
			if(me || pe) {
				x = this.value(null, "x") + parseInt(x.replace(me ? '=' : '+=', ''), 10);
			} else {
				x = isNaN(parseInt(x, 10)) ? undefined : parseInt(x, 10);
			}
		}
		
		if(y !== undefined && y.constructor != Number) {
			var me = /^\-\=/.test(y), pe = /^\+\=/.test(y);
			if(me || pe) {
				y = this.value(null, "y") + parseInt(y.replace(me ? '=' : '+=', ''), 10);
			} else {
				y = isNaN(parseInt(y, 10)) ? undefined : parseInt(y, 10);
			}
		}

		if(o.axis != "vertical" && x !== undefined) {
			if(o.stepping.x) x = Math.round(x / o.stepping.x) * o.stepping.x;
			x = this.translateValue(x, "x");
			x = this.translateLimits(x, "x");
			x = this.translateRange(x, "x");

			o.animate ? this.currentHandle.stop().animate({ left: x }, (Math.abs(parseInt(this.currentHandle.css("left")) - x)) * (!isNaN(parseInt(o.animate)) ? o.animate : 5)) : this.currentHandle.css({ left: x });
		}

		if(o.axis != "horizontal" && y !== undefined) {
			if(o.stepping.y) y = Math.round(y / o.stepping.y) * o.stepping.y;
			y = this.translateValue(y, "y");
			y = this.translateLimits(y, "y");
			y = this.translateRange(y, "y");
			o.animate ? this.currentHandle.stop().animate({ top: y }, (Math.abs(parseInt(this.currentHandle.css("top")) - y)) * (!isNaN(parseInt(o.animate)) ? o.animate : 5)) : this.currentHandle.css({ top: y });
		}
		
		if (this.rangeElement)
			this.updateRange();
			
		//Store the slider's value
		this.currentHandle.data("mouse").sliderValue = {
			x: Math.round(this.convertValue(x, "x")) || 0,
			y: Math.round(this.convertValue(y, "y")) || 0
		};
	
		if (!noPropagation) {
			this.propagate('start', null);
			this.propagate('stop', null);
			this.propagate('change', null);
			this.propagate("slide", null);
		}
	}
});

$.ui.slider.getter = "value";

$.ui.slider.defaults = {
	handle: ".ui-slider-handle",
	distance: 1,
	animate: false
};

})(jQuery);

/**
 * Pager
 *
 * @name Pager
 * @description Create a navigation object width options
 * @param All parameters are optional
 * @cat Plugins/Interface
 * @author rz <roman@plotinka.ru>
 * @version 1.0.0
 */
 
;(function($) {

	$.oPager = {
	
		conf: {
		    'button_selector': 'a', 
			'switcher_selector': 'span',
			'button_class_prefix': '', 
			'switcher_class_prefix': ''
		},
		
		iSelected: 1,
		
		aButton: {
		},
		
		aSwitcher: {
		},
		
		init: function(options) { 
		
		    var _oSelf = $(this);
			
            if ( !_oSelf.length ) {
			    return false;
			}
			
			$.extend($.oPager.conf, options || {});
			
			$.extend($.oPager, {
				    aButton:   _oSelf.find( $.oPager.conf['button_selector'] ) || {},
				    aSwitcher: _oSelf.find( $.oPager.conf['switcher_selector'] ) || {}
			    }
			);
			
            if ( !$.oPager.aButton.length ) {
			    return false;
			}
			
			$.oPager.iSelected = parseInt($.oPager.aButton.filter( '[class*=selected]' ).attr('class').match(/selected(\d+)/)[1], 10);
			
		 	$.oPager.aButton.click(
			    function() {
				
				    var iNum = parseInt( $(this).attr('class').match(/\w+(\d+)/)[1], 10);
					$(this).pager_switch_on(iNum);
					
					return false;
					
		 	    }
			);
	
		 	$.oPager.aSwitcher.click(
			    function() {

				    $(this).pager_switch_on();
					
					return false;
					
		 	    }
			);

	    },
		
		button_switch_on: function(iNum) {
		
		    if ( null == iNum ) {
			    return false;
			}
			
			var _oSelected = $.oPager.aButton.filter( '[class=' + $.oPager.conf['button_class_prefix'] + iNum + ']' ), 
			    _oCurrent  = $.oPager.aButton.filter( '[class*=selected]' );
				
		    if ( !_oSelected.length || !_oCurrent.length ) {
			    return false;
			}

			_oCurrent.attr( 'class', _oCurrent.attr('class').replace(/\s*selected\d+/, '') );
			_oSelected.addClass('selected' + iNum);
			
			return _oSelected;
			
		},

		switcher_switch_on: function(iNum) {
		
		    if ( null == iNum ) {
			    return false;
			}

			var _iFirstNum      = 1, 
			    _iLastNum       = parseInt($.oPager.aButton.length, 10), 
			    _oFirstSwitcher = $($.oPager.aSwitcher[0]),
				_oLastSwitcher  = $($.oPager.aSwitcher[$.oPager.aSwitcher.length - 1]);
				
		    if ( !_oFirstSwitcher.length ) {
			    return false;
			}

			_oFirstSwitcher[ iNum ==  _iFirstNum ? 'addClass' : 'removeClass' ]('disabled' + _iFirstNum);
			
		    if ( !_oLastSwitcher.length ) {
			    return false;
			}

			_oLastSwitcher[ iNum ==  _iLastNum ? 'addClass' : 'removeClass' ]('disabled' + $.oPager.aSwitcher.length);
			
			return iNum;
			
		},
		
		page_switch_on: function(iNum) {
		
		    if ( null == iNum ) {
			    return false;
			}
			
			return iNum;
			
		},
		
		switch_on: function(iNum) {
		
			if ( iNum && iNum == $.oPager.iSelected ) {
				return false;
			}
			
			if ( !iNum ) {

			    var iSNum = parseInt( $(this).attr('class').match(/\w+(\d+)/ )[1], 10), 
				    iNum  = ( iSNum == $.oPager.aSwitcher.length ) ? $.oPager.iSelected + 1 : $.oPager.iSelected - 1, 
					_oSelected = $.oPager.aButton.filter( '[class=' + $.oPager.conf['button_class_prefix'] + iNum + ']' );
				
			    if ( !_oSelected.length ) {
				    iNum = (1 == iSNum) ? $.oPager.aButton.length : 1;
				}
				
				$.oPager.aButton.filter( '[class=' + $.oPager.conf['button_class_prefix'] + iNum + ']' ).click();
				
			} else {
			
			    $.oPager.button_switch_on(iNum); 
				
			}
			
			$.oPager.iSelected = iNum;
			$.oPager.switcher_switch_on(iNum);
		 // $.oPager.page_switch_on(iNum);
			
			return iNum;		
		}

	}
	
	$.fn.extend(
	    {
		    pager_init:      $.oPager.init, 
			pager_switch_on: $.oPager.switch_on
		}
	);
	
})(jQuery);
/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 2/19/2008
 * @author Ariel Flesler
 * @version 1.3.3
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function($){var o=$.scrollTo=function(a,b,c){o.window().scrollTo(a,b,c)};o.defaults={axis:'y',duration:1};o.window=function(){return $($.browser.safari?'body':'html')};$.fn.scrollTo=function(l,m,n){if(typeof m=='object'){n=m;m=0}n=$.extend({},o.defaults,n);m=m||n.speed||n.duration;n.queue=n.queue&&n.axis.length>1;if(n.queue)m/=2;n.offset=j(n.offset);n.over=j(n.over);return this.each(function(){var a=this,b=$(a),t=l,c,d={},w=b.is('html,body');switch(typeof t){case'number':case'string':if(/^([+-]=)?\d+(px)?$/.test(t)){t=j(t);break}t=$(t,this);case'object':if(t.is||t.style)c=(t=$(t)).offset()}$.each(n.axis.split(''),function(i,f){var P=f=='x'?'Left':'Top',p=P.toLowerCase(),k='scroll'+P,e=a[k],D=f=='x'?'Width':'Height';if(c){d[k]=c[p]+(w?0:e-b.offset()[p]);if(n.margin){d[k]-=parseInt(t.css('margin'+P))||0;d[k]-=parseInt(t.css('border'+P+'Width'))||0}d[k]+=n.offset[p]||0;if(n.over[p])d[k]+=t[D.toLowerCase()]()*n.over[p]}else d[k]=t[p];if(/^\d+$/.test(d[k]))d[k]=d[k]<=0?0:Math.min(d[k],h(D));if(!i&&n.queue){if(e!=d[k])g(n.onAfterFirst);delete d[k]}});g(n.onAfter);function g(a){b.animate(d,m,n.easing,a&&function(){a.call(this,l)})};function h(D){var b=w?$.browser.opera?document.body:document.documentElement:a;return b['scroll'+D]-b['client'+D]}})};function j(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);
/**
 * jQuery.LocalScroll - Animated scrolling navigation, using anchors.
 * Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 6/3/2008
 * @author Ariel Flesler
 * @version 1.2.6
 **/
;(function($){var g=location.href.replace(/#.*/,''),h=$.localScroll=function(a){$('body').localScroll(a)};h.defaults={duration:1e3,axis:'y',event:'click',stop:1};h.hash=function(a){a=$.extend({},h.defaults,a);a.hash=0;if(location.hash)setTimeout(function(){i(0,location,a)},0)};$.fn.localScroll=function(b){b=$.extend({},h.defaults,b);return(b.persistent||b.lazy)?this.bind(b.event,function(e){var a=$([e.target,e.target.parentNode]).filter(c)[0];a&&i(e,a,b)}):this.find('a,area').filter(c).bind(b.event,function(e){i(e,this,b)}).end().end();function c(){var a=this;return!!a.href&&!!a.hash&&a.href.replace(a.hash,'')==g&&(!b.filter||$(a).is(b.filter))}};function i(e,a,b){var c=a.hash.slice(1),d=document.getElementById(c)||document.getElementsByName(c)[0],f;if(d){e&&e.preventDefault();f=$(b.target||$.scrollTo.window());if(b.lock&&f.is(':animated')||b.onBefore&&b.onBefore.call(a,e,d,f)===!1)return;if(b.stop)f.queue('fx',[]).stop();f.scrollTo(d,b).trigger('notify.serialScroll',[d]);if(b.hash)f.queue(function(){location=a.hash;$(this).dequeue()})}}})(jQuery);
/**
 * Slider Scroll
 *
 * @name SliderScroll
 * @description Create a navigation object with a slider and a smooth scrolling effect
 * @param All parameters are optional
 * @example $('.mod-history').slider_scroll_init({'scroll_duration': 500, 'total_pages': 5});
 *
 * @cat Plugins/Interface
 * @author Olga Koryakova
 * @version 1.0.0
 * @depends ui.core.js, ui.slider.js, jq.pager.js, jq.scrollTo.js, jq.localscroll.js
 *
 * @todo To check for other values of 'total_pages' parameter if plugin works correctly during 'onresize' event (sections width bug)
 */

;(function($) {
		   
    $.oSliderScroll = function(options) {
		$.extend($.oSliderScroll.conf, options || {});
		
		this.oScrollTarget = ($.oSliderScroll.conf['scroll_target'])    ? $( $.oSliderScroll.conf['scroll_target'] )    : {};
		this.oSlider       = ($.oSliderScroll.conf['slider_container']) ? $( $.oSliderScroll.conf['slider_container'] ) : {};
		this.oSliderHandle = ($.oSliderScroll.conf['slider_handle'])    ? $( $.oSliderScroll.conf['slider_handle'] )    : {};
		this.oPager        = ($.oSliderScroll.conf['pager_container'])  ? $( $.oSliderScroll.conf['pager_container'] )  : {};
		
		this.oContainer    = ($.oSliderScroll.conf['scroll_section_id_prefix']) ? $( '.' + $.oSliderScroll.conf['scroll_section_id_prefix'] ) : {};
		
		this.iCurrentPage  = 0; // zero-based
		this.iPageWidth    = this.oScrollTarget.width();
		this.oLastLink     = $([]);
		
		this.init();
	}
	
    // configuration settings
	$.oSliderScroll.conf = {
		'pager_container'             : '.pager',   // container for buttons
		'pager_button_selector'       : 'a',        // css selector for buttons
		'pager_button_class_prefix'   : 'pp',
		'pager_switcher_selector'     : 'span',     // css selector for back-forward buttons (arrows)
		'pager_switcher_class_prefix' : 'ar',
		
		'scroll_duration'             : 500,        // speed of animation
		'scroll_section_id_prefix'    : 'section',  // wide container for all pages
		'scroll_target'               : '#content', // this container define a visible part of content (with css property 'overflow')
				
		'slider_container'            : '#slider',  // container for slider
		'slider_handle'               : '.ui-slider-handle', // scroll box
		
		'total_pages'                 : 5
	};
	
	// initialization
	$.oSliderScroll.prototype.init = function() {	
		this.setScrollHandler();
		this.setSliderHandler();
	}
	
	
	$.oSliderScroll.prototype.setScrollHandler = function() {
		
		var oSelf = this;
		
		this.oScrollTarget.attr({scrollTop: 0, scrollLeft: 0});
		
		this.oPager.find($.oSliderScroll.conf['pager_switcher_selector']).css('display', 'block');
		
		this.oPager.pager_init({								
		   'button_class_prefix'  : $.oSliderScroll.conf['pager_button_class_prefix'], 
		   'switcher_class_prefix': $.oSliderScroll.conf['pager_switcher_class_prefix']		   
		});
		
		this.oPager.localScroll({			
			target: oSelf.oScrollTarget,
			axis: 'x',
			duration: $.oSliderScroll.conf['scroll_duration'],
			onBefore: function( e, anchor, $target ) { 
				
				var oLink = $(this),
				    sHref = oLink.attr('href');
					
				oSelf.iCurrentPage = sHref.substr(sHref.length - 1, 1) - 1;				
				oSelf.setSliderHandlePosition(oSelf.iCurrentPage, 1);
				
				oSelf.setPagesWidth(oLink);
				
			},
			onAfter: function( anchor ) {			
				oSelf.oLastLink.removeClass('scrolling');
			}			
		});
		
	}
	
	$.oSliderScroll.prototype.setSliderHandler = function() {
		
		var oSelf = this;
		
		this.oSlider.css('display', 'block').slider({
			animate: 1, // an integer, because animation is too slowly if this parameter is set to true
			min: 1,
			max: $.oSliderScroll.conf['total_pages'],
			start: function(e, ui) {
				oSelf.oSliderHandle.stop();
			},
			change: function(e, ui) {
				
				var iNum  = Math.round(ui.value), 
				    oCurrentLink = $($.oSliderScroll.conf['pager_button_selector'] + '[@class=' + $.oSliderScroll.conf['pager_button_class_prefix'] + iNum + ']'), 
					oCurrentPage = $('div[@id=' + $.oSliderScroll.conf['scroll_section_id_prefix'] + iNum + ']');
				
				oSelf.oPager.pager_switch_on(iNum);
				
				oSelf.setPagesWidth(oCurrentLink);			
			
			    oSelf.oScrollTarget.scrollTo(oCurrentPage, {
					axis: 'x', 
					duration: $.oSliderScroll.conf['scroll_duration'],
					onAfter: function( anchor ){
						oSelf.oLastLink.removeClass('scrolling');
					}
				});
				
			},
			stop: function(e, ui) {
				oSelf.iCurrentPage = Math.round(ui.value) - 1;
			    oSelf.setSliderHandlePosition(oSelf.iCurrentPage, 1);
			}
		}).bind(
			'resize',
			function() {				
			    oSelf.setSliderHandlePosition(oSelf.iCurrentPage);
				if (oSelf.oLastLink[0] != undefined) {
					oSelf.oScrollTarget.attr({ scrollLeft: parseInt(oSelf.getProperty($(oSelf.oLastLink.attr('href')).css('left'))) });
				}
			}
		);
		
	}
	
	
	/**
	 * @description Set a slider handle into a given position
	 * @param [required] iNum - number of a position
	 *        [optional] mode - 1 - using animation, 0 - without animation
	 */
	$.oSliderScroll.prototype.setSliderHandlePosition = function(iNum, mode) {
		var iLeftOffset = this.oSlider.width() * iNum / ($.oSliderScroll.conf['total_pages'] - 1);
		
		switch (mode) {
			case 1: {
				this.oSliderHandle.animate({
					left: iLeftOffset
				}, $.oSliderScroll.conf['scroll_duration']);
			}
			break;
			default: {
				this.oSliderHandle.css('left', iLeftOffset);
			}
		}
	}
	
	/**
	 * @description Fix a width bug that appears when the window has been resized
	 * @param [required] oTargetLink - link that was clicked
	 */
	$.oSliderScroll.prototype.setPagesWidth = function(oTargetLink) {
		
		var oCurrentPage = $(oTargetLink.attr('href'));
		
		this.oContainer.css('height', oCurrentPage.height());
		
		this.oLastLink.removeClass('scrolling');
		this.oLastLink = oTargetLink.addClass('scrolling');
		
		if ( oTargetLink.blur ) {
			oTargetLink.blur(); // remove the awful outline
		}
		
	}
	
	/**
	 * @name getProperty
	 * @description Get css-property in necessary units
	 * @param [string] sProperty - a given property
	 *        [string] sMode  - optional, possible value: 'percent'
	 * @return [string] css-property in percents or in pixels (default in pixels)
	 */
	$.oSliderScroll.prototype.getProperty = function(sProperty, sMode) {
		var sUnit = ('%' == sProperty.substr(sProperty.length - 1, 1)) ? '%' : 'px';
		
		switch (sMode) { 
			case 'percent': {
				if ('%' == sUnit) {
					return parseInt(sProperty) + '%';
				} else {
					return Math.round(parseInt(sProperty) * 100 / this.oContainer.width()) + '%';
				}
			}
			break;
			default: { // in pixels
				if ('%' == sUnit) {
					return Math.round(parseInt(sProperty) * this.oContainer.width() / 100) + 'px';
				} else {
					return parseInt(sProperty) + 'px';
				}
			}
		}
	}
	
	$.fn.extend({
        slider_scroll_init: function(options) {
            new $.oSliderScroll(options);
        }
    });
	
})(jQuery);
;(function($) {
    // История
    
	$.eready('ul.ui-tabs-nav', 
	    function() {
		    $('ul.ui-tabs-nav').tabs();
		}
	);
    
	// Slider Scroll
	$.eready('.mod-history',
		function() {
			$('.mod-history').slider_scroll_init();
		}
	);
})(jQuery);

var dateSlider = {
    WIDTH: 12,
    EM: 16,
    init: function () {
        var b = this;
        this.slider = $("#date_slider");
        this.sliderLine = $(".date_controller");
        this.line = $(".line");
        this.disabled = false;
        this.container = $("#date_navigation:not(.pic_slider_full, .pic_slider)");
        this.dateList = $("#date_list_ul");
        this.measurerWidth = $("#inner_measurer").width();
        this.containerWidth = this.container.width();
        this.containerOffset = this.container.offset().left;
        this.sliderOffset = parseInt(this.slider.css("left"));
        this.sliderMouseOffset = 0;
        this.dateListWidth = this.calculateWidth();
        this.rate = (this.dateListWidth - this.containerWidth) / this.containerWidth;
        this.selectedItem = this.dateList.find("li.active");
        var c = this.dateListWidth - this.containerWidth;
        var a = this.selectedItem.offset().left - this.containerOffset;
        a += -(this.containerWidth / 2) + (this.selectedItem.width() / 2) + 10;
        if (a > c) {
            this.dateList.css({
                left: -(this.dateListWidth - this.containerWidth)
            });
            this.slider.css({
                left: this.containerWidth - this.WIDTH
            });
        } else {
            if (a > 0) {
                this.dateList.css({
                    left: -(a)
                });
            }
            if (a / this.rate < 0) {
                this.slider.css({
                    left: 0
                });
            } else {
                if (a / this.rate > this.dateListWidth) {
                    this.slider.css({
                        left: this.dateListWidth - this.WIDTH
                    });
                } else {
                    this.slider.css({
                        left: a / this.rate
                    });
                }
            }
        }
        if (this.dateListWidth < this.containerWidth) {
            this.slider.addClass("disabled");
            this.slider.css({
                left: 0
            });
            this.dateList.css({
                left: 0
            });
            this.line.addClass("disabled_line");
            this.disabled = true;
        }
        this.clicked = false;
        this.attachEvents();
        /* common.Measurer.setFunc(function () {
            b.recalculateParams();
        }); */
    },
    calculateWidth: function () {
        var c = this;
        var d = $("li:last", this.container);
        var b = 0;
        var a = $("li", this.container);
        a.each(function () {
            b += $(this).width() + 13;
            if ($(this).hasClass("year")) {
                b += 1;
            }
        });
        return (b);
    },
    recalculateParams: function () {
        this.EM = $("#measurer").height();
        var a = this.containerWidth;
        this.dateListWidth = this.calculateWidth();
        this.containerWidth = this.container.width();
        this.containerOffset = this.container.offset().left;
        if (this.dateListWidth > this.containerWidth) {
            if (this.disabled) {
                this.slider.removeClass("disabled");
                this.line.removeClass("disabled_line");
                this.disabled = false;
            }
            this.rate = (this.dateListWidth - this.containerWidth) / this.containerWidth;
            this.sliderOffset = parseInt(this.slider.css("left"));
            var c = this.sliderOffset * (this.containerWidth / a);
            if (c > this.containerWidth - this.WIDTH) {
                c = this.containerWidth - this.WIDTH;
            }
            this.sliderOffset = c;
            var b = this.sliderOffset / this.containerWidth;
            this.slider.css({
                left: c
            });
            this.dateList.css({
                left: -((this.sliderOffset + this.WIDTH * b) * this.rate)
            });
        } else {
            this.slider.addClass("disabled");
            this.line.addClass("disabled_line");
            this.disabled = true;
        }
    },
    attachEvents: function () {
        var a = this;
        this.slider.mousedown(function (b) {
            b.preventDefault();
            b.stopPropagation();
            a.sliderMouseOffset = b.pageX - a.containerOffset - parseInt(a.slider.css("left"));
            a.clicked = true;
        });
        $(document).mousemove(function (d) {
            if (a.clicked && !a.disabled) {
                d.preventDefault();
                a.sliderOffset = parseInt(a.slider.css("left"));
                var b = a.sliderOffset / a.containerWidth;
                var f = parseInt(d.pageX - a.containerOffset - a.sliderMouseOffset);
                if (f > 0 && f < (a.containerWidth - a.WIDTH)) {
                    a.sliderOffset = f;
                    a.slider.css({
                        left: f
                    });
                    var c = -((f + (a.WIDTH * b)) * a.rate);
                    a.dateList.css({
                        left: c
                    });
                }
            }
        });
        $(document).mouseup(function () {
            a.clicked = false;
        });
        this.sliderLine.mousedown(function (d) {
            if (!a.disabled) {
                a.sliderMouseOffset = a.WIDTH / 2;
                var b = a.sliderOffset / a.containerWidth;
                var f = parseInt(d.pageX - a.containerOffset - 6);
                if (f > 0 && f < (a.containerWidth - a.WIDTH)) {
                    a.sliderOffset = f;
                    a.slider.css({
                        left: f
                    });
                    var c = -((f + (a.WIDTH * b)) * a.rate);
                    a.dateList.css({
                        left: c
                    });
                }
            }
        });
    }
}
