function replaceHTML(el, html) {
    var oldEl = (typeof el === "string" ? document.getElementById(el) : el);
    var newEl = document.createElement(oldEl.nodeName);
    // Preserve the element's id and class (other properties are lost)
    newEl.id = oldEl.id;
    newEl.className = oldEl.className;
    // Replace the old with the new
    newEl.innerHTML = html;
    oldEl.parentNode.replaceChild(newEl, oldEl);
    /* Since we just removed the old element from the DOM, return a reference
    to the new element, which can be used to restore variable references. */
    return newEl;
};

function ajax_createRequestObject()
{
    var xmlhttp=false;
    /*@cc_on @*/
    /*@if (@_jscript_version >= 5)
    // JScript gives us Conditional compilation, we can cope with old IE versions.
    // and security blocked creation of the objects.
    try {
	xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
	try {
    	    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
	catch (E) {
    	    xmlhttp = false;
        }
    }
    @end @*/
    if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
	try {
	    xmlhttp = new XMLHttpRequest();
	}
        catch (e) {
	    xmlhttp=false;
        }
    }
    if (!xmlhttp && window.createRequest) {
	try {
	    xmlhttp = window.createRequest();
	}
	catch (e) {
	    xmlhttp=false;
	}
    }
    return xmlhttp;
}

var ajax_httpprot = ajax_createRequestObject();

function shopping(id,sec,qty){
    sec_arg = (sec ? 999 : 0);
    c_num = document.getElementById('cart_num');
    c_total = document.getElementById('cart_total');
    descr = document.getElementById('descr_'+id);

    upqty = document.getElementById('upqty'+id);
    downqty = document.getElementById('downqty'+id);

    ajax_httpprot.open('get', '/cart/prod'+id+'/qty'+qty+'/');
    ajax_httpprot.onreadystatechange = processReqChange;
    ajax_httpprot.send(null);
}

function processReqChange(){
    if(ajax_httpprot.readyState == 4)
    {
    	var response = ajax_httpprot.responseText;
    	arr = response.split("|");
    	id = arr[0];		//id продукта
    	cart = arr[1];		//в корзине сейчас
    	action = arr[2];	//экшен
    	total2 = arr[3];	    //сумма

        if(sec_arg > 0) //удаление строки
        {
            if(totqty > 0)
        	    c_num.innerHTML = totqty;
            else
                c_num.innerHTML = cart;
//        	c_total.innerHTML = number_format(total,',');
        }
        else            //в корзину\из корзины
        {
            if(action == 'add')
            {
                upqty.style.display = 'inline-block';
                downqty.style.display = 'inline-block';
                action = "В корзину";
            }
            else        //удалить
            {
                upqty.style.display = 'none';
                downqty.style.display = 'none';
                action = 'Удалить';
            }
    	    c_num.innerHTML = cart;
    	    c_total.innerHTML = number_format(total2,',');
    	    descr.innerHTML = action;
            document.getElementById('cartimg').src = '/img/basket_'+(total2 > 0 ? 'full':'empty')+'.png';
        }
    }
}







function checkout(price,id,num_prod,def_price){
    var fieldcount = document.forms.buy.elements.length;
    final = 0;
    for (var i=0; i< fieldcount; i++)
    {
	    var obj = document.forms.buy.elements[i];
	    if(i%2==0)
	    {
	        qty = obj.value;
		    continue;
	    }
	    objname = obj.name;
	    if(objname == 'price')
	    {
	        p = obj.value;
	        fp = p*qty;
	        final = final + fp;
	    }
    }
}

function updatecart()
{
    var fieldcount = document.forms.buy.elements.length;
    userfields = 9;
    spinto = fieldcount-userfields;
    final = 0;
    totqty = 0;
    for(i=0;i < spinto;i++)
    {
	    var obj = document.forms.buy.elements[i];
	    if(i%2==0)
	    {
	        qty = obj.value;
            if(!qty)
                qty = 0;
            totqty += parseInt(qty);
		    continue;
	    }

	    objname = obj.name;
        if(obj.name == 'price')
        {
            p = obj.value;
        	fp = p*qty;
        	final = parseInt(final + fp);
        }
    }
}

function delcart(row,id){
    oldqty = document.getElementById('q'+id).value;
    document.getElementById('q'+id).value = 0;
    updatecart();
    document.getElementById(row).style.display='none';
    if(final == 0)
    {
        document.getElementById('oform').style.display='none';
        document.getElementById('confirm').style.display='none';
        document.getElementById('emptycart').innerHTML = 'Ваша корзина пуста';
        document.getElementById('cartimg').src = '/img/basket_empty.png';
    }
    document.getElementById('final_price').innerHTML = number_format(final,',');
    document.getElementById('cart_total').innerHTML = number_format(final,',');
    shopping(id,999,oldqty);
}

function saveqty(id,num_prod){
    ajax_httpprot.open('get', '/cart/prod'+id+'/qty'+num_prod+'/update/');
    ajax_httpprot.onreadystatechange = function(){};
    ajax_httpprot.send(null);
}


function checkout_price(price,id,num_prod){
    updatecart();
    document.getElementById('final_price').innerHTML = number_format(final,',');
    document.getElementById('cart_total').innerHTML = number_format(final,',');
    document.getElementById('cart_num').innerHTML = totqty;
    saveqty(id,num_prod);
}


function openhide(e,id)
{
    if(!e){var e=window.event;}
    if(e.id == 'but')
    {
        return false;
    }
    else
    {
        var detail = document.getElementById('detail'+id);
        if (detail.style.display == 'none')
            detail.style.display = 'block';
        else
            detail.style.display = 'none';
    }
}

function number_format(number, thousands_sep)
{
    var integer = (number > 0 ? Math.floor (number) : Math.abs (Math.ceil (number))).toString ();
    for (i = integer.length - 3; i > 0; i -= 3)
	    integer = integer.substring (0 , i) + thousands_sep + integer.substring (i);
    return integer;
}

function isEmpty(str) {
   for (var i = 0; i < str.length; i++)
      if (" " != str.charAt(i))
          return false;
      return true;
}
function validEmail(mail) 
{
  return (new RegExp ("^[_.0-9A-z-]+@([0-9A-z][0-9A-z_-]+.)+[A-z]{2,4}$").test(mail) ? 1 : 0);
}
function validtel(tel) 
{
  return (new RegExp ("\\d{7,11}").test(tel) ? 1 : 0);
}
function checkform(f)
{
    var errMSG = "";

    var pattern=/['А-я']/;

    if (!pattern.test(document.buy.name.value)) // пустой
        errMSG += "Поле ФИО заполняется русскими буквами\n";

    if (document.buy.delivery.value == '0') // пустой
        errMSG += "Поле доставка обязательно для выбора\n";

    if (isEmpty(document.buy.city.value) && document.buy.delivery.value == 2) // пустой
        errMSG += "Поле город обязательно для заполнения\n";

    if (isEmpty(document.buy.index.value) && document.buy.delivery.value == 2) // пустой
        errMSG += "Поле индекс обязательно для заполнения\n";

    if(validEmail(document.buy.email.value) == 0)
        errMSG += "Поле e-mail заполнено некорректно\n";

    if(validtel(document.buy.phone.value) == 0)
        errMSG += "Поле телефон заполнено некорректно (только цифры)\n";

    if ("" != errMSG)
    {
        alert(errMSG);
        return false;
    }
    else
        document.buy.submit();
}

