function centerToScreen(id){
	o = document.getElementById(id);
	var top = document.body.scrollTop + (document.body.clientHeight/2 - o.offsetHeight/2);
	o.style.top = top > document.body.scrollTop ? top : document.body.scrollTop;
	o.style.left = document.body.scrollLeft + document.body.clientWidth/2 - o.offsetWidth/2;
}

function resizeToHoldContent(container, o){
	plusx = o.outerWidth()>=o.width() ? o.outerWidth()-o.width() : o.outerWidth(); 
	plusy = o.outerHeight()>=o.height() ? o.outerHeight()-o.height() : o.outerHeight();
	//alert("o.outerWidth()="+o.outerWidth()+" o.width()="+o.width()+" plusx="+plusx);
    container.width(o.width()+plusx).height(o.height()+plusy);
}


function fixPNG(o){
	//if (o.currentStyle.backgroundImage=="none") continue;
	backgroundImage = o.src ? o.src : o.currentStyle.backgroundImage.split('"')[1];
	if (!backgroundImage) return;
	o.style.background = "none";
	o.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+backgroundImage+"', sizingMethod='scale')";
}


function lightbox_showBg(){
	$("#lightbox_bg").css({
		width: document.body.scrollLeft+document.body.clientWidth, 
		height: document.body.clientHeight,
		top: document.body.scrollTop}).show().addClass("loading_big");
	//centerToScreen("lightbox_bg");
	$(window).bind('scroll', function(){
		document.getElementById("lightbox_bg").style.top = document.body.scrollTop;
	});
}
function lightbox_close(){
	$("#lightbox_content").children().fadeOut(function(){
		$("#lightbox").hide();
		//$($('#lightbox_content')[0].childNodes[0]).hide();
		//document.body.appendChild($('#lightbox_content')[0].childNodes[0]);
		//?????
		//alert(this.childNodes[0].id);
		//alert(this.hasChildNodes());
		//this.removeChild(this.childNodes[0]);
    });
	$("#lightbox_bg").hide();
	$("#lightbox_close").hide();
	//$(window).scroll(function(){});
	$(window).unbind('scroll');
}
function lightbox_showCloseButton(){
	$("#lightbox_bg").removeClass("loading_big");
    var position = $("#lightbox").position();
    $('#lightbox_close').css({left: position.left+$("#lightbox").width()-17, top: position.top-11}).show();	
}

