function amz_js_PopWin(url,name,options){
	var ContextWindow = window.open(url,name,options);
	ContextWindow.opener = this;
	ContextWindow.focus();
}

var couldProcess = false;

    function makeRequest(url, params) {

        var http_request = false;

        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                http_request.overrideMimeType('text/xml');
                // See note below about this line
            }
        } else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!http_request) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
        http_request.onreadystatechange = function() { alertContents(http_request); };
        http_request.open('POST', url, true);
		http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http_request.setRequestHeader("Content-length", params.length);
		http_request.setRequestHeader("Connection", "close");
        http_request.send(params);

    }

    function alertContents(http_request) {

        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
                //alert(http_request.responseText);
                eval(http_request.responseText);
            } else {
                alert('There was a problem with the request.');
            }
        }
    }


	function add_to_cart(form_id) {

		var form_elements_object = document.forms[form_id].elements;
		var params_str = "";

		for ( var i=0, j=form_elements_object.length; i < j; ++i ) {
			//alert(form_elements_object[i].name);
			params_str += form_elements_object[i].name + '=' + form_elements_object[i].value + '&';
		}

		params_str += 'ajax=1';

		//alert(params_str);
		var url = 'search_catalogue/additem.php';

		//var url = 'http://www.rdcards.ru/test.php';
		//document.forms['search'].elements['p5']

		makeRequest(url,params_str);
	}


// PrintVar(document.getElementById['elem']);
function PrintVar (obj){
	var i, str;
	str = '<pre>';

	for(i in obj){
		str += '\n' + i + ' = ' + obj[i];
	}

	str += '</pre>';

	document.write(str);
}



function GoReg()
	{

	var error_msg = "ОШИБКА! \n\n";
	var error = 0;

		if( document.forms['fn'].elements['login'].value == "" ){
			error_msg = error_msg  + "Введите Логин \n";
			error = 1;
		}

		if( document.forms['fn'].elements['pwd'].value == "" ){
			error_msg = error_msg +  "Введите Пароль \n";
			error = 1;
		}



		if( document.forms['fn'].elements['surname'].value == "" ){
			error_msg = error_msg + "Введите Фамилию \n";
			error = 1;
		}

		if( document.forms['fn'].elements['name'].value == "" ){
			error_msg = error_msg +  "Введите Имя \n";
			error = 1;
		}

		if( document.forms['fn'].elements['city'].value == "" ){
			error_msg = error_msg + "Введите название Вашего населённого пункта \n";
			error = 1;
		}

		if( document.forms['fn'].elements['country'].value == "" ){
			error_msg = error_msg + "Введите Вашу страну \n";
			error = 1;
		}

		if( document.forms['fn'].elements['email'].value == "" ){
			error_msg = error_msg + "Введите Ваш e-mail \n";
			error = 1;
		}


		if( document.forms['fn'].elements['org'].value == "" ){
			error_msg = error_msg + "Введите название организации на которую будут оформляться заказы \n";
			error = 1;
		}

		if( document.forms['fn'].elements['phone'].value == "" ){
			error_msg = error_msg + "Введите контактный телефон \n";
			error = 1;
		}

		if( document.forms['fn'].elements['pwd'].value != document.forms['fn'].elements['pwd2'].value ){
			error_msg = error_msg +  "Подтверждение пароля не соответствует \n";
			error = 1;
		}

		error_msg = error_msg + "\n\n";

		if(error != 1){
		  document.forms['fn'].submit();
		}

		if(error == 1){
			alert(error_msg);
		}
	}

function GoReg2()
	{alert('Есть');}



function GoLog()
	{

	var error_msg = "ОШИБКА! \n\n";
	var error = 0;

		if( document.forms['login'].elements['id'].value == "" ){
			error_msg = error_msg + "Введите Логин \n";
			error = 1;
		}

		if( document.forms['login'].elements['pwd'].value == "" ){
			error_msg = error_msg +  "Введите Пароль \n";
			error = 1;
		}

		error_msg = error_msg + "\n\n";

		if(error != 1){
			document.forms['login'].submit();
		}

		if(error == 1){
			alert(error_msg);
		}
	}


  //////////////////
	//Корзина
	//////////////////
