var keysave = 0;
var antiCusel = 0;

// используем кнопки для постраничной
if($(".pagenavig a").length > 0){
	$("body").keydown(function(e){
	  if(keysave==17 && e.which==39) location.href=$(".pagenavig .next").attr("href");
	  else if(keysave==17 && e.which==37) location.href=$(".pagenavig .prev").attr("href");
	  else keysave = e.which;
	});
}
function round(num, dec){
	var dec = 10 ^ dec;
	return Math.round(num * dec) / dec;
}
function sklon(num, form1, form2, form3){
	if(num%10==0 || num%10>4 || num==11 || num==12 || num==13 || num==14) return form1;
	else if(num%10==1) return form2;
	else return form3;
}

// Полезные функции
function getAbs(val){
	return Math.abs(eval(val.replace("px","")));
}
function getClientWidth(){
  //return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientWidth:document.body.clientHeight;
  return $.browser.opera? window.innerWidth : $(window).width();
}

function getClientHeight(){
  //return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.innerHeight;
  return $.browser.opera? window.innerHeight : $(window).height();
}

function formatSumm(summ){
	var costf = "";
	cost = summ+"";
	cnt = 0;
	for(i=(cost.length-1);i>=0;i--){
		if((cnt)%3==0) costf = ' '+costf;
		costf = cost[i]+costf;
		cnt ++;
	}
	return costf;
}



// Функции автозагрузки
$(function(){


	// Универсальная простая форма
	// Для работы необходим JQuery и JQuery.forms
	// Форме нужно дать класс uniform, приготовить слой для ошибок .error и картинку для анимации работы
	// action формы ведёт на страницу с аякс-обработчиком
	$(".uniform input").keypress(function(event,form){
		if(event.keyCode==13) $(this).submit();
	});
	$(".uniform a.submit").click(function(){$(this).submit();});
	$(".uniform").submit(function(){
		if(antiCusel == 0){
			$(this).addClass("active").removeClass("success");
			$(this).find(".element-form").removeClass("error");
			$(this).find(".error").show().html("<img class='preloader' src='/images/preloader.gif'>");
			var ser = $(this).formSerialize();
			$.post($(this).attr("action"),ser,function(data){
				if (typeof handler == 'function') {
					handler(data);
				}
				if(data.match("error")){
					setTimeout((function(data_){return function(){
						var mat = data.match(/errorblock:([а-яА-Я0-9a-zA-Z_\-]+)/);
						if(mat){
							data = data.replace("errorblock:"+mat[1],"");

							while (mat[1].match("_")){
								mat[1] = mat[1].replace("_"," ");
								if(mat) $(".uniform.active input[name='"+mat[1]+"']").parents(".element-form").addClass("error");
							}
						}

						$(".uniform.active .error").html(data.replace("error ","")).fadeIn();					
						

						$(".uniform.active").removeClass("active");
					}})(data),200);		
				}else  if(data.match("success")){
					setTimeout((function(data_){return function(){
						if(data.match("refresh")) history.go(0);
						else if(data.match("redirect")){
							var mat = data.match(/redirect:([0-9a-zA-Z-\-\/]+)/);
							if(mat) location.href = (mat[1]);
						}else if(data.match("alert")){
							alert("success");
						}
						//$(".uniform.active .error").html(data.replace("success ","")).addClass("success").fadeIn();
						$(".uniform.active").removeClass("active");
					}})(data),200);		
				}else{
					$(".uniform.active .error").html("").fadeIn();
					$(".uniform.active").removeClass("active");
				}
			});
		}
		return false;
	});


	// Задаём полям класс hasDef и rel с дефолтным значением 
	$("input.hasDef, textarea.hasDef").each(function(){
		if($(this).val()!=$(this).attr("rel")) $(this).addClass("hasText");
		$(this).blur(function(){
			if($(this).val()==""){
				$(this).val($(this).attr("rel"));
				$(this).removeClass("hasText");
			}
		});
		$(this).focus(function(){
			if($(this).val()==$(this).attr("rel")){
				$(this).val("");
				$(this).addClass("hasText");
			}			
		});
	});


});

// Защищаем нашу форму от Cusel Submit
$(".cusel").live('mouseup',function(){antiCusel = 1;});
$(".cusel").live('click',function(){setTimeout(function(){antiCusel = 0;},100);});

// Вункция считает абсолютное положение элемента на странице [0] - лево [1] - верх
function offsetPosition(element) {
	if(element!=undefined){
		var offsetLeft = 0, offsetTop = 0;
		do {
			offsetLeft += element.offsetLeft;
			offsetTop  += element.offsetTop;
		} while (element = element.offsetParent);
		return [offsetLeft, offsetTop];
	}
}