$(function () {
	$(document.body).append('<table cellspacing="0" cellpadding="0" id="lightbox">'+
			'<tr><td></td><td></td><td></td></tr>'+
			'<tr><td></td><td></td><td></td></tr>'+
			'<tr><td></td><td></td><td></td></tr>'+
			'</table>');
	$(document.body).append('<div id="lightbox_bg"></div>');
	$(document.body).append('<div id="lightbox_close"></div>');
	
	lightbox_tds = $("#lightbox").find("td");
	lightbox_tds[0].id = "lightbox_lt";
	lightbox_tds[1].id = "lightbox_t";
	lightbox_tds[2].id = "lightbox_rt";
	lightbox_tds[3].id = "lightbox_l";
	lightbox_tds[4].id = "lightbox_content";
	lightbox_tds[5].id = "lightbox_r";
	lightbox_tds[6].id = "lightbox_lb";
	lightbox_tds[7].id = "lightbox_b";
	lightbox_tds[8].id = "lightbox_rb";

	if ($.browser.msie && $.browser.version<=6){ //PNG fix
		//alert("Я Ые6");
		for (i=0; i<lightbox_tds.length; i++){
			fixPNG(lightbox_tds[i]);
		}
		fixPNG($("#lightbox_close")[0]);
		
		//fix all others
		$(".fixpng").each(function(){
			fixPNG(this);
		});		
	}
	
	
	$("a.imgpopup").click(function() {
		lightbox_showBg();
		//return false;
		//$("#lightbox_content").html("").width("200").height("200").addClass("loading_big"); 
		//$("#lightbox").show(); centerToScreen("lightbox");
		var imgpopup = new Image();
		$(imgpopup).load(function () {
		    var container = $('#lightbox_content'); 
		    //$(this).hide();
		    //alert(this.width);
		    container.html(this); //.width(this.width).height(this.height); //removeClass("loading_big")
		    $("#lightbox").show(); centerToScreen("lightbox");
		    $(this).hide().fadeIn();
		    lightbox_showCloseButton();
		//.click(function () { lightbox_close(); ),
		})
		.error(function () {
			lightbox_close();
			alert("Error loading "+attr('src'));
		});
		$(imgpopup).attr('src', this.href);
		return false;
	});		
	
	$("a.idpopup").click(function(){
		lightbox_showBg();
		ido = $("#"+$(this).attr("idpopup"));
	    var container = $('#lightbox_content');
	    resizeToHoldContent(container, ido);
	    $("#lightbox").show(); centerToScreen("lightbox");
	    container.html("").removeClass("loading_big");
	    container[0].appendChild(ido[0]);
	    ido.fadeIn();
	    centerToScreen("lightbox");
	    lightbox_showCloseButton();
		return false;
	});

	var ajaxpopup_width, ajaxpopup_height; 
	$("a.ajaxpopup").click(function() {
		lightbox_showBg();
		params = $(this).attr("params");
		params = params ? eval("({"+params+"})") : undefined; //expect it to be json
		//alert(params);
		ajaxpopup_width = params && params.width ? params.width : 0;  
		ajaxpopup_height = params && params.height ? params.height : 0;  
		//$("#lightbox_content").html("").width(200).height(200).addClass("loading_big").click(lightbox_close);
		//$("#lightbox").show(); centerToScreen("lightbox");
		$.ajax({
			type: "GET",
			url: this.href,
			success: function(html){
				var container = $('#lightbox_content');
				container.html("<div id=ajaxpopup_content>"+html+"</div>"); //removeClass("loading_big")
				if (ajaxpopup_width) $("#ajaxpopup_content").width(ajaxpopup_width);
				if (ajaxpopup_height) $("#ajaxpopup_content").height(ajaxpopup_height);
				resizeToHoldContent(container, $("#ajaxpopup_content"));
			    //centerToScreen("lightbox");
				$("#lightbox").show(); centerToScreen("lightbox");
				$("#ajaxpopup_content").hide().fadeIn();
			    lightbox_showCloseButton();
			},
			error: function () {
				lightbox_close();
				alert("Error loading data");
			}
		});		
		return false;
	});	
		
	$("#lightbox_close, #lightbox_bg, #lightbox").click(lightbox_close);		
});


/* =====================================================================================================
 * cookies.js ============================================================================================
 * =====================================================================================================*/


function Set_Cookie( name, value, expires, path, domain, secure ) 
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	/*
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	*/
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}



/* =====================================================================================================
 * check.js ============================================================================================
 * =====================================================================================================*/

var id_error;

function HighlightError(f, i){
  //f[i].style.backgroundColor="#C3C3C3";
  f[i].className = "inputerror";
  if ((id_error==-1) || (i<id_error)){
  	f[i].focus();
	id_error = i;
  }
}

function CheckRequired(f, i){
	//alert("req "+i);
	if (f[i].type=="text" || f[i].type=="password"){
		if (f[i].value.length==0){
			HighlightError(f, i);
			return false;
		}
	}else if (f[i].type=="textarea"){
		if (f[i].value.length==0){
			HighlightError(f, i);
			return false;
		}
	}else if (f[i].type=="select-one"){
		if (f[i][ f[i].selectedIndex ].text.length==0 || f[i][ f[i].selectedIndex ].value==""){
			HighlightError(f, i);
			return false;
		}
	}else if (f[i].type=="select-multiple"){
		for (si=0; si<f[i].length; si++)
			if (f[i].options[si].selected)
				return true;
		HighlightError(f, i);
		return false;
	}else if (f[i].type=="checkbox"){
		if (!f[i].checked){
			HighlightError(f, i);
			return false;
		}
	}else if (f[i].type=="file"){
		if (f[i].value.length==0){
			HighlightError(f, i);
			return false;
		}
	}else{
		//alert(f[i].type); return false;
	}

	return true;
}