function minus_(id)
{
  var x=document.forms['form_i']['num_'+id].value;
  var y=document.getElementById('mult_'+id).innerHTML;
  y=parseInt(y);
  if (x - y >0)
  {
    new_qal=x - y;
    var price=parseInt(document.getElementById('price_'+id).innerHTML);
    updateItemQuantity(id, new_qal+"", price+"");
    document.forms['form_i']['num_'+id].value = new_qal;
    document.forms['form_i']['sum_'+id].value=new_qal*price;
    document.getElementById('totalprice').value=getAllSum();
  }
  else
  alert("ОШИБКА! \n\nДопустимы только цифры \nЧисла должны быть положительными \n\n");

}

function plus_(id)
{
  var x=document.forms['form_i']['num_'+id].value;
  x=parseInt(x);
  var y=document.getElementById('mult_'+id).innerHTML;
  y=parseInt(y);
  new_qal=x + y;
  var price=parseInt(document.getElementById('price_'+id).innerHTML);
  updateItemQuantity(id, new_qal+"", price+"");
  document.forms['form_i']['num_'+id].value = new_qal;
  document.forms['form_i']['sum_'+id].value=new_qal*price;
  document.getElementById('totalprice').value=getAllSum();
}


function GetCookieValueByName(name){
	var beg = document.cookie.indexOf(name+"=");
	if(beg==-1)
		return false;

	var end = document.cookie.indexOf(";", beg + name.length);
	if(end==-1)
		end = document.cookie.length;
  //alert("qw"+document.cookie.substring(beg + name.length + 1, end));
	return unescape(document.cookie.substring(beg + name.length + 1, end));
}

function SetCookieForNDays(name, value, days, path, domain, secure){
	//alert(value);
	var today = new Date();
	expires = new Date(today.getTime() + days*24*60*60*1000);
	document.cookie = name + "=" + escape(value) +
                "; expires=" + expires.toGMTString() +
                ((path) ? "; path=" + path : "") +
                ((domain) ? "; domain=" + domain : "") +
                ((secure) ? "; secure" : "");

}


function getAllQuantity()
{
  var quant=0;
	var it_cart = GetCookieValueByName('it_cart');
	while (it_cart.length>0)
  {
     //alert(it_cart);
     item_str=it_cart.match(new RegExp('(?:^|;)\\d+,\\d+,\\d+(?:\\.\\d+)?;'));
     it_cart=it_cart.replace(item_str[0],'');
  	 var item = item_str[0].split(',');
  	 //alert("Текущее кол-во: "+item[1]);
  	 quant += parseInt(item[1]);
  }
  return quant;
}

function getAllSum()
{
  var sum=0;
	var it_cart = GetCookieValueByName('it_cart');
	while (it_cart.length>0)
  {
     //alert(it_cart);
     item_str=it_cart.match(new RegExp('(?:^|;)\\d+,\\d+,\\d+(?:\\.\\d+)?;'));
     it_cart=it_cart.replace(item_str[0],'');
  	 var item = item_str[0].split(',');
  	 //alert("Текущее кол-во: "+item[1]);
  	 sum += parseInt(item[1])*parseFloat(item[2]);
  }
  return sum;
  //alert(sum);
}


