function SetCookie(name,cook,path) {
	if (!path) path='/';
	now=new Date();
	D=new Date(now.getTime()+12*60*60*1000);
	document.cookie=name+'='+escape(cook)+'; expires='+D.toGMTString()+'; path='+path+';';
	return true;
}

function GetCookie(name) {
	nn=name+'=';
	i=0;
	while (i<= document.cookie.length) {
	    j=i+nn.length;
	    if (document.cookie.substring(i,j)==nn) {
		    k=document.cookie.indexOf(';',j);
	    	if (k<0) {
		    	k=document.cookie.length;
			}
			return unescape(document.cookie.substring(j,k));
		}
		i=document.cookie.indexOf(' ',i)+1;
		if (i==0) {
			return null;
		}
	}
	return null;
};

function DelCookie(name,path) {
	if (!path) path='';
	D=new Date(0);
	cook=GetCookie(name);
	document.cookie=name+'='+cook+'; expires='+D.toGMTString()+'; path=/'+path+';';
};

function AddChart(id,name) {

    var color = $("select#prod_color").val();
    var size = $("input#prod_size").val();

    SetCookie('props['+id+'][color]',color);
	SetCookie('props['+id+'][size]',size);


	pid='prod['+id+']';

	cnt=GetCookie(pid);
	if (!cnt) cnt=0;
	s='';
	if (cnt>0) s='Кол-во единиц этого товара в корзине : '+cnt+'\n\n';
	s+='Добавить товар ['+name+'] в корзину?';
	if (!confirm(s)) return false;
	cnt++;
	SetCookie(pid,cnt);
	document.Cart.info.value++;
	if (document.all) document.all.cart_info.style.display='inline';
	return false;
}

/*function toCurr(n) {
	return (cc=Math.floor(n))+'.'+String( Math.round((n-cc)*100)+100 ).substr(1);
}*/
function calcRow(n) {
	var cost = $("input#cost"+n).val();
	var count = $("input#count"+n).val();
	//$("input#sum"+n).val(toCurr(cost*count));
	var sum = cost*count;
    var discount = $("input#discount"+n).val();
	var jc_status = $("select#jcstatus").val();
	if(jc_status == 1){
	    sum = sum - (sum * discount / 100);
	}


	$("input#sum"+n).val(sum);

	var weight = $("input#weight"+n).val();
    $("input#sum_weight"+n).val(weight*count);


	if (!$("input#sum"+n).val()) $("input#sum"+n).val(0);
	SetCookie('prod['+n+']',count);
	calcAll();
	return true;
}

function recalcRow() {
    var i = 0;
    while(all_prod_ids[i]){

	   var cost = $("input#cost"+all_prod_ids[i]).val();
	   var count = $("input#count"+all_prod_ids[i]).val();
	   var sum = cost*count;
       var discount = $("input#discount"+all_prod_ids[i]).val();
	   var jc_status = $("select#jcstatus").val();
	   if(jc_status == 1){
	       sum = sum - (sum * discount / 100);
	   }

	   $("input#sum"+all_prod_ids[i]).val(sum);

	   var weight = $("input#weight"+all_prod_ids[i]).val();
       $("input#sum_weight"+all_prod_ids[i]).val(weight*count);

	   if (!$("input#sum"+all_prod_ids[i]).val()) $("input#sum"+all_prod_ids[i]).val(0);

	   SetCookie('prod['+all_prod_ids[i]+']',count);

	   i++;
    }
    calcAll();

	return true;
}

function calcAll(){
    var i = 0;
    var sum = 0;
    while(all_prod_ids[i]){
        var next = $("input#sum"+all_prod_ids[i]).val() * 1;
        sum += next;
        i++;
        //alert(sum);
    }
    $("input#order_total").val(sum);
    calcAllweight();
    delivery_cost();
}

function calcAllweight(){
    var i = 0;
    var sum_weight = 0;
    while(all_prod_ids[i]){
        var next = $("input#sum_weight"+all_prod_ids[i]).val() * 1;
        sum_weight += next;
        i++;
    }
    $("input#sum_weight_total").val(sum_weight);
    $("input#sum_weight_total_show").val(sum_weight+" г.");
}

function subChart(n,name) {
	if (!confirm('Убрать ['+name+'] из корзины?')) return false;
	f=document.fOrder;
	f['count'+n].value=0;
	f['sum'+n].value=0;
	calcAll();
	if (document.all) document.all['r'+n].style.display='none';
	DelCookie('prod['+n+']');
	DelCookie('props['+n+'][color]');
	DelCookie('props['+n+'][size]');
}

function SaveInf(f) {
	now=new Date();
	D=new Date(now.getTime()+1000*60*60*24*365);
	document.cookie=f.name+'='+escape(f.value)+'; expires='+D.toGMTString()+'; path=/;';
	return true;
}