//-------------------------------------------------
function Raise(f,i){
	HighlightError(f,i);
	alert('Неверный e-mail адрес');
	return false;
}
function valid_email(f,i) {
		e = f[i];
		e_mail = e.value;

		zyuka = e_mail.indexOf("@");
		if (zyuka==-1) return Raise(f, i);

		dot = e_mail.indexOf(".", zyuka);
		if (dot==-1) return Raise(f, i);

		space = e_mail.indexOf(" ");
		if (space!=-1) return Raise(f, i);

		l = e_mail.length;
		if (l<6) return Raise(f, i);

		if (zyuka+1>=dot) return Raise(f, i);
		if (dot+3>l) return Raise(f, i);

		return true;
}

function CheckEmail(f, i) {
	if (f[i].type=="text"){
		if (!CheckRequired(f, i)) return false;
		return valid_email(f, i);
	}
	return true;
}
function CheckEmailOrNull(f, i) {
	if (f[i].type=="text"){
		if (f[i].value=="") return true;
		return valid_email(f, i);
	}
	return true;
}

//--------------------------------------------------------

function CheckInt(f,i) {
	if (f[i].type=="text"){
		v = f[i].value;
		for (s=0; s<v.length-1; s++){
			ch = v.charAt(s);
			if ( (ch=='0')||(ch=='1')||(ch=='2')||(ch=='3')||(ch=='4')||(ch=='5')||(ch=='6')||(ch=='7')||(ch=='8')||(ch=='9') )
				continue;
			HighlightError(f, i);
			alert('Not an integer!');
			return false;
		}
	}
	return true;
}
//--------------------------------------------------------
function CheckFloat(f,i) {
	if (f[i].type=="text"){
		v = f[i].value;
		for (s=0; s<v.length-1; s++){
			ch = v.charAt(s);
			if ( (ch=='.')||(ch=='0')||(ch=='1')||(ch=='2')||(ch=='3')||(ch=='4')||(ch=='5')||(ch=='6')||(ch=='7')||(ch=='8')||(ch=='9') )
				continue;
			HighlightError(f, i);
			//alert('Not a float!');
			return false;
		}
	}
	return true;
}
//--------------------------------------------------------

function CheckPositive(f,i) {
	if (f[i].type=="text"){
		v = f[i].value;
		if (v.charAt(0)=='0' || v.length==0){
			HighlightError(f, i);
			alert('Должно быть целое положительное');
			return false;
		}
		for (s=0; s<v.length-1; s++){
			ch = v.charAt(s);
			if ( (ch=='0')||(ch=='1')||(ch=='2')||(ch=='3')||(ch=='4')||(ch=='5')||(ch=='6')||(ch=='7')||(ch=='8')||(ch=='9') )
				continue;

			HighlightError(f, i);
			alert('Должно быть целое положительное');
			return false;
		}
	}
   return true;
}
function CheckPositiveOrNull(f,i) {
	if (f[i].type=="text"){
		if (f[i].value=="") return true;
		return CheckPositive(f,i);
	}
   return true;
}
//--------------------------------------------------------

function CheckPassword(f, i) {
  notfound = true;
	  		passwd1 = f[i].value;
			passwd2 = f[i+1].value;
			if ( passwd1 != passwd2 ){
				HighlightError(f, i);
				HighlightError(f, i+1);
				alert('Пароли не совпадают');
				notfound = false;
			}else if ( passwd1==''){
				HighlightError(f, i);
				HighlightError(f, i+1);
				//alert('Password required!');
				notfound = false;
			}
  return notfound;
}

