
var h1_header= "<h1><span><b>Корзина товаров</b></span></h1>";

function str_replace(search, replace, subject) {
    return subject.split(search).join(replace);
}
function str_substr(str, start, len) {
	return str.substr(start,len);
}

// пререкодируем
function win2unicode(str) {
   var charmap   = unescape(
      "%u0402%u0403%u201A%u0453%u201E%u2026%u2020%u2021%u20AC%u2030%u0409%u2039%u040A%u040C%u040B%u040F"+
      "%u0452%u2018%u2019%u201C%u201D%u2022%u2013%u2014%u0000%u2122%u0459%u203A%u045A%u045C%u045B%u045F"+
      "%u00A0%u040E%u045E%u0408%u00A4%u0490%u00A6%u00A7%u0401%u00A9%u0404%u00AB%u00AC%u00AD%u00AE%u0407"+
      "%u00B0%u00B1%u0406%u0456%u0491%u00B5%u00B6%u00B7%u0451%u2116%u0454%u00BB%u0458%u0405%u0455%u0457")
   var code2char = function(code) {
               if(code >= 0xC0 && code <= 0xFF) return String.fromCharCode(code - 0xC0 + 0x0410)
               if(code >= 0x80 && code <= 0xBF) return charmap.charAt(code - 0x80)
               return String.fromCharCode(code)
            }
   var res = ""
   for(var i = 0; i < str.length; i++) res = res + code2char(str.charCodeAt(i))
   return res
}

// Смотерть на подмиг кнопки
function basceerclear(){
  document.getElementById("bascet_erros").value="0";
}
function bascetstatclear(ID){
  document.getElementById(ID).value="0";
}
function bascetstat(ID,data,PolEr,reload){
  if (document.getElementById("bascet_reload")){
    if (reload==document.getElementById("bascet_reload").value){
    if (document.getElementById(ID)){
      if (document.getElementById(ID).value!=data){
        if (document.getElementById(PolEr).value == "0"){
           document.getElementById(PolEr).value="1";
           document.getElementById("bascet_erros").value++;
        }
      } else {
        if (document.getElementById(PolEr).value == "1"){
           document.getElementById(PolEr).value="0";
           document.getElementById("bascet_erros").value=document.getElementById("bascet_erros").value-1;
        }
      }
      setTimeout("bascetstat('"+ID+"','"+data+"','"+PolEr+"','"+reload+"')",500);
    } else {
    if (document.getElementById(PolEr)){
        if (document.getElementById(PolEr).value == "1"){
           document.getElementById(PolEr).value="0";
           document.getElementById("bascet_erros").value=document.getElementById("bascet_erros").value-1;
        }
     }
     setTimeout("bascetstat('"+ID+"','"+data+"','"+PolEr+"','"+reload+"')",500);
    }
    }
  }
}


function basceterror(){
  if (document.getElementById("bascet_erros").value=="0"){
    if (document.getElementById('bascet_pre')){
      document.getElementById('bascet_pre').className ="but_bascet";
    }
  } else {
    document.getElementById('bascet_pre').className ="but_bascet_ok";
  }
  setTimeout("basceterror()", 500);
}
/* Подмигивание закончилось */

function getAjax(){
  if (window.ActiveXObject) { // для IE
     return new ActiveXObject("Microsoft.XMLHTTP");
  } else if (window.XMLHttpRequest){
     return new XMLHttpRequest();
  } else {
     alert("Browser does not support AJAX.");
     return null;
    }
}
function getCookie(name) { // функция для считывания кукисов
    var prefix = name + "="
    var cookieStartIndex = document.cookie.indexOf(prefix)
    if (cookieStartIndex == -1)
            return null
    var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length)
    if (cookieEndIndex == -1)
            cookieEndIndex = document.cookie.length
    return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex))
}

