  //opens new window
	function open_window(link,w,h){
		var win = "width="+w+",height="+h+",menubar=no,location=no,resizable=yes,scrollbars=yes";
		newWin = window.open(link,'newWin',win);
		newWin.focus();
	}

  //unsubscription confirmation
	function confirmDelete() {
		temp = window.confirm('Удалить?');
		if (temp)	{
			window.location="index.php?killuser=yes";
		}
	}
	
  function trim(stringToTrim) {
  	return stringToTrim.replace(/^\s+|\s+$/g,"");
  }

  function ltrim(stringToTrim) {
  	return stringToTrim.replace(/^\s+/,"");
  }

  function rtrim(stringToTrim) {
  	return stringToTrim.replace(/\s+$/,"");
  }	
	
  //function validate_custinfo()
  //  synch. with OTHER_CUSTINFO.TPL.HTML and FUNCTIONS.JS 
  // direction_id      ->  direction_ru-РФ, Не Москва; direction_rum-РФ, Москва; direction_other-Не РФ  
  // payment_type_id ->  0-Не определен; 1-Курьер; 2-Самовывоз(Дом); 3-Почта/Предоплата; 4-Почта/Наложенный платеж; 5-Самовывоз(Китай-Город)   
	function validate_custinfo(direction_id, payment_type_id) {	
    var allSpacesRe = /\s+/g;
    //alert( 'direction_id: ' + direction_id + ', payment_type_id: '+payment_type_id);
  
    // email
    var email = document.custinfo_form.email.value.replace(allSpacesRe,"");
		if ( email =="" ){
			alert('Пожалуйста, укажите Ваш email');
			return false;
		} 
    else {
	    if (checkemail(email) == false){
  			alert('Пожалуйста, укажите правильно Ваш email. Имя email должно соответствовать шаблону, например: xxxxxx@yyyyyy.zzz');
  			return false;
      }
	  }

    // name
    var name0  = document.custinfo_form.first_name.value;
    name0 = rtrim(ltrim(name0));
    var name1  = name0.replace(allSpacesRe,"");
    if (name1 == ""){
      if (payment_type_id == 1 || payment_type_id == 2 || payment_type_id == 5){
			 alert('Пожалуйста, укажите Ваше Имя');
			}
      else if (payment_type_id == 3 || payment_type_id == 4){
			 alert('Пожалуйста, укажите Ваше Имя и Фамилию. Наличие Фамилии нужно для оформления почтового перевода');
			}
			return false;
		} 
    else {
      if( name1.length < 3){
			  alert('Пожалуйста, укажите правильно Ваши ФИО. Элементы имен не должны быть менее 3-х символов.');
			  return false;
			}
			if (payment_type_id == 3 || payment_type_id == 4){
			  var n = name0.indexOf(' '); 
			  if (n==-1){
          alert('Пожалуйста, укажите Ваше Имя и Фамилию, пример формата ввода: "Иван Иванов". (Наличие фамилии нужно для оформления почтового перевода EMS)');
          return false;
        }
			}
		}                                                   
		document.custinfo_form.first_name.value = name0;

    //phone
    var phone = document.custinfo_form.phone.value.replace(allSpacesRe,"");
		if (phone=="")		{
			alert('Пожалуйста, укажите Ваш телефон');
			return false;
		} else {
      if( phone.length < 3){
			  alert('Пожалуйста, укажите правильно Ваш телефон. Номер телефона не может быть менее 3-х символов.');
			  return false;
			}
		  /*
	    if (checkInternationalPhone(phone) == false){
  			alert('Пожалуйста, укажите правильно Ваш телефон. В номере телефона должны быть указаны код города или оператора,например: 095-3701111, 8-903-5557766');
  			return false;
      }
      */
	  }

    //zip  
	  var zip = document.getElementById('zip');
	  if (zip){
      var val = zip.value.replace(allSpacesRe,"");
  		if (val=="")		{
  			alert('Пожалуйста, укажите Ваш почтовый индекс');
  			return false;
  		} else {
  	    if (validateZIP(val) == false){
  			  alert('Пожалуйста, укажите правильно Ваш почтовый индекс. Почтовый индекс не должен быть менее 5-ти символов,например: 111539');
  			  return false;
  			}  
  		}
		}

    //city
    var city = document.getElementById('city');
	  if (city){
      var val  = city.value.replace(allSpacesRe,""); 
  		if (val == ""){
  			alert('Пожалуйста, укажите Ваш город');
  			return false;
  		} else {
        if( val.length < 3){
  			  alert('Пожалуйста, укажите правильно Ваш город. Имя города не должно быть менее 3-х символов.');
  			  return false;
  			}
        if (direction_id != 'direction_rum'){
  			  val = val.toUpperCase();
          if (val == "МОСКВА"){
    			  alert('Пожалуйста, укажите правильно Ваш город.\nВы выбирали регион доставки отличный от Москвы: \n"' + document.custinfo_form.direction_name.value + '"');
    			  return false;
  			  }
  			}
  		}
		}

    //state
    var state = document.getElementById('state');
	  if (state){
      var val = state.value.replace(allSpacesRe,"");  
  		if (val=="")	{
  			alert('Пожалуйста, укажите Вашу область');
  			return false;
  		}
  		else{
    		if (val.length < 3 )	{
  			  alert('Пожалуйста, укажите правильно Вашу область. Имя области не должно быть менее 3-х символов.');
  			  return false;
    		}
  		}
		}

    //street  
    var street = document.getElementById('street');
	  if (street){
      var val = street.value.replace(allSpacesRe,"");
  		if (val=="")	{
  			alert('Пожалуйста, укажите Вашу улицу');
  			return false;
  		}	else {
    		if (val.length < 3 )	{
  			  alert('Пожалуйста, укажите правильно Вашу улицу. Имя улицы не должно быть менее 3-х символов.');
  			  return false;
    		}
  		}
		}

    //house 
    var house = document.getElementById('house');
	  if (house){
      var val = house.value.replace(allSpacesRe,"");
  		if (val=="")	{
  			alert('Пожалуйста, укажите Ваш дом');
  			return false;
  		}	else{
    		if (val.length < 1 )	{
  			  alert('Пожалуйста, укажите правильно Ваш дом. Номер дома не должно быть менее 1-го символа.');
  			  return false;
    		}
  		}
		}

    //country
    /*
    var country = document.getElementById('country');
	  if (country){
      var val = country.value.replace(allSpacesRe,"");  
  		if (val=="")	{
  			alert('Пожалуйста, укажите Вашу страну');
  			return false;
  		}
		}
		*/

    //metro_na  
	  var metro_na = document.getElementById('metro_na');
	  if (metro_na){
      var val = metro_na.selectedIndex;
      //var val_label = metro_na.options[val].text.replace(allSpacesRe,"");
  		if ( val == 0 )		{
  			alert('Пожалуйста, укажите Вашу станцию метро');
  			return false;
  		} 
		}
		
    //metro_me  
	  var metro_me = document.getElementById('metro_me');
	  if (metro_me){
      var val = metro_me.selectedIndex;
      //var val_label = metro_me.options[val].text.replace(allSpacesRe,"");
  		if ( val == 0 )		{
  			alert('Пожалуйста, укажите метод передвижения от вашей станции метро до вашего дома');
  			return false;
  		} 
		}

    //metro_mi  
	  var metro_mi = document.getElementById('metro_mi');
	  if (metro_mi){
      var val = metro_mi.selectedIndex;
      //var val_label = metro_mi.options[val].text.replace(allSpacesRe,"");
  		if ( val == 0 )		{
  			alert('Пожалуйста, укажите кол-во минут в пути от вашей станции метро до вашего дома');
  			return false;
  		} 
		}

    //EMS
    var ems = document.getElementById('ems_summ');
	  if (ems){
      var val = ems.value.replace(allSpacesRe,"");  
  		if ( val == "" )	{
  			alert('Пожалуйста, воспользуйтесь калькулятором EMS');
  			return false;
  		}
      if( direction_id == "direction_ru" || direction_id == "direction_other" ){
        var ems_to = document.getElementById("ems_to");
        var ems_label = ems_to.options[ems_to.selectedIndex].text.replace(allSpacesRe,"");
        if( direction_id == "direction_ru" ){
      		var city_label  = city.value.replace(allSpacesRe,""); 
      		var state_label = state.value.replace(allSpacesRe,"");
          if( ems_label != city_label && ems_label != state_label ){
      			alert('Имя области или города доставки EMS не совпадает ни с одним из реквизитов адреса');
      			return false;
          }
        } 
        else if( direction_id == "direction_other" ){
          //var country = ems_label;
          var other = document.getElementById("other");
          var adr = other.value.replace(allSpacesRe,"");
          if( adr == ""){
      			alert('Укажите реквизиты адреса доставки в свободной форме.\n Можно воспользоваться сервисом поиска по карте Google для уточнения адреса.. ');
      			return false;
          }
        }
      }
		}
		return true;
	}
	
	function сheckMoscow() {
		if(document.custinfo_form.check_moscow.checked == true){
		  document.custinfo_form.city.value = "Москва";
		  document.custinfo_form.city.disabled = true;
    } 
    else{
		  document.custinfo_form.city.value = "";
		  document.custinfo_form.city.disabled = false;
    }
  }
	
  function checkemail(email){
    var filter = /^.+@.+\..{2,3}$/;
    if (filter.test(email)) {
      return true
    }   
    else {
      return false
    }
  }

  //phone verification	
  var digits = "0123456789";
  var phoneNumberDelimiters = "()- ";
  var validWorldPhoneChars = phoneNumberDelimiters + "+";
  var minDigitsInIPhoneNumber = 8;
  function isInteger(s){   
    var i;
    for (i = 0; i < s.length; i++) {   
      var c = s.charAt(i);
      if (((c < "0") || (c > "9"))) 
        return false;
    }
    return true;
  }
  function trim(s){   
    var i;
    var returnString = "";
    for (i = 0; i < s.length; i++) {   
      var c = s.charAt(i);
      if (c != " ") returnString += c;
    }
    return returnString;
  }
  function stripCharsInBag(s, bag){   
    var i;
    var returnString = "";
    for (i = 0; i < s.length; i++) {   
      var c = s.charAt(i);
      if (bag.indexOf(c) == -1) 
        returnString += c;
    }
    return returnString;
  }
  function checkInternationalPhone(strPhone){
    var bracket=3
    strPhone=trim(strPhone)
    if(strPhone.indexOf("+")>1) 
      return false
    if(strPhone.indexOf("-")!=-1)
      bracket=bracket+1
    if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)
      return false
    var brchr=strPhone.indexOf("(")
    if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+2)!=")")
      return false
    if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)
      return false
    s=stripCharsInBag(strPhone,validWorldPhoneChars);
    return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
  }
	
	//zip validation
  var minDigitsInZIPNumber = 5;
  function validateZIP(s) {
    return (isInteger(s) && s.length >= minDigitsInZIPNumber);
  }

  function changeBgImage (image, id) {
  	var button = document.getElementById(id);
  	button.style.backgroundImage = "url( "+image+")";
  }
  
  function changeAttr (flag,id) {
  	var b0 = document.getElementById(id);
 	  b0.style.backgroundImage = "url(images/button_"+flag+".png)";
 	  var b1 = b0.childNodes; 
 	  var b2 = b1[0].childNodes; 
  }
  
	function clear_custinfo(){
    document.custinfo_form.email.value = "";
    document.custinfo_form.first_name.value = "";
    document.custinfo_form.phone.value = "";
    try{document.custinfo_form.zip.value = "";}catch(err){}
    try{document.custinfo_form.city.value = ""; }catch(err){}
    try{document.custinfo_form.street.value = "";}catch(err){}
    try{document.custinfo_form.house.value = "";}catch(err){}
    try{document.custinfo_form.flate.value = "";}catch(err){}
    try{document.custinfo_form.day.value = "";}catch(err){}
    try{document.custinfo_form.time.value = "";}catch(err){}
    try{document.custinfo_form.state.value = "";}catch(err){}  
    try{document.custinfo_form.country.value = "";}catch(err){}  
    try{document.custinfo_form.ems_summ.value = "";}catch(err){}  
    try{document.custinfo_form.ems_days.value = "";}catch(err){}  
    try{document.custinfo_form.other.value = "";}catch(err){}  
  }

  // AJAX call ..


  function adm_order_update( in_id, in_val, in_field ) {
    document.body.style.cursor = 'wait';
    window.setTimeout(
      function(){ adm_order_update0( in_id, in_val, in_field ); },100);
  }

  function adm_order_update0( in_id, in_val, in_field )  {
    //alert( in_id + "," + in_val + "," + in_field );
    JsHttpRequest.query(
        'shopping_cart/adm_order_upd_ajax.php',
        { 'id'    : in_id, 
          'val'   : in_val, 
          'field' : in_field 
        },
        function(result, errors){
          if ( result["err"] != '' ){
            document.body.style.cursor = 'default';
            alert( result["err"] );
          } 
          else {
            document.body.style.cursor = 'default';
            alert( result["res"] );
          }
        },
        true  
    );
  }
  

  //--
  function pricelist(){
    cursor_wait();
    window.setTimeout(
      function(){pricelist0();},100);
  }

  function pricelist0(){
    document.getElementById("download_div").innerHTML = "";
    JsHttpRequest.query(
        'price_pdf/price_ajax.php', { },
        function(result, errors){
          var err = result["err"];
          if ( err != '' ){
            cursor_clear();
            alert(err);
          } 
          else {
           if ( result["filepdf"] != '' ){
             //alert( result["filepdf"] );
             cursor_clear();
             var sblank = '<acronym title="Скачать прайс-лист в формате PDF">'+
                             '<a href=\'http://www.dog-yarn.ru' + result["filepdf"] + '\'>'+
                                '<img src="images/Download.png">'+
                             '</a>' +  
                          '</acronym>';
             document.getElementById("download_div").innerHTML = sblank;
           } 
           else {
             cursor_clear();
           }
          }
        },
        true  
    );
  }

  //--

  function shopping_cart_check(pAhref){
    cursor_wait();
    window.setTimeout(
      function(){shopping_cart_check0(pAhref);},100);
  }

  function shopping_cart_check0(pAhref){
    JsHttpRequest.query(
        'shopping_cart/shopping_cart_ajax.php', { 'action' : 'check' },
        function(result, errors){
          var err = result["err"];
          if ( err != '' ){
            cursor_clear();
            alert(err);
          } 
          else {
           if ( result["shopping_cart_items"] != 0 ){
             location.href = pAhref;
             cursor_clear();
           } 
           else {
             cursor_clear();
             alert('Корзина пуста!');
           }
          }
        },
        true  
    );
  }

  function check_history_custinfo(save_address,customer_id){
    //alert( save_address + ', ' + customer_id );
    if ( save_address == 0 ){
      cursor_wait();
      setCookie("customer_id","","Mon, 01-Jan-2011 00:00:00 GMT");
      window.setTimeout(
        function(){clear_history_custinfo(save_address,customer_id);},100);
    } 
    else {
      setCookie("customer_id",customer_id,"Mon, 01-Jan-2011 00:00:00 GMT");
    }
  }
  
  function clear_history_custinfo(save_address,customer_id){
    JsHttpRequest.query(
        'shopping_cart/del_cookies_ajax.php', 
        { 'action' : 'del' },
        function(result, errors){
          cursor_clear();
        },
        true  
    );
  }

  function cart_product(in_productid,x,elementId,isShowCart)  {
    var val = null;
    if( x == 'clear' || x == 'add1' || x == 'del' )
      val = x;
    else{
      val = x;
      if( val == null ||
          val == "" || 
          isInteger(val) == false ||
          (isInteger(val) && val < 0 ) 
        ){
  			alert('Пожалуйста, укажите количество товара в корзине!\n\n( Количество товара должно быть больше или равно 0 )');
  			return false;
  		}	
    }    
    cursor_wait();
    var obj = document.getElementById("sinfo"); 
    obj.style.border = "yellow solid 2px";
    window.setTimeout(function(){cart_product0(in_productid,val,elementId,isShowCart);},10);
  }

  function cart_product0(in_productid,val,elementId,isShowCart)  {
    JsHttpRequest.query(
        'shopping_cart/shopping_cart_ajax.php',
        { 'productid': in_productid,
          'action'   : val 
        },
        function(result, errors){
          var err = result["err"];
          if ( err != '' ){
            cursor_clear();
            alert(err);
          } 
          else {
            document.getElementById("shopping_cart_items").innerHTML = result["shopping_cart_items"];
            document.getElementById("shopping_cart_value").innerHTML = result["shopping_cart_value"];
            try{
              var f = document.getElementById(elementId);
              var v = f.value;
              if (val == 'clear'){
                document.getElementById("shopping_cart_items").innerHTML = "0 шт.";
                document.getElementById("shopping_cart_value").innerHTML = "0 р.";
                f.value = 0;
              }
              else
                if( val != 'del')
                  f.value = result["shopping_cart_items_pid"];
            } 
            catch(e){
            }      
          }
          var obj = document.getElementById("sinfo"); 
          obj.style.border = "";
          cursor_clear();
          if( isShowCart==1 || isShowCart==2 ){
            if( isShowCart==2 ){
              top_max();
            }  
            top_content_div('maindiv_cart_step1_ajax.php');
          }  
        },
        true  
    );
  }
  
  function cart_product_1_deldiv(in_productid){
    var div0 = document.getElementById('div_'+in_productid);
    div0.style.visibility = "hidden";
  }

  function cart_product_1_adddiv(in_productid, in_cnt){
    var div0 = document.getElementById('div_'+in_productid);
    div0.style.visibility = "visible";
  }
  
  function customer_zip()  {
    var allSpacesRe = /\s+/g;
    var zip   = document.custinfo_form.zip.value.replace(allSpacesRe,"");
    //alert(zip);
		if (zip=="")		{
			alert('Пожалуйста, укажите Ваш почтовый индекс');
			return false;
		} 
    else {
	    if (validateZIP(zip) == false){
			  alert('Пожалуйста, укажите правильно Ваш почтовый индекс. Почтовый индекс не должен быть менее 5-ти символов,например: 111539');
			  return false;
			}  
		}
    cursor_wait();
    window.setTimeout(
      function(){customer_zip0(zip);},100);
    return false;
  }

  function customer_zip0(zip)  {
    JsHttpRequest.query(
        'shopping_cart/customer_zip_ajax.php', 
        { 'zip' : zip },
        function(result, errors){
          var err = result["err"];
          if ( err != '' ){
            cursor_clear();
            alert(err);
          } 
          else {
            //var s = 'Город: '+result["city"]+', Область: '+result["state"]+', EMS: '+result["ems_code"];
            //alert(s);
            document.custinfo_form.state.value = result["state"]; 
            document.custinfo_form.city.value = result["city"]; 
            document.custinfo_form.ems_summ.value = ""; 
            document.custinfo_form.ems_days.value = ""; 
            for (var i=0; i < document.custinfo_form.ems_to.length; i++) {
              if (document.custinfo_form.ems_to[i].value == result["ems_code"]) {
                document.custinfo_form.ems_to[i].selected = true;
              }
            }
            setMapLocations();
            cursor_clear();
          }
        },
        true  
    );
    return false;
  }

  function cursor_wait() {
    document.body.style.cursor = 'wait';
		document.getElementById("wait_div").style.visibility = "visible";
  }
  
  function cursor_clear() {
    document.body.style.cursor = 'default';
    document.getElementById("wait_div").style.visibility = "hidden";
  }

  function warn_color(idOb,color1,val,flag)  {
    var obj = document.getElementById(idOb);
    obj.value = val;
    var color0 = obj.style.backgroundColor;
    obj.style.backgroundColor = color1;
    if (flag==1){
      window.setTimeout(function(){back_color(idOb,color0,val);}, 1000);
    }
  }
  
  function back_color(idOb,color,val){
    var obj = document.getElementById(idOb);
    obj.style.backgroundColor = color;
  }

  function setMapLocations(){
    var sAddress = ""; 
    var f_state = document.getElementById('state');
	  if (f_state){
	   if( f_state.value != ""){
	     sAddress = sAddress + f_state.value + ','; 
     }
    }
    var f_city = document.getElementById('city');
	  if (f_city){
	   if( f_city.value != ""){
	     sAddress = sAddress + f_city.value + ','; 
     }
    }
    var f_street = document.getElementById('street');
	  if (f_street){
	   if( f_street.value != ""){
	     sAddress = sAddress + f_street.value + ','; 
     }
    }
    var f_house = document.getElementById('house');
	  if (f_house){
	   if( f_house.value != ""){
	     sAddress = sAddress + f_house.value + ','; 
     }
    }
    //alert(sAddress);
    cursor_wait();
    window.setTimeout(function(){setMapLocations0(sAddress);}, 100);
  }

  function setMapLocations0(sAddress){
    document.custinfo_form.q_a.value = sAddress;
    //showLocation(0);
    cursor_clear();   
  }

  function getLocations()  {
    //cursor_wait();
    //window.setTimeout(function(){getLocations0();}, 100);
  }

  function getLocations0(){
    JsHttpRequest.query(
        'shopping_cart/customer_address_ajax.php', 
        { 'customer_address' : 'customer_address' },
        function(result, errors){
          var err = result["err"];
          if ( err != '' ){
            //alert(err);
            document.custinfo_form.q_a.value = 'Россия, Москва';
            showLocation(0);
            cursor_clear();
          } 
          else{
            s = result["customer_address"]; 
            //alert( "address: " + s );
            document.custinfo_form.q_a.value = s;
            //function from ymapcoord.js
            showLocation(0);
            cursor_clear();   
          }
        },
        true  
    );
  }

  function ysetGeoInfo(idOb,val0,json_details)  {
    cursor_wait();
    window.setTimeout(function(){ysetGeoInfo0(idOb,val0,json_details);}, 100);
  }

  function ysetGeoInfo0(idOb,val0,json_details){
    //var val = val0.replace(/,/g,',\n');
    //alert(json_details);
    var val = val0;
    var obj = document.getElementById(idOb);
    obj.value = val;
    var color0 = obj.style.backgroundColor;
    obj.style.backgroundColor = "yellow";
    window.setTimeout(function(){back_color(idOb,color0,val);}, 1000);
    JsHttpRequest.query(
        'shopping_cart/address_ajax.php', 
        { 'address' : json_details },
        function(result, errors){
          var err = result["err"];
          if ( err != '' ){
            cursor_clear();
            alert(err);
          } 
          else{
            var f_state = document.getElementById('state');
        	  if (f_state){
              var g_state = result["state"]; 
              var g_substate = result["substate"];
              if( g_substate != ""){
                g_state = g_state + ',' + g_substate;
              } 
              f_state.value = g_state;
            }
            
            var f_city = document.getElementById('city');
        	  if (f_city){
        	    var g_city = result["city"];
              var g_subcity = result["subcity"];
              if( g_subcity != ""){
                g_city = g_city + ',' + g_subcity;
              } 
              f_city.value = g_city;
            }

            var f_street = document.getElementById('street');
        	  if (f_street){
        	    var g_street = result["street"];
              f_street.value = g_street;
            }

            var f_house = document.getElementById('house');
        	  if (f_house){
        	    var g_house = result["house"];
              f_house.value = g_house;
        	  }

            cursor_clear();
          }
        },
        true  
    );
  }

  function gsetGeoInfo(idOb,val0,g_country)  {
    cursor_wait();
    window.setTimeout(function(){gsetGeoInfo0(idOb,val0,g_country);}, 100);
  }

  function gsetGeoInfo0(idOb,val0,g_country){
    var val = val0;
    var obj = document.getElementById(idOb);
    obj.value = val;
    var color0 = obj.style.backgroundColor;
    obj.style.backgroundColor = "yellow";
    var f_country = document.getElementById('country');
	  if (f_country){
      f_country.value = g_country;
    }
    window.setTimeout(function(){back_color(idOb,color0,val);}, 1000);
    cursor_clear();
  }
  
  function price_ems(country)  {
    cursor_wait();
    window.setTimeout(function(){price_ems0(country);}, 100);
  }

  function price_ems0(country)  {
    // country: 0 - ru, 1 - others
    var ems_to = document.getElementById("ems_to");
    var ems_to_val = ems_to.options[ems_to.selectedIndex].value;
    var ems_to_name = ems_to.options[ems_to.selectedIndex].text;
    //alert(ems_to_val + ', ' + ems_to_name);
    warn_color('ems_summ','yellow','',0);
    if( country == 0 ){
      warn_color('ems_days','yellow','',0);
    }
    JsHttpRequest.query(
        'shopping_cart/price_ems_ajax.php', 
        { 'action' : 'price_ems', 
          'to_code' : ems_to_val,
          'to_name' : ems_to_name,
          'country' : country
        },
        function(result, errors){
          var err = result["err"];
          if ( err != '' ){
            warn_color('ems_summ','lightgray','-',0);
            if( country == 0 ){
              warn_color('ems_days','lightgray','-',0);
            }
            cursor_clear();
            alert(err);
          } 
          else {
            //alert(result["price"]);
            var s = '';
            if( country == 0 ){
              s = 
                'Место отправления  : Москва\n'+
                'Место доставки     : ' + ems_to_name + '\n' +
                'Стоимость доставки : ' + result["price"] + '\n' +
                'Срок доставки      : ' + result["time"] + '\n' +
                '---'+'\n'+
                'Использован калькулятор онлайн-сервиса EMS Почта России по запросу:'+'\n'+ 
                result["url"]+'\n';
            }  
            else if( country == 1 ){
              s = 
                'Место отправления  : Москва\n'+
                'Место доставки     : ' + ems_to_name + '\n' +
                'Стоимость доставки : ' + result["price"] + '\n' +
                '---'+'\n'+
                'Использован калькулятор онлайн-сервиса EMS Почта России по запросу:'+'\n'+ 
                result["url"]+'\n';
            }  
            cursor_clear();
            //alert(s);
            warn_color('ems_summ','lightgray',result["price"],0);
            if( country == 0 ){
              warn_color('ems_days','lightgray',result["time"],0);
            }
            if (ems_to_val.substr(0,4) == "city"){
              warn_color('city','yellow',ems_to_name,1);
            } 
            else {
              warn_color('state','yellow',ems_to_name,1);
            }
            cursor_clear();
            setMapLocations();
          }
        },
        true  
    );
    return false;
  }
  
  var top_h = 0;
  
  function top_max(){
    top_h = 1;
  }
  
  function top_min(){
    top_h = 0;
  }

  function top_content_div_h(flag){
    var h = $("#top_content_div").css("min-height"); 
    if( flag == 1 )
      h = $(window).height() - 80; 
    $("#top_content_div").height(h);
    top_h = 0;
  }
  
  function top_content_div(dname){
    cursor_wait();
    window.setTimeout(function(){top_content_div0(dname);},100);
  }
  function top_content_div0(dname){
    JsHttpRequest.query(
        dname,
        {},
        function(result, errors){
          //alert(dname);
          var err = result["err"];
          if ( err != '' ){
            cursor_clear();
            alert(err);
          } 
          else {
           if ( result["html"] != '' ){
             cursor_clear();
             document.getElementById("top_content_div").innerHTML = result["html"];
             top_content_div_h(top_h);
             //----------------
             try{
               obj = document.getElementById('script_js');
               if(obj){
                 var d = obj.getElementsByTagName("script");
                 var t = d.length;
                 for (var x=0; x<t; x++ ){
                   var s = document.createElement('script');
                   s.type = "text/javascript";
                   s.text = d[x].text;
                   s.charset = d[x].charset;
                   s.language = d[x].language;
                   s.src = d[x].src;
                   document.getElementById('script_js').appendChild (s);
                 }
               }
             }
             catch(e){
             } 
             //----------------
           } 
           else {
             cursor_clear();
           }
          }
        },
        true  
    );
  }

  function top_content_video_js(par1){
    cursor_wait();
    window.setTimeout(
      function(){top_content_video_js1(par1);},100);
  }
  function top_content_video_js1(par1){
    cursor_clear();
    var w = 500-60;
    var h = 375-60;
    var name = ' ';
    var site = 'http://www.dog-yarn.ru/webasyst/flv/';
    //var site = 'http://localhost/webasyst/flv/';
    //alert(site+par1);
    var html = 
     '<center>'+
		   '<div>'+
          '<video width='+w+' height='+h+' controls>'+
						 '<source src="'+site+par1+'.ogv" type="video/ogg">'+
						 '<source src="'+site+par1+'.mp4" type="video/mp4">'+
						 '<object type="application/x-shockwave-flash" data="'+site+'uflvplayer_500x375.swf" '+
				             'width="'+w+'" height="'+h+'"'+ '>' +
							 '<param name="bgcolor" value="#FFFFFF" />' +
               '<param name="wmode" value="opaque" />'+
							 '<param name="allowFullScreen" value="true" />' + 
							 '<param name="allowScriptAccess" value="always" />' + 
							 '<param name="movie" value="'+site+'uflvplayer_500x375.swf" />' +
							 '<param name="FlashVars" '+
								      'value="way='+site+par1+'.flv&amp;'+
								             'swf='+site+'uflvplayer_500x375.swf&amp;'+
								             //'w='+w+'&amp;h='+h+'&amp;'+
								             'pic='+site+'video.jpg&amp;autoplay=1&amp;'+
								             'tools=1&amp;skin=white&amp;volume=70&amp;q=&amp;comment=" />'+ 
							'</object>'
          '</video>'+
		    '</div>'+
      '</center>'
    ;
    document.getElementById("top_content_div").innerHTML = html;
    $("#top_content_div").height(h);
    //$("#top_content_div").width(w);
  }

  function top_content_div_1(dname,par1){
    cursor_wait();
    window.setTimeout(
      function(){top_content_div1(dname,par1);},100);
  }
  function top_content_div1(dname,par1){
    JsHttpRequest.query(
        dname,
        {'par1' : par1},
        function(result, errors){
          var err = result["err"];
          if ( err != '' ){
            cursor_clear();
            alert(err);
          } 
          else {
           if ( result["html"] != '' ){
             cursor_clear();
             document.getElementById("top_content_div").innerHTML = result["html"];
             top_content_div_h(top_h); 
           } 
           else {
             cursor_clear();
           }
          }
        },
        true  
    );
  }

  // use for only order_custinfo.tpl.html
  function top_content_div_2_cust(dname,payment_type_id,blank){
    cursor_wait();
    window.setTimeout(
      function(){top_content_div2cust(dname,payment_type_id,blank);},50);
  }
  function top_content_div2cust(dname,payment_type_id,blank){
    JsHttpRequest.query(
        dname,
        {'par1' : payment_type_id,
         'par2' : blank
        },
        function(result, errors){
          var err = result["err"];
          if ( err != '' ){
            cursor_clear();
            alert(err);
          } 
          else {
           if ( result["html"] != '' ){
             cursor_clear();
             var obj = null;
             try{
               document.getElementById("top_content_div").innerHTML = result["html"];
               top_content_div_h(top_h);
               //----------------
               obj = document.getElementById('mapmain');
               if(obj){
                 var d = obj.getElementsByTagName("script");
                 var t = d.length;
                 for (var x=0; x<t; x++ ){
                   var s = document.createElement('script');
                   s.type = "text/javascript";
                   s.text = d[x].text;
                   s.charset = d[x].charset;
                   s.language = d[x].language;
                   s.src = d[x].src;
                   //alert(s.src);
                   document.getElementById('mapmain').appendChild (s);
                 }
               } 
               //----------------
             }
             catch(e){
               alert('top_content_div_2_cust err: '+ e.name);
             }
           } 
           else {
             cursor_clear();
           }
          }
        },
        true  
    );
  }

  function tag_content_div(dname){
    cursor_wait();
    window.setTimeout(function(){tag_content_div0(dname);},100);
  }
  function tag_content_div0(dname){
    JsHttpRequest.query(
        dname,
        {},
        function(result, errors){
          var err = result["err"];
          if ( err != '' ){
            cursor_clear();
            alert(err);
          } 
          else {
           if ( result["html"] != '' ){
             cursor_clear();
             document.getElementById("top_content_div").innerHTML = result["html"];
             top_content_div_h(top_h);
             //----------------
             obj = document.getElementById('tags');
             if(obj){
               var d = obj.getElementsByTagName("script");
               var t = d.length;
               for (var x=0; x<t; x++ ){
                 var s = document.createElement('script');
                 s.type = "text/javascript";
                 s.text = d[x].text;
                 s.charset = d[x].charset;
                 s.language = d[x].language;
                 s.src = d[x].src;
                 //alert(s.src);
                 document.getElementById('tags').appendChild (s);
               }
             } 
             //----------------
           } 
           else {
             cursor_clear();
           }
          }
        },
        true  
    );
  }

  function top_content_shop_ok(dname,save_address){
    cursor_wait();
    window.setTimeout(
      function(){top_content_shop_ok1(dname,save_address);},100);
  }
  function top_content_shop_ok1(dname,save_address){
    JsHttpRequest.query(
        dname,
        {"par1" : save_address},
        function(result, errors){
          var err = result["err"];
          if ( err != '' ){
            cursor_clear();
            alert(err);
          } 
          else {
           if ( result["html"] != '' ){
             cursor_clear();
             try{
               document.getElementById("top_content_div").innerHTML = result["html"];
               top_content_div_h(top_h);
               var d = document.getElementById('onload').getElementsByTagName("script");
               var t = d.length;
               for (var x=0; x<t; x++ ){
                 var s = document.createElement('script');
                 s.type = "text/javascript";
                 s.text = d[x].text;
                 document.getElementById('onload').appendChild (s); 
               } 
             }
             catch(e){
               alert(e.name);
             }
           } 
           else {
             cursor_clear();
           }
          }
        },
        true  
    );
  }
  
  function popup_content_div(dname){
    cursor_wait();
    window.setTimeout(
      function(){popup_content_div0(dname);},50);
  }
  function popup_content_div0(dname){
    JsHttpRequest.query(
        dname,
        {},
        function(result, errors){
          var err = result["err"];
          if ( err != '' ){
            cursor_clear();
            alert(err);
          } 
          else {
           if ( result["html"] != '' ){
             cursor_clear();
             popup_win( result["html"] ); 
           } 
           else {
             cursor_clear();
           }
          }
        },
        true  
    );
  }
  function popup_win(html){
    openwindow=window.open("", "ShopDogYarn","height=500,width=400,toolbar=no,resizable=yes,scrollbars=yes,menubar=no");
    openwindow.document.write("<html>");
    openwindow.document.write("<title>Условия</title>");
    //openwindow.document.write("<style type=\"text/css\">");
    //openwindow.document.write("  body {background-image:url(images/pattern4.jpg)}");
    //openwindow.document.write("</style>");
    openwindow.document.write("<body style=\"background-image:url(images/pattern4.jpg)\">");
    openwindow.document.write(html);
    openwindow.document.write("</body>");
    openwindow.document.write("</html>");
    openwindow.document.close();  
  }

  function main_content_div(dname){
    cursor_wait();
    window.setTimeout(
      function(){main_content_div0(dname);},100);
  }
  function main_content_div0(dname){
    JsHttpRequest.query(
        dname,
        {},
        function(result, errors){
          var err = result["err"];
          if ( err != '' ){
            cursor_clear();
            alert(err);
          } 
          else {
           if ( result["html"] != '' ){
             cursor_clear();
             document.getElementById("main_content_div").innerHTML = result["html"]; 
           } 
           else {
             cursor_clear();
           }
          }
        },
        true  
    );
  }

  function main_content_div_1(dname,par1){
    cursor_wait();
    window.setTimeout(
      function(){main_content_div1(dname,par1);},100);
  }
  function main_content_div1(dname,par1){
    JsHttpRequest.query(
        dname,
        {'par1' : par1},
        function(result, errors){
          var err = result["err"];
          if ( err != '' ){
            cursor_clear();
            alert(err);
          } 
          else {
           if ( result["html"] != '' ){
             cursor_clear();
             document.getElementById("main_content_div").innerHTML = result["html"]; 
           } 
           else {
             cursor_clear();
           }
          }
        },
        true  
    );
  }
  
  function js_search_catalog(dname,val,e){
    var keycode;
    if (window.event) 
      keycode = window.event.keyCode;
    else 
      if (e) keycode = e.which; else return true;
    if (keycode == 13) {
      js_search_catalog1(dname,val);
      return false;
    }
    else
      return true;
  }  

  function js_search_catalog1(dname,val){
    var allSpacesRe = /\s+/g;
    if (val == ""){
      alert('Критерий поиска не указан!');
      return false;
    }
    val = val.replace(allSpacesRe,"");
    if (val == ""){
      alert('Критерий поиска не указан!');
      return false;
    }
    top_content_div_1(dname,val);
  }

  // use for only order_place.tpl.html
  function main_content_shop_ok(dname,save_address){
    cursor_wait();
    window.setTimeout(
      function(){main_content_shop_ok1(dname,save_address);},100);
  }
  function main_content_shop_ok1(dname,save_address){
    JsHttpRequest.query(
        dname,
        {"par1" : save_address},
        function(result, errors){
          var err = result["err"];
          if ( err != '' ){
            cursor_clear();
            alert(err);
          } 
          else {
           if ( result["html"] != '' ){
             cursor_clear();
             try{
               document.getElementById("main_content_div").innerHTML = result["html"];
               var d = document.getElementById('onload').getElementsByTagName("script");
               var t = d.length;
               for (var x=0; x<t; x++ ){
                 var s = document.createElement('script');
                 s.type = "text/javascript";
                 s.text = d[x].text;
                 document.getElementById('onload').appendChild (s); 
               } 
             }
             catch(e){
               alert(e.name);
             }
           } 
           else {

             cursor_clear();
           }
          }
        },
        true  
    );
  }

  function js_order_key_info_k(myfield,e){
    var keycode;
    if (window.event) 
      keycode = window.event.keyCode;
    else 
      if (e) keycode = e.which;
      else 
        return true;
    if (keycode == 13) {
      js_order_key_info(myfield.value);
      return false;
    }
    else
       return true;
  }  
  
  function js_order_key_info(key){
    //alert(key);
    var allSpacesRe = /\s+/g;
    if (key == ""){
      alert('Код не указан!');
      return false;
    }
    key = key.replace(allSpacesRe,"");
    if (key == ""){
      alert('Код не указан!');
      return false;
    }
    cursor_wait();
    window.setTimeout(
      function(){js_order_key_info0(key);},100);
  }
  function js_order_key_info0(key)  {
    JsHttpRequest.query(
        'maindiv_orderkey_ajax.php',
        { 'order_key' : key },
        function(result, errors){
          var err = result["err"];
          if ( err != '' ){
            cursor_clear();
            alert(err);
          } 
          else{
            cursor_clear();
            document.getElementById("search_status_form").innerHTML = result["html"];
            return false;
          }
        },
        true  
    );
    return false;
  }

  //--
  function catprod_info(key){
    cursor_wait();
    window.setTimeout(
      function(){catprod_info0(key);},100);
  }
  function catprod_info0(key)  {
    JsHttpRequest.query(
        'maindiv_catprod_ajax.php',
        { 'key' : key },
        function(result, errors){
          var err = result["err"];
          if ( err != '' ){
            cursor_clear();
            alert(err);
          } 
          else{
            cursor_clear();
            catprod_out(key,result["html"]);
          }
        },
        true  
    );
    return true;
  }
  
  function catprod_out(key,res){
    //alert(key+', '+res)
    var div = "top_content_div"; 
    var n = key.search('product');
    if(n != -1){
      div = "main_content_div";
      top_content_div_h(0);
    }  
    document.getElementById(div).innerHTML = res;  
    try{
      obj = document.getElementById('script_js');
      if(obj){
        var n = 0;
        var link = obj.getElementsByTagName("link");
        if(link){
          n = link.length; 
          for (var x=0; x<n; x++ ){
            var li = document.createElement('link');
            li.rel   = "stylesheet";
            li.type  = "text/css";
            li.href  = link[x].href;
            document.getElementById('script_js').appendChild(li);
          }  
        }
        var script = obj.getElementsByTagName("script");
        if(script){
          n = script.length;
          for (var x=0; x<n; x++ ){
            var s   = document.createElement('script');
            s.type  = "text/javascript";
            s.text  = script[x].text;
            s.charset  = script[x].charset;
            s.language = script[x].language;
            s.src   = script[x].src;
            document.getElementById('script_js').appendChild (s);
          }
        }
      }
    }
    catch(e){
    } 
  }

  function payment_type_change(ptid){
    var ptid_name = '';
    var obj  = document.getElementById('payment_type_head');
    var obj3 = document.getElementById('payment_type_id3');
    var obj4 = document.getElementById('payment_type_id4');
    if (ptid==3){
      obj3.checked = true;
      obj4.checked = false;
      ptid_name = obj3.value; 
    }
    else if (ptid==4){
      obj4.checked = true;
      obj3.checked = false; 
      ptid_name = obj4.value; 
    }
    obj.value = ptid_name;
    //alert(ptid+', '+ptid_name);
    JsHttpRequest.query(
        'shopping_cart/price_ems_ajax.php', 
        { 'action'            : 'payment_change',
          'payment_type_id'   : ptid, 
          'payment_type_name' : ptid_name 
        },
        function(result, errors){
          var err = result["err"];
          if ( err != '' ){
            alert(err);
          } 
        },
        true  
    );
  }
  
  //output money comma
  function outputMoney(number,sym) {
    return outputDollars(Math.floor(number-0) + '') + outputCents(number - 0) + sym;
  }
  function outputDollars(number) {
    if (number.length <= 3)
        return (number == '' ? '0' : number);
    else {
        var mod = number.length%3;
        var output = (mod == 0 ? '' : (number.substring(0,mod)));
        for (i=0 ; i < Math.floor(number.length/3) ; i++) {
            if ((mod ==0) && (i ==0))
                output+= number.substring(mod+3*i,mod+3*i+3);
            else
                output+= '\'' + number.substring(mod+3*i,mod+3*i+3);
        }
        return (output);
    }
  } 
  function outputCents(amount) {
    amount = Math.round( ( (amount) - Math.floor(amount) ) *100);
    return (amount < 10 ? '.0' + amount : '.' + amount);
  }
  
  var idelivery = 0;
  function ddelivery(){
      var obj = document.getElementById("ddelivery");
      if(idelivery==0) 
        obj.style.border = "yellow solid 3px";
      idelivery++;
      if(idelivery==2){
        obj.style.border = "red solid 3px";
        idelivery = 0;
      }
  }

  function shop_ok(){
    if (document.order_mail.shop_delivery.checked != true){ 
      window.setInterval("ddelivery()",500);
      /*
      var myInterval = 
        window.setInterval(
          function (obj) {
            obj.style.border = "yellow solid 2px";
          },1000
        );
      window.setTimeout(
        function (obj) {
          clearInterval(myInterval);
          obj.style.border = "";
        },3500
      );
      */
      alert('Пожалуйста, подтвердите согласие с условиями магазина.');
      return false;
    }   
    else  
      return true;
  }

  function history_prev_cart(){
    //alert('prev: '+window.history.previous);
  }

  //javascrip:setCookie('test0','test00','Mon, 01-Jan-2011 00:00:00 GMT');
  function setCookie (name, value, expires) {
    document.cookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires : "")
    ;
    //alert('Save cookies: '+name+' -> '+value);
  }
  
  // onLoad="javascript:alert( getCookie('customer_id') )  
  function getCookie(name) {
  	var cookie = " " + document.cookie;
  	var search = " " + name + "=";
  	var setStr = null;
  	var offset = 0;
  	var end = 0;
  	if (cookie.length > 0) {
  		offset = cookie.indexOf(search);
  		if (offset != -1) {
  			offset += search.length;
  			end = cookie.indexOf(";", offset)
  			if (end == -1) {
  				end = cookie.length;
  			}
  			setStr = unescape(cookie.substring(offset, end));
  		}
  	}
  	return(setStr);
  }
  
  //--  Jquery use
  $(document).ready(function(){  
    $('[rel=tooltip]').bind('mouseover', function(){ 
      // переменной themessage приравниваем значения поля content
      var theMessage = $(this).attr('content');
      //themessage выводим между тегами div с классом tootltip
      $('<DIV class="tooltip">' + theMessage + '</DIV>').appendTo('body').fadeIn('fast');
      //функция определяет положение мыши и переносит за ним подскаску
      $(this).bind('mousemove', function(e){ 
  			$('div.tooltip').css({
  				'top': e.pageY - ($('div.tooltip').height())-10,
  				'left': e.pageX + 25
  			});
  		});
  		//функция убирает подсказку если мышка не на объекте
  	}).bind('mouseout', function(){ 
  		$('div.tooltip').fadeOut('fast', function(){
  			$(this).remove();
  		});
  	});
  });
  
  $(document).ready(function(){  
    $('[rel=tooltip_var]').bind('mouseover', function(){ 
      var theMessage = $(this).attr('content');
      $('<DIV width='+theMessage.length+' class="tooltip_var">' + theMessage + '</DIV>').appendTo('body').fadeIn('fast');
      $(this).bind('mousemove', function(e){ 
  			$('div.tooltip_var').css({
  				'top': e.pageY - ($('div.tooltip_var').height())-10,
  				'left': e.pageX + 25
  			});
  		});
  	}).bind('mouseout', function(){ 
  		$('div.tooltip_var').fadeOut('fast', function(){
  			$(this).remove();
  		});
  	});
  });



      