function addItem2Cart(name, id, price, quantity)
{
  price=price.toFixed(2);
	//alert('name: '+name+'  id: '+id+'  price: '+price);
	var it_cart = GetCookieValueByName('it_cart');
	mult=document.forms['form_'+id]['must_be_num'].value;
  quantity=""+ceil(quantity, mult)
	while(1){

		if(!quantity)
 			return;

		if(quantity.search(/^\d+$/)){
   		alert('Некорректный ввод.');
   		continue;
 		}

		if(!it_cart)
 			break;

		if(it_cart.search(new RegExp('(?:^|;)'+id+',\\d+,\\d+(?:\\.\\d+)?;'))!=-1)
    {
 			updateItemQuantity(id, quantity, price);
 			document.forms['form_'+id]['already'].value=quantity;
 			document.forms['form_'+id]['summ'].value=0;
      document.getElementById('cartnum').value=getAllQuantity();
      document.getElementById('totalprice').value=getAllSum();
 			return;
		}

		break;
	}

	SetCookieForNDays('it_cart',GetCookieValueByName('it_cart') + id + ',' + quantity + ',' + price + ';',1, '/');
	document.forms['form_'+id]['already'].value=quantity;
	document.forms['form_'+id]['summ'].value=0;
  document.getElementById('cartnum').value=getAllQuantity();
  document.getElementById('totalprice').value=getAllSum();
	showCart();
}


function delItemFromCart(id)
{
	var it_cart = GetCookieValueByName('it_cart');
	it_cart = it_cart.replace(new RegExp('(^|;)'+id+',\\d+,\\d+(?:\\.\\d+)?;'),'$1');
	SetCookieForNDays('it_cart',it_cart,1, '/');
	showCart();
}

function updateItemQuantity(id, quantity, price){
	var it_cart = GetCookieValueByName('it_cart');
	var item_str = it_cart.match(new RegExp('(?:^|;)'+id+',\\d+,\\d+(?:\\.\\d+)?;'));
	var item = item_str[0].split(',');

	while(item && item.length){
  	//quantity = prompt('Данный элемент уже присутствует в корзине в количестве ' + item[1] + 'шт. Уточните новое количество элементов в корзине.',quantity);

  	if(!quantity)
   		return;

  	if(quantity.search(/^\d+$/)){
   		alert('Некорректный ввод.');
   		continue;
  	}
 		break;
 	}

	it_cart = it_cart.replace(new RegExp('(^|;)'+id+',\\d+,\\d+(?:\\.\\d+)?;'), '$1' + id + ',' + quantity + ',' + price + ';');
	SetCookieForNDays('it_cart',it_cart,1, '/');
	showCart();
}

function showCart(){
	var it_cart = GetCookieValueByName('it_cart');
	//alert(it_cart);
	var div_cart = document.getElementById('div_cart');
	if(!div_cart){
  	//alert('Where is my cart?');
  	return;
 	}
	var price_sum=0;
	var item_sum=new Number(0);
	var items;
	var real_items_q=new Number(0);

	if(it_cart){
 		items = it_cart.split(';');
 		real_items_q = items.length ? items.length-1 : 0;
	}

	div_cart.innerHTML ='';

 	for(var i=0;i<real_items_q;i++){
  	var item = items[i].split(',');
   	price_sum += item[1]*item[2];
   	item_sum += parseInt(item[1]);
   	//div_cart.innerHTML += item[0] +' '+ item[1] +' '+ item[2]
   	//+ '<a href=# onclick="updateItemQuantity('+item[0]+','+item[1]+','+item[2]+')">U</a> '
   	//+ '<a href=# onclick="delItemFromCart('+item[0]+')">D</a>' + '<br>';
  }

	div_cart.innerHTML += 'В корзине позиций ' + item_sum + ' шт.';

	if(item_sum!=0){
		if(price_sum)
		div_cart.innerHTML += ' на сумму ' + price_sum.toFixed(2);
		if(window.location.href.indexOf("/catalogue/cart/")==-1)
		div_cart.innerHTML += '<br><a href=/catalogue/cart/><b>Оформить заказ</b></a>';
	}
}

function getItemQuantity(id){
	var it_cart = GetCookieValueByName('it_cart');
	var item_str = it_cart.match(new RegExp('(?:^|;)'+id+',\\d+,\\d+(?:\\.\\d+)?;'));
	var item = item_str[0].split(',');
	return item[1];
}