//--------------------------------------------------------

function Check(f){
		id_error = -1;

		res = true;
		for (i=0; i<f.length; i++){
			//f[i].style.backgroundColor="";
			if (f[i].className=="inputerror") f[i].className = "";
			if (f[i].id=="required"){
				res = CheckRequired(f, i) && res;
		  	}else if (f[i].id=="email"){
				res = CheckEmail(f, i) && res;
			}else if (f[i].id=="int"){
				res = CheckInt(f, i) && res;
			}else if (f[i].id=="float"){
				res = CheckFloat(f, i) && res;
			}else if (f[i].id=="password"){
				res = CheckPassword(f, i) && res;
			}else if (f[i].id=="positive"){
				res = CheckPositive(f, i) && res;
			}else if (f[i].id=="positiveornull"){
				res = CheckPositiveOrNull(f, i) && res;
			}else if (f[i].id=="emailornull"){
				res = CheckEmailOrNull(f, i) && res;
			}
		}

		return res;
}



function Clear(el, tpl){
	if (el.value==tpl) el.value = '';
}


/* =====================================================================================================
 * ajax.js ============================================================================================
 * =====================================================================================================*/


var xmlHttp;
function ajax(method, url, vars, callback) {
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}

	// fighting with cache
	var d = new Date();
	ts = d.getTime();
	tsparam = url.indexOf('?') > -1 ? "&nocache=" + ts : "?nocache=" + ts;

	xmlHttp.open(method, url + tsparam, true);
	xmlHttp.onreadystatechange = callback;

	if (method=="POST"){
		//alert(vars);
		xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	}

	xmlHttp.send(vars);

}

function ajax_params2str(f) {
	var getstr = "&";
	for (i=0; i<f.length; i++){
		if (f[i].type=="text" || f[i].type=="textarea" || f[i].type=="hidden"){
			getstr += f[i].name + "=" + encodeURIComponent(f[i].value) + "&";
		}else if (f[i].type=="select-one"){
			getstr += f[i].name + "=" + f[i].options[f[i].selectedIndex].value + "&";
		}else if (f[i].type=="radio"){
			getstr += f[i].name + "=" + f[i].value + "&";
		}else if (f[i].type=="checkbox"){
			getstr += f[i].name + "=" + (f[i].checked?"on":"") + "&";
		}
	}
	//alert(getstr);
	return getstr;
}

/**
 * Converts the given data structure to a JSON string.
 * Argument: arr - The data structure that must be converted to JSON
 * Example: var json_string = array2json(['e', {pluribus: 'unum'}]);
 * 			var json = array2json({"success":"Sweet","failure":false,"empty_array":[],"numbers":[1,2,3],"info":{"name":"Binny","site":"http:\/\/www.openjs.com\/"}});
 * http://www.openjs.com/scripts/data/json_encode.php
 */
function array2json(arr) {
    var parts = [];
    var is_list = (Object.prototype.toString.apply(arr) === '[object Array]');

    for(var key in arr) {
    	var value = arr[key];
        if(typeof value == "object") { //Custom handling for arrays
            if(is_list) parts.push(array2json(value)); /* :RECURSION: */
            else parts[key] = array2json(value); /* :RECURSION: */
        } else {
            var str = "";
            if(!is_list) str = '"' + key + '":';

            //Custom handling for multiple data types
            if(typeof value == "number") str += value; //Numbers
            else if(value === false) str += 'false'; //The booleans
            else if(value === true) str += 'true';
            else str += '"' + value + '"'; //All other things
            // :TODO: Is there any more datatype we should be in the lookout for? (Functions?)

            parts.push(str);
        }
    }
    var json = parts.join(",");
    
    if(is_list) return '[' + json + ']';//Return numerical JSON
    return '{' + json + '}';//Return associative JSON
}
