$(function (){
	$('.recomend_navi a').click(
		function(){
			$('.recomend_navi a').removeClass('active');
			$('.recomend_navi a:contains("'+this.innerHTML+'")').addClass('active');
			$('.recomend_page').hide();
			$('#recomend_page_'+this.innerHTML).show();
		}
	);
	
	preventSelection(document);
	$('a.light-box').each(function(){
		$(this).removeAttr('onclick')
		$(this).click(function(){
			preView(this.href,0,0);
			return false;
		})
	});
	$("input[name='item_form[email]']").focus(function (){
		if (this.value == 'email@email.ru') this.value = '';
	})
	$("input[name='item_form[email]']").blur(function (){
		if (this.value == '') this.value = 'email@email.ru';
	})
	$("input[name='item_form[login]']").focus(function (){
		if (this.value == 'login') this.value = '';
	})
	$("input[name='item_form[login]']").blur(function (){
		if (this.value == '') this.value = 'login';
	})
	$("input[name='item_form[passw]']").focus(function (){
		if (this.value == 'password') this.value = '';
	})
	$("input[name='item_form[passw]']").blur(function (){
		if (this.value == '') this.value = 'password';
	})
		
	$selectes = $("select_");
	
	if ($.browser.msie && $.browser.version < 8)
	{
		$('table[width="100%"]').css('width','99%');
	}
	
	for (i=0;i<$selectes.length;i++){
		select = $selectes[i];
		$select = $(select);
		$select.hide();
		$select.attr("idx",$select.attr("id"));
		$select.attr("id","select_"+i);
		$parent = $select.parent();
		
		inpt  = document.createElement("input");
		$inpt = $(inpt);
		$inpt.attr("id","inptSel_"+i);
		$inpt.attr("type","text");
		$inpt.attr("class","text_h21");
		$inpt.css("cursor","pointer");
		$inpt.click(listDown);
		$inpt.focus(listDown);
		$inpt.keydown(function (){return false;});
		
		a = document.createElement("a");
		$(a).attr("id","linkSel_"+i);
		$(a).attr("href","");
		$(a).attr("class","down");
		$(a).click(listDown);
		
		div = document.createElement("div");
		$div = $(div);
		$div.attr("id","divDrop_"+i);
		$div.attr("class","drop");
		for (j=0;j<select.options.length;j++)
		{
			aOption = document.createElement("a");
			aOption.innerHTML = select.options[j].innerHTML;
			$(aOption).attr("value",select.options[j].value);
			
			if (select.options[j].selected){
				$inpt.val($(select.options[j]).text());
			}
				
			$(aOption).click(checkSelect);
			$div.append(aOption);
		}
		
		$parent.append("<span class=\"inpt_l_h21\"></span>");
		$parent.append(inpt);
		$parent.append(a);
		$parent.append(div);
		$(document).click(function (){$(".drop").hide();});
		
		$div.css("min-width",$inpt.width() + 6 + 21);
//		$div.css("left",$inpt.offset().left - 6);
		$div.css("top",$inpt.offset().top+$inpt.height() + 2);
	}
	$(".inbasket").click(function (){
		idx = this.id.split("_")[2];
		if (!idx) return
		count = $("#inpt_inbasket_"+idx).val();
		if (count == 0 || count == "") {
			alert("Укажите количество товара");
			$("#inpt_inbasket_"+idx).focus();
			return
		}
//		re = /^[0-9]+$/ig;
//		if (!re.test(count)){
//			alert("Количество товара должно быть целым числом");
//			$("#inpt_inbasket_"+idx).focus();
//			return
//		}
		req = $.ajax({
			type:"POST",
			url:host+"/ajax/addbasket.php",
			data:"id="+idx+"&count="+count+"&PHPSESSID="+phpsessid,
			success: function(msg){
			     if (msg == "error") {
			     	alert("Не удалось добавить товар в корзину");
			     	return;
			     }
			     var tmp = eval("("+msg+")");
			     if (tmp['status']='Ok'){
			     	$("#priceAll").html(tmp['priceAll']);
			     	$("#countAll").html(tmp['countAll']);
			     	alert("Товар успешно добавлен в корзину");
			     }
		   }
		});
	});
	
	if ($("select[idx=county]")[0])
		$("select[idx=county]")[0].onchange = function(el){
			pid = el.options[el.options.selectedIndex].value;
			if (!pid) return;
			$("select[idx=region]").empty();
			if (!window.countyArr[pid]) return;
			idx = $("select[idx=region]")[0].id.split("_")[1];
			$("#divDrop_"+idx).html("");
			
			for(i=0;i<window.countyArr[pid].length;i++){
				nOption = document.createElement("option");
				nOption.value = window.countyArr[pid][i]['value'];
				nOption.innerHTML = window.countyArr[pid][i]['title'];
				
				aOption = document.createElement("a");
				aOption.innerHTML = window.countyArr[pid][i]['title'];
				$(aOption).attr("value",window.countyArr[pid][i]['value']);

				$(aOption).click(checkSelect);
				$("#divDrop_"+idx).append(aOption);
				
				$("select[idx=region]").append(nOption);
			}
		};
		
	$(".toggleList").click(function (){
		idx = this.id.split("_")[1];
		$("#d_"+idx).slideToggle("slow");
	})
});
function removeBasket(id,title){
	if (!id) return;
	if (!confirm("Вы действительно хотите удалить из корзины \n"+title+"?")) return;
	req = $.ajax({
		type:"POST",
		url:host+"/ajax/addbasket.php",
		data:"id="+id+"&count=1&PHPSESSID="+phpsessid+"&dell=1",
		success:function(msg){document.location.reload()}
	});
	return false;
}
function listDown(){
	idx = this.id.split("_")[1];
	$(".drop").hide();
	$("#divDrop_"+idx).show();
	return false;
}
function checkSelect(){
	idx = $(this).parent()[0].id.split("_")[1];
	value = $(this).attr("value");
	$("#divDrop_"+idx).hide();
	select = $("#select_"+idx)[0];
	for (i=0;i<select.options.length;i++){
		if (value == select.options[i].value){
			$("#inptSel_"+idx).val($(select.options[i]).text());
			select.options[i].selected = true;
			break;
		}
	}
	if (typeof(select.onchange) == "function")
		select.onchange(select);
}
function selectCity(){
	if ($("select[idx=country]")[0].options.selectedIndex == -1) return;
	country = $("select[idx=country]")[0].options[$("select[idx=country]")[0].options.selectedIndex].value;
	if (country == "") return;
	val = $("#city").val();
	$("#downList").html("<img src='"+host+"/images/ajax-loader.gif' width='16px' height='16px'>");
	$("#downList").show();
	$("#downList").width($("#city").width()+5);
	$("#downList").css("text-align","center");
	req = $.ajax({
		type:"GET",
		url:host+"/ajax/selectCity.php",
		data:"countryID="+country+"&search_text="+val,
		success: function(msg){
			if (msg == "error"){
				$("#downList").hide();
				return;
			}
			var result = eval("("+msg+")");
			if (result['status'] != "Ok"){
				$("#downList").hide();
				return;
			}
			$("#downList").html("");
			$("#downList").css("text-align","left");
			for (i=0;i<result['result'].length;i++){
				a = document.createElement("a");
				$(a).html(result['result'][i]['title']);
				$(a).click(function (){
					$("#city").val($(this).html());
				});
				$("#downList").append(a);
			}
		}
	});
		
}
function richEdit(divID,textID){
	if (window.editorWindow){
		if (!window.editorWindow.closed){
			alert("Закройте окно редактора и попробуйте снова.");
			return ;
		}
	}
	$(window).unload(function(){
		if (window.editorWindow && !window.editorWindow.closed)
			window.editorWindow.close();
	})
	window.parentDivElement  = $('#'+divID);
	window.parentTextElement = $('#'+textID);
	window.editorWindow = window.open(host+"/editor/editor.php","editorWindow");
}

function preView(url_img,width,height){
	if (url_img.match('^http\:\/\/'))
		var url = url_img
	else
		var url = host +"/uplfile/"+url_img;
	
	mask = document.createElement("div");
	mask.id = "popupMask";
	mask.className = "popupMask";
	wndWidth 	= $(document).width();
	wndHeight 	= $(document).height();
	$(mask).width(wndWidth);
	$(mask).height(wndHeight);
	$(window).bind("scroll",function (e){
		clearTimeout(window.tm);
		window.tm = setTimeout('$("#popupCont").animate({"left":getBodyScrollLeft(),"top":getBodyScrollTop()});',500);
	});
	/*
	if (document.body.clientWidth < width || document.body.clientHeight < height)
		$(document.body).css("overflow","hidden");
	*/
	document.getElementsByTagName("body")[0].appendChild(mask);
	cont = document.createElement("div");
	cont.id = "popupCont";
	attr = (width > height)?"width='640px'":"height='640px'";
	$(cont).css("width",(document.body.parentElement?document.body.parentElement.clientWidth:document.body.clientWidth));
	$(cont).css("height",(document.body.parentElement?document.body.parentElement.clientHeight:document.body.clientHeight));
	$(cont).css("min-width",(document.body.parentElement?document.body.parentElement.clientWidth:document.body.clientWidth));
	$(cont).css("min-height",(document.body.parentElement?document.body.parentElement.clientHeight:document.body.clientHeight));
	$(cont).css("left",getBodyScrollLeft());
	$(cont).css("top",getBodyScrollTop());
	$(cont).css("position","absolute");
	$(cont).css("z-index","1000");
	$(cont).css("display","none");
	$(cont).css("overflow","auto");
	$(cont).html("<table height='100%' align='center'><tr><td id='img_cont'><img src='"+url+"' "+attr+" align='absmiddle' onclick='HideMask()'><div style='text-align:right;background-color:#FFFFFF'><img src='"+host+"/images/close_prev.gif' width='26px' height='26px' style='cursor:pointer' title='Закрыть' alt='Закрыть' onclick='HideMask()'></div></td></tr></table>");
	img = document.createElement("img");
	img.width 	= width;
	img.height	= height;
	img.src 	= url;
	$(document.body).append(cont);
	$(mask).show("");
	$(cont).fadeIn("slow");
	return false;
}
function HideMask(){
	$("#popupMask").remove();
	$("#popupCont").remove();
	$(document.body).css("overflow","auto");
}
function getBodyScrollTop()
{
  return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
}

function getBodyScrollLeft()
{
  return self.pageXOffset || (document.documentElement && document.documentElement.scrollLeft) || (document.body && document.body.scrollLeft);
}

function preventSelection(element){
  var preventSelection = false;

  function addHandler(element, event, handler){
    if (element.attachEvent) 
      element.attachEvent('on' + event, handler);
    else 
      if (element.addEventListener) 
        element.addEventListener(event, handler, false);
  }
  function removeSelection(){
    if (window.getSelection) { window.getSelection().removeAllRanges(); }
    else if (document.selection && document.selection.clear)
      document.selection.clear();
  }
  function killCtrlA(event){
    var event = event || window.event;
    var sender = event.target || event.srcElement;

    if (sender.tagName.match(/INPUT|TEXTAREA/i))
      return;

    var key = event.keyCode || event.which;
    if (event.ctrlKey && key == 'A'.charCodeAt(0))  // 'A'.charCodeAt(0) можно заменить на 65
    {
      removeSelection();

      if (event.preventDefault) 
        event.preventDefault();
      else
        event.returnValue = false;
    }
  }

  // не даем выделять текст мышкой
  addHandler(element, 'mousemove', function(){
    if(preventSelection)
      removeSelection();
  });
  addHandler(element, 'mousedown', function(event){
    var event = event || window.event;
    var sender = event.target || event.srcElement;
    preventSelection = !sender.tagName.match(/INPUT|TEXTAREA/i);
  });

  // борем dblclick
  // если вешать функцию не на событие dblclick, можно избежать
  // временное выделение текста в некоторых браузерах
  addHandler(element, 'mouseup', function(){
    if (preventSelection)
      removeSelection();
    preventSelection = false;
  });

  // борем ctrl+A
  // скорей всего это и не надо, к тому же есть подозрение
  // что в случае все же такой необходимости функцию нужно 
  // вешать один раз и на document, а не на элемент
  addHandler(element, 'keydown', killCtrlA);
  addHandler(element, 'keyup', killCtrlA);
}

function credit_calc()
{
	var credit_full_ammount  = parseFloat($('#credit_full_ammount').val().replace(',','.'));
	var credit_term			 = parseInt($('#credit_term').val());
	var credit_percent		 = parseFloat($('#credit_percent').val().replace(',','.'));
	var credit_first_payment = parseFloat($('#credit_first_payment').val().replace(',','.'));
	
	switch(true)
	{
		case !credit_full_ammount: alert('Укажите стоимость лечения'); return false;
		case !credit_term: alert('Укажите срок кредита'); return false;
		case !credit_percent: alert('Укажите ставку по банковскому кредиту'); return false;
		case !(credit_full_ammount = credit_full_ammount - credit_first_payment): alert('Сумма первоночального взноса должна быть меньше суммы кредита'); return false;
	}
	
	var month_percent = credit_percent / 12;
	var year_percent  = month_percent * credit_term;
	var ammount_overpayment = (credit_full_ammount * year_percent) / 100;
	
	credit_full_ammount = credit_full_ammount + ammount_overpayment;
	var month_payment = credit_full_ammount / credit_term;
	var month_overpayment = ammount_overpayment / credit_term;
	
	
	$('#credit_full_ammount_result').val(number_format(credit_full_ammount, 2, ',', ' '));
	$('#credit_month_payment')		.val(number_format(month_payment, 2, ',',' '));
	$('#credit_full_overpayment')	.val(number_format(credit_full_ammount + credit_first_payment, 2, ',', ' '));
	$('#budget_calc_result').show();
}
function number_format( number, decimals, dec_point, thousands_sep ) {  
	// Format a number with grouped thousands
    //
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://crestidg.com)

    var i, j, kw, kd, km;

    // input sanitation & defaults
    if( isNaN(decimals = Math.abs(decimals)) ){
        decimals = 2;
    }
    if( dec_point == undefined ){
        dec_point = ",";
    }
    if( thousands_sep == undefined ){
        thousands_sep = ".";
    }

    i = parseInt(number = (+number || 0).toFixed(decimals)) + "";

    if( (j = i.length) > 3 ){
        j = j % 3;
    } else{
        j = 0;
    }

    km = (j ? i.substr(0, j) + thousands_sep : "");
    kw = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep);
    //kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).slice(2) : "");
    kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).replace(/-/, 0).slice(2) : "");

    return km + kw + kd;
}


function getValueMoney(value, round, delim){
	value = "" + value;
	len = value.length;
	pos = value.indexOf(".");
	if (pos == -1) {
		pos = value.indexOf(",");
		if (pos == -1){
			return value + delim + str_repeat("0", round);
		}
	}
	if (len - pos - 1 < round){
		value = value + str_repeat("0", round - (len - pos - 1));
	}
	value = value.substr(0, pos + 1 + round).replace(/\./, delim);
	return value;
}