function getItemSum(id){
	var it_cart = GetCookieValueByName('it_cart');
	var item_str = it_cart.match(new RegExp('(?:^|;)'+id+',\\d+,\\d+(?:\\.\\d+)?;'));
	var item = item_str[0].split(',');
	return item[2];
}

function printItemSum(id){
	var it_cart = GetCookieValueByName('it_cart');
	var item_str = it_cart.match(new RegExp('(?:^|;)'+id+',\\d+,\\d+(?:\\.\\d+)?'));
	var item = item_str[0].split(',');
	var item_sum=new Number(item[1]*item[2]);
	document.write(item_sum.toFixed(2));
}

function printItemQuantity(id)
{
	var it_cart = GetCookieValueByName('it_cart');
	var item_str = it_cart.match(new RegExp('(?:^|;)'+id+',\\d+,\\d+(?:\\.\\d+)?;'));
	var item = item_str[0].split(',');
	document.write(item[1]);
}


//Увеличивает i, чтобы стало кратным mult
function ceil(i, mult)
{
  n=(i-i%mult)/mult;
  if (i%mult)
    n++;
  return n*mult;
}

function formatAsMoney(mnt) {
    mnt -= 0;
    mnt = (Math.round(mnt*100))/100;
    return (mnt == Math.floor(mnt)) ? mnt + '.00'
              : ( (mnt*10 == Math.floor(mnt*10)) ?
                       mnt + '0' : mnt);
}

function GoGo(form_id)
	{

	var item_val = document.forms[form_id].elements['num'].value
	var item_price = document.forms[form_id].elements['price'].value


		if( (item_val < 0) || (isNaN(item_val)) ){

			alert("ОШИБКА! \n\nДопустимы только цифры \nЧисла должны быть положительными \n\n");
			document.forms[form_id].elements['num'].value = '';
			return false;
		}

		if( (item_price <= 0) || (isNaN(item_price)) ){

			alert("ОШИБКА! \n\nЦена не задана для этой открытки. Вы можете купить этот товар, но цены Вам будет нужно уточнить у нас (после оформления заказа наш менеджер свяжется с Вами и назовет цену на заказанный Вами товар). \n\n");
			return false;
		}

		document.forms[form_id].elements['summ'].value = formatAsMoney(item_val * item_price);

	}


//Функция для вывода картинки в новом окне
function OpenImagePopup(imgPath, title, alt) {
    var win = window.open('','preview',
    'width=50,height=50,left=0,top=0,screenX=0,screenY=0,resizable=1,scrollbar=0,status=0');

    var winDoc = win.document;
    if (title == undefined) title = 'My Image, Click to Close';
    if (alt   == undefined) alt   = 'My Image, Click to Close';
    var content = '<html><head><title>' + title + '</title>' +
    			  '<style>body{overflow: hidden;margin:0;}img{border:0;}</style>' +
    			  '</head><body><a href="javascript:self.close()">' +
    			  '<img alt="' + alt + '" id="image" src="' + imgPath + '" /></a></body></html>'
    win.document.write(content);

    winDoc.body.onload = function() {
    	var obj = winDoc.getElementById('image');
    	var w = obj.width, h = obj.height;
    	var iHeight= document.body.clientHeight, iWidth = self.innerWidth;

    	var left = (self.opera ? iWidth : screen.availWidth)/2 - w/2;
    	var top =  (self.opera ? iHeight : screen.availHeight)/2 - h/2;
    	win.resizeTo(w+10, h+26);
    	win.moveTo(left, top);
    }

    win.onload = winDoc.body.onload; // special for Mozilla

    // !!! Important statement: popup onload won't execute without it!
    win.document.close();
    win.focus();
}

 
 function hide_id(id)
 {
  ob=document.getElementById(id);
  if (ob.style.display=='none')
    ob.style.display='block';
  else
    ob.style.display='none';
 }
 