// Отправляем заказ или выдаем ошибку.
function send_shop(){
  i=0;
	
  document.getElementById('wrapper').style.filter="alpha(opacity=50)";
  document.getElementById('wrapper').style.opacity="0.5";
  document.getElementById("bascet_load").innerHTML = "Идет обработка отправки корзины";
  document.getElementById('cards_add').style.display="block";

  document.getElementById('e_fio').innerHTML="";
  document.getElementById('e_email').innerHTML="";
  document.getElementById('e_tel').innerHTML="";

  if (document.getElementById('fio').value=="") 
  { 
	i++; 
	document.getElementById('e_fio').innerHTML ="Заполните поле: <b>Ф. И. О.</b>"; 
	}
  if (document.getElementById('email').value=="")
  { 
	i++; 
	document.getElementById('e_email').innerHTML ="Заполните поле: <b>E-mail</b>.";
	}
  if (document.getElementById('tel').value=="")
  { 
	i++; 
	document.getElementById('e_tel').innerHTML ="Заполните поле: <b>Телефон</b>.";}
 

	if (i>0) {
		setTimeout('showtext()', 100);
		return false;
	}
  
  
    setTimeout("send_order('')", 3000);
	
  //}
  //}
   setTimeout("showtime()", 3000);
  return false;
}