function delivery_cost(){
    var country = $("select#country").val();
    switch(country){
        case "Россия": country = 1;
        break;
        case "Беларусь":
        case "Узбекистан":
        case "Эстония": country = 2;
        break;
        default: country = 3;
    }
    $("input#data_country").val(country);
    //country = (country == "other") ? 3 : country;
    var index = $("input#order_index").val();
    var summ_price = $("input#order_total").val();
    var weight = $("input#sum_weight_total").val();
    weight = (weight != 0) ? weight : 250;
    var pay_method = $("select#order_pay_method").val();



    var delivery_cost;
    //alert("country: " + country + "index: " + index + "summ_price: " + summ_price + "weight: " + weight + "pay_method: " + pay_method);
    if(country && index && summ_price && weight && pay_method){
        $("input#order_total_delivery").val("ожидание...");
        $.ajax({
        type: "POST",
            url: "get_cost_order.php",
            //$country, $index, $summ_price, $weight, $pay_method
            data: "country="+country+"&index="+index+"&summ_price="+summ_price+"&weight="+weight+"&pay_method="+pay_method,
            success: function(msg){
                    $("input#order_total_delivery").val(msg);
                    delivery_cost = msg;
                    switch(pay_method){
                        //sberbank
                        case '1':
                            $("div#msg").html('* в полную стоимость не включена комиссия банка - дополнительно 3%');
                        break;
                        //impeksbank
                        case '2':
                            $("div#msg").html('* при данном варианте оплаты комиссия 0%');
                        break;
                        //yandex
                        case '3':
                            $("div#msg").html('* при данном варианте оплаты комиссия 0%');
                        break;
                        //webmoney R
                        case '4':
                            $("div#msg").html('* В полную стоимость не включена комиссия электронного кошелька, которая будет вычтена при оплате.');
                        break;
                        //nalojjka
                        case '5':
                            var ppp = Math.round(delivery_cost * 1.020006 * 100)/100;
                            $("div#msg").html('*при данном варианте доставки почта дополнительно взымает сбор 1.7% + НДС на сумму сбора, что составит около '+ppp+' руб.');
                        break;
                        //electron
                        case '6':
                            $("div#msg").html('* В полную стоимость не включена комиссия почты (тариф зависит от Вашего региона), которую Вы уплатите при отправке.');
                        break;
                        //paypal
                        case '7':
                            $("div#msg").html('* при данном варианте оплаты комиссия 0%');
                        break;
                        //wu
                        case '8':
                            $("div#msg").html('* В полную стоимость не включена комиссия (зависит от суммы платежа и региона), которую Вы оплатите Банку. ');
                        break;
                        //kurer
                        case '9':
                            var ppp = delivery_cost - summ_price;
                            $("div#msg").html('* стоимость доставки курьером '+ppp+' руб.');
                        break;
                        //webmoney Z
                        case '10':
                            var ppp = delivery_cost - summ_price;
                            $("div#msg").html('* В полную стоимость не включена комиссия электронного кошелька, которая будет вычтена при оплате.');
                        break;
                    }

                    //$("input#comment").val($("div#msg").html());

                    if(pay_method == 8 || pay_method == 10){
                        $("span.currency").text('$');
                    }
                    else{
                        $("span.currency").text('РУБ.');
                    }
                }
        });
    }
    else{
        $("input#order_total_delivery").val('...');
        $("div#msg").html('Необходимо заполнить все поля отмеченные звездочкой (*)');
    }
}

function full_form(){
    $.ajax({
        type: "POST",
            url: "/registration/check_logged",
            async: false,
            success: function(msg){
                    if(msg == 'true'){
                        return true;
                    }
                    else{
                        if (GetCookie('inf_fio'))	document.sendOrder.inf_fio.value=GetCookie('inf_fio');
                        if (GetCookie('inf_phone'))	document.sendOrder.inf_phone.value=GetCookie('inf_phone');
                        if (GetCookie('inf_email'))	document.sendOrder.inf_email.value=GetCookie('inf_email');
                        if (GetCookie('inf_sex'))	document.sendOrder.inf_sex.value=GetCookie('inf_sex');
                        if (GetCookie('inf_country'))	document.sendOrder.inf_country.value=GetCookie('inf_country');
                        if (GetCookie('inf_index'))	$("input#order_index").val(GetCookie('inf_index'));
                        if (GetCookie('inf_obl'))	document.sendOrder.inf_obl.value=GetCookie('inf_obl');
                        if (GetCookie('inf_city'))	document.sendOrder.inf_city.value=GetCookie('inf_city');
                        if (GetCookie('inf_addr'))	document.sendOrder.inf_addr.value=GetCookie('inf_addr');
                        if (GetCookie('inf_jclogin'))	document.sendOrder.inf_jclogin.value=GetCookie('inf_jclogin');
                        if (GetCookie('inf_pay'))	document.sendOrder.inf_pay.value=GetCookie('inf_pay');
                    }
            }
        });
}