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 () {
	
	var imgloader_container = document.createElement('div');
	imgloader_container.setAttribute("id","imgloader_container");
	document.body.appendChild(imgloader_container);	

	var imgloader_closebox = document.createElement('div');
	imgloader_closebox.setAttribute("id","imgloader_closebox");
	document.body.appendChild(imgloader_closebox);	
	
	
	$("a.imgpopup").click(function() {
		$("#imgloader_container").html("").width("500").height("400").addClass('loading').show();
		centerToScreen("imgloader_container");

		var imgpopup = new Image();
		$(imgpopup).load(function () {
		    $(this).hide();
		    var container = $('#imgloader_container'); 
		    container.removeClass('loading').html(this).width($(this).width()).height($(this).height());
		    $(this).fadeIn();
		    $('#imgloader_closebox').show();
		    centerToScreen("imgloader_container");
		    var position = container.position();
		    $('#imgloader_closebox').css({"left":position.left+container.width()+3, "top":position.top-7});
		})
		.error(function () {
			$("#imgloader_container").hide();
			alert("Error loading "+attr('src'));
		})
		.click(function () {
			$("#imgloader_container").fadeOut();	
			$("#imgloader_closebox").hide();
		})
		
		$(imgpopup).attr('src', this.href);
		
		return false;
	});		
	
	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);
	}
	
	$("a.idpopup").click(function() {
		ido = $("#"+$(this).attr("idpopup"));
	    var container = $('#imgloader_container');
	    resizeToHoldContent(container, ido);
	    container.html("").removeClass('loading').show();
	    container[0].appendChild(ido[0]);
	    ido.fadeIn();
	    $('#imgloader_closebox').show();
	    centerToScreen("imgloader_container");
	    var position = container.position();
	    $('#imgloader_closebox').css({"left":position.left+container.width()+3, "top":position.top-7});
		return false;
	});

	var ajaxpopup_width, ajaxpopup_height; 
	$("a.ajaxpopup").click(function() {
		params = $(this).attr("params");
		params = eval("("+params+")"); //expect it to be json
		//alert(params.width);
		ajaxpopup_width = params && params.width ? params.width : 0;  
		ajaxpopup_height = params && params.height ? params.height : 0;  
		$("#imgloader_container").html("").width(200).height(200).addClass('loading').fadeIn().click(function () {
			$("#imgloader_container").fadeOut();	
			$("#imgloader_closebox").hide();
		})
		centerToScreen("imgloader_container");
		$.ajax({
			type: "GET",
			url: this.href,
			success: function(html){
				var container = $('#imgloader_container');
				container.removeClass('loading').html("<div id=ajaxpopup_content>"+html+"</div>");
				if (ajaxpopup_width) $("#ajaxpopup_content").width(ajaxpopup_width);
				if (ajaxpopup_height) $("#ajaxpopup_content").height(ajaxpopup_height);
				resizeToHoldContent(container, $("#ajaxpopup_content"));
			    $('#imgloader_closebox').show();
			    centerToScreen("imgloader_container");
			    var position = container.position();
			    $('#imgloader_closebox').css({"left":position.left+container.width()+3, "top":position.top-7});
			},
			error: function () {
				$("#imgloader_container").hide();
				alert("Error loading data");
			}
		});		
		return false;
	});	
		
		
	$('#imgloader_closebox').click(function() {
		$("#imgloader_container").fadeOut(function(){
			$($('#imgloader_container')[0].childNodes[0]).hide();
			document.body.appendChild($('#imgloader_container')[0].childNodes[0]);
			//alert(this.childNodes[0].id);
			//alert(this.hasChildNodes());
			//this.removeChild(this.childNodes[0]);
	    });
		$("#imgloader_closebox").hide();
	});		
	
});

/* =====================================================================================================
 * 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"){
		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=="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;
		}
	}

	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")
		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
}