// Отправляем заказ
function send_order(USER_ID){
 
  if (USER_ID==""){
    USER_ID=0;//document.getElementById('show_user_item').value;
  }
   ajax=getAjax();
    if (ajax != null/* && USER_ID>0*/) {

if (document.getElementById('nkm')){
  nkm=document.getElementById('nkm').value;
} else {
  nkm=0;
}

expireAt = new Date;
expireAt.setMonth(expireAt.getMonth() + 3);

     document.cookie = "fio=" + encodeURIComponent(document.getElementById("fio").value) + "; path=/; expires=" + expireAt.toGMTString();
     document.cookie = "email=" + encodeURIComponent(document.getElementById("email").value) + "; path=/; expires=" + expireAt.toGMTString();
     document.cookie = "tel=" + encodeURIComponent(document.getElementById("tel").value) + "; path=/; expires=" + expireAt.toGMTString();
     document.cookie = "f_comments=" + encodeURIComponent(document.getElementById("f_comments").value) + "; path=/; expires=" + expireAt.toGMTString();
 
     ajax.open("post", "include/bascet.php?send=true&nkm="+nkm,true);
        ajax.send(null);
        ajax.onreadystatechange = function(){
        expireAt = new Date("01 January, 1970 00:00:01");
        document.cookie = "fio=0; path=/; expires="+expireAt.toGMTString();
        document.cookie = "email=0; path=/; expires="+expireAt.toGMTString();
        document.cookie = "tel=0; path=/; expires="+expireAt.toGMTString();
        document.cookie = "f_comments=0; path=/; expires="+expireAt.toGMTString();
       
        if (ajax.responseText=="true"){
          document.getElementById('bascet_show_tab').innerHTML= h1_header+"<p>Ваш заказ был успешно отправлен. В ближайшее время наш менеджер свяжется с Вами.</p>";
          
		  setTimeout("price_show('show_count_price')", 1000);
          setTimeout("showItemsCount('show_count_item')", 2000);
        } else {
          document.getElementById('bascet_show_tab').innerHTML= h1_header+"<p>При отправки заказа произошли следующие ошибки:<ul><li>Не получилось отправить письмо на ваш e-mail</li></ul></p>";
        }
		
      }
	  
    }
	//document.cookie = "pay=0; path=/; expires="+expireAt.toGMTString(); // обнуляем признак необходимости оплаты онлайн
}
// формируем запрос на оформление заказа и перенаправление пользователя на страницу он-лайн оплаты
function toPay(){
	document.getElementById('pay').value="true";	
	send_shop();
}
  function isValidEmail (email){
    return (/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test(email);
  }

// Очищаем корзину
function shop_clear(){
  if (confirm('Вы действительно хотите очистить вашу корзину товаров?')){
    ajax=getAjax();
    if (ajax != null) {
      ajax.open("GET", "include/bascet.php?bascet=clear",true);
      ajax.send(null);
      ajax.onreadystatechange = function(){
      }
    }

    setTimeout("price_show('show_count_price')", 1000);
    setTimeout("showItemsCount('show_count_item')", 2000);
    setTimeout("nowshow()", 3000);
    setTimeout("top.location.reload()", 3000);
  }

}


function elemiedit_replac(name){
  CID=str_replace('count[','',name);
  CID=str_replace('][','_',CID);
  CID=str_replace(']','',CID);
  return "item_"+CID;
}

function elemiinput_replac(name){
  CID=str_replace('count[','',name);
  CID=str_replace('][','_',CID);
  CID=str_replace(']','',CID);
  return "int_count"+CID;
}

function nowshow(){
    ajax=getAjax();
    if (ajax != null) {
      if (document.getElementById('nkm')){
        ajax.open("GET", "bascet.php?bascet=reload&nkm="+document.getElementById('nkm').value,true);
      } else {
        ajax.open("GET", "bascet.php?bascet=reload",true);
      }
      ajax.send(null);
      ajax.onreadystatechange = function(){
        document.getElementById('table_shop').innerHTML =ajax.responseText;
      }
    }
}

// Перерасчет всех товаров в корзине
function reload_shop(form){
  if (confirm('Вы действительно хотите перерасчитать весь товар в вашей корзине?')){
    var el,elName,value,type;
     document.getElementById('bascet_pred_data').value =Math.random();
	//alert(form.elements.length);
    for (var i = 0; i < form.elements.length; i++) {
      el = form.elements[i];
      elName = el.nodeName.toLowerCase();
      value = el.value;
	  //alert(el.name);
      if (elName == "input"){
        type = el.type.toLowerCase();
		
        switch (type) {
          case "text" :
            ajax=getAjax();
            if (ajax != null) {
                if (el.name != null){
                if (el.name != "nkm"){
                dataval=value;
                ajax.open("GET", "include/bascet.php?name="+el.name+"&value="+value+"&bascet=update",true);
                ajax.onreadystatechange = updatePage(el.name,value);
                ajax.send(null);
                ajax.onreadystatechange = function(){
                  elements=elemiinput_replac(el.name);
                  nameTD=elemiedit_replac(el.name);
                  if (document.getElementById(elements)){
                    if (document.getElementById(elements).value<1){
                      document.getElementById(nameTD).innerHTML = "";
                    } else {
                      document.getElementById(elements).value=document.getElementById(elements).value;
                    }
                  } else {
                    if (document.getElementById(nameTD)){
                      document.getElementById(nameTD).innerHTML = "";
                    }
                  }
                }
                }
              }
            }
          break;
          default :
          break;
        }
      }
    }
  }
  setTimeout("price_show('show_count_price')", 1000);
  setTimeout("showItemsCount('show_count_item')", 2000);
  setTimeout("nowshow()", 4000);
  setTimeout(function() {top.location.reload();}, 2000);
  return false;
}

function updatePage(ID,val) {
  document.getElementById('bascet_erros').value ="0";
  ids=str_replace('][','_',ID);
  ids=str_replace(']','',ids);
  ids=str_replace('[','',ids);
  ids=str_replace('count','',ids);
  document.getElementById('bascet_pre').className ="but_bascet";
  document.getElementById('bascet_reload').value =document.getElementById('bascet_pred_data').value;
 // alert('bascet_erros'+ids);
  bascetstatclear('bascet_erros'+ids);
  bascetstat('int_count'+ids,val,'bascet_erros'+ids,document.getElementById('bascet_pred_data').value);
}


// Удаление единичного товара из корзины
function shop_removed(ID){
    count_item=document.getElementById('table_count').value-1;
    ajax=getAjax();
    if (ajax != null) {
      ajax.open("GET", "include/bascet.php?id="+ID+"&bascet=removid",true);
      ajax.send(null);
      ajax.onreadystatechange = function(){
        if (count_item<1){
          top.location.reload();
          document.getElementById('table_shop').innerHTML = "<p>В вашей корзине еще нет товаров</p>";
        } else {
          document.getElementById('table_count').value=count_item;
          document.getElementById("item_"+ID+"_0").style.display="none";
          document.getElementById("item_"+ID+"_1").innerHTML = "";
          document.getElementById("item_"+ID+"_2").innerHTML = "";
          document.getElementById("item_"+ID+"_3").innerHTML = "";
          document.getElementById("item_"+ID+"_4").innerHTML = "";
          document.getElementById("item_"+ID+"_5").innerHTML = "";
          document.getElementById("item_"+ID+"_6").innerHTML = "";
        }
      }
    }
  setTimeout("price_show('show_count_price')", 3000);
  setTimeout("showItemsCount('show_count_item')", 4000);
  //setTimeout("price_show_end('price_show_end')", 2000);
  setTimeout(" top.location.reload()", 1000);
}

// Функция добавления товара в корзину
function cards_add(ID,color){
  var col_vo = document.getElementById('col_'+ID).value;

  if(col_vo == '')
  {
    alert('Укажите метраж');
  }
  else
  {
  textload='<img src="images/bascet-loader.gif" style="margin: 10px;" align="left" />Идет добавление товара в корзину';
  textokey='Товар добавлен в корзину';
  document.getElementById('wrapper').style.filter="alpha(opacity=50)";
  document.getElementById('wrapper').style.opacity="0.5";
//  document.getElementById('footer_id').style.opacity="alpha(opacity=50)";
//  document.getElementById('footer_id').style.filter="0.5";
  document.getElementById("bascet_load").innerHTML = textload;
  document.getElementById('cards_add').style.display="block";


    ajax=getAjax();
	
    if (ajax != null) {	
		ajax.open("GET", "include/bascet.php?id="+ID+"&color="+color+"&col="+col_vo,true);
		ajax.send(null);
		ajax.onreadystatechange = function(){
			if (ajax.readyState < 4)
			{
				document.getElementById("bascet_load").innerHTML = textload; 
			}
			else if(ajax.readyState==4)
			{
				document.getElementById("bascet_load").innerHTML = textokey;
				showtime();
			}
		}
	}
    setTimeout("price_show('show_count_price')", 3000);
    setTimeout("showItemsCount('show_count_item')", 4000);
	
    if ( document.location=="http://www.grand-parket.ru/bascet.php" ) {
        setTimeout(" top.location.reload()", 1000);
    }
  }
}

function price_show(ID){
  price=getAjax();
  if (price != null) {
    price.open("GET", "include/bascet.php?bascet=price&rnd="+Math.random(),true);
    price.send(null);
    price.onreadystatechange = function(){
     if(price.readyState==4){
        document.getElementById(ID).innerHTML=price.responseText+" руб.";
      }
    }
  }
}
function price_show_end(){
  price=getAjax();
    if (price != null) {
    price.open("GET", "include/bascet.php?bascet=price&rnd="+Math.random(),true);
    price.send(null);
    price.onreadystatechange = function(){
     if(price.readyState==4){
       show=getAjax();
        if (show != null) {
          show.open("GET", "include/bascet.php?send=rprice&price="+price.responseText,true);
          show.send(null);
          show.onreadystatechange = function(){
            if(show.readyState==4){
              document.getElementById("price_show_end").innerHTML=show.responseText;
            }
          }
        }
      }
    }
  }
}

function showItemsCount(ID){
  show=getAjax();
    if (show != null) {
    show.open("GET", "include/bascet.php?bascet=show&rnd="+Math.random(),true);
    show.send(null);
    show.onreadystatechange = function(){
     if(show.readyState==4){
        document.getElementById(ID).innerHTML=show.responseText+" шт.";
      }
    }
  }
}

// обновление цвета картинки
function preload_img(img,cod_id){
  document.getElementById('itemBlock').style.filter="alpha(opacity=30)";
  document.getElementById('itemBlock').style.opacity="0.3";
  oldcontent=document.getElementById('namecolor').title;
  newcontent=document.getElementById('color_name_'+cod_id).title;
  card_tit=str_replace(oldcontent,newcontent,document.getElementById('prod_image').title);
  card_new=str_replace(newcontent,oldcontent,document.getElementById('prod_image').title);
  document.getElementById('prod_image').title=card_tit;
  document.getElementById('prod_image').alt=card_tit;
  li_imgs= str_replace('big','small',document.getElementById('prod_image').src);
  li_imgs= str_replace('http://www.intim-country.ru/include/thumb.php?src=http://www.intim-country.ru/images/catalog/','/images/catalog/',li_imgs);
  li_imgs= str_replace('&w=180&h=180&far=1&bg=ffffff','',li_imgs);

  document.getElementById('link_s_'+cod_id).innerHTML='<a onclick="preload_img(\''+str_replace('/images/','images/',li_imgs)+'\',\''+cod_id+'\')" style="cursor:pointer;" target="_blank"><img alt="'+card_new+'" title="'+card_new+'" src="'+li_imgs+'" /></a>';

  img=str_replace('small','big',img);
  document.getElementById('link_image').href=img;
  document.getElementById('link_image_2').href=img;
  document.getElementById('prod_image').src='http://www.intim-country.ru/include/thumb.php?src=http://www.intim-country.ru/'+img+'&w=180&h=180&far=1&bg=ffffff';

  st_color=document.getElementById('namecolor').style.color;
  newcolor=document.getElementById('color_name_'+cod_id).style.color;
  document.getElementById('namecolor').style.color=newcolor;
  document.getElementById('color_name_'+cod_id).style.color=st_color;

  document.getElementById('namecolor').title=newcontent;
  document.getElementById('color_name_'+cod_id).title=oldcontent;
  document.getElementById('namecolor').innerHTML=newcontent;
  document.getElementById('color_name_'+cod_id).innerHTML='<b>'+oldcontent+'</b>';

  setTimeout('start_repload()', 4000);
}

function start_repload(){
  document.getElementById('itemBlock').style.filter="100";
  document.getElementById('itemBlock').style.opacity="100";
}

function str_replace(search, replace, subject) {
    return subject.split(search).join(replace);
}
// Обновление странички
function showtext(){
  document.getElementById('wrapper').style.filter="100";
  document.getElementById('wrapper').style.opacity="100";
//  document.getElementById('footer_id').style.filter="100";
//  document.getElementById('footer_id').style.opacity="100";
  document.getElementById('cards_add').style.display="none";
}
function showtime(){
  setTimeout('showtext()', 3000);
}



function preload_img2(id_pic){
 url=id_pic.replace('prev','big');
 document.getElementById('bigimgs').innerHTML="<a id='link_image' href='"+url+"' class='primg' target='_blank'><img height='180' id='prod_image' src='"+id_pic+"' alt='' title='' /></a>";
}
function mini_img(id_pic, not_pic){
document.getElementById('miniimgs').innerHTML="<table><tr>";
image=id_pic.split('|');
for(var i=0;i<image.length;i++){
if(image[i]!=not_pic){//delete image[i];
	document.getElementById('miniimgs').innerHTML+="<td><a id='img"+image[i]+"' onclick=\"mini_img('"+id_pic+"', '"+image[i]+"');preload_img3('"+id_pic+"','"+image[i]+"');\"><img height='100' id='prod_image' src='images/catalog/c_small_"+image[i]+".jpg' alt='' title='' style='margin:0 10px' /></a></td>";
}}
document.getElementById('miniimgs').innerHTML+="</tr></table>";
}
function preload_img3(id_pic, not_pic,color,code){
document.getElementById('namecolor').innerHTML=color;
document.getElementById('namecolor').style.color="#"+code+"";
document.getElementById('link_image'+not_pic+'').style.display='block';
image=id_pic.split('|');
for(var i=0;i<image.length;i++){
if(image[i]!=not_pic){
document.getElementById('link_image'+image[i]+'').style.display='none';
}}}


function mini_img2(id_pic, not_pic,color,code){
document.getElementById('ZoomImage').src="images/catalog/c_big_"+not_pic+".jpg";
document.getElementById('td'+not_pic+'').style.display='none';
image=id_pic.split('|');
color=color.split('|');
code=code.split('|');
for(var i=0;i<image.length;i++){
if(image[i]!=not_pic){
document.getElementById('color_name_'+image[i]+'').innerHTML='<b>'+color[i]+'</b>';
document.getElementById('color_name_'+image[i]+'').style.color="#"+code[i]+"";
document.getElementById('td'+image[i]+'').style.display='table-cell';
}}
}

