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(check_pwd)
	{

	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['login'].value != "" ){
			if (document.forms['fn'].elements['login'].value.search(/^[a-zA-Z0-9+_-]*$/) == -1) {
				error_msg = error_msg  + "Логин должен состоять только из латинских букв , цифр и символов\n";
				error = 1;
			}
		}*/

		if(check_pwd && 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)
{
    if (GetCookieValueByName('IT_USER')=='valera')
   var is_log=true;
  else
   var is_log=false;
    //price=price.toFixed(2); Из-за этой строки не отрабатывается нажатие ентера
	//alert('name: '+name+'  id: '+id+'  price: '+price+' quantity: '+quantity);
	var it_cart = GetCookieValueByName('it_cart');
	mult=document.forms['form_'+id]['must_be_num'].value;
  quantity=""+ceil(quantity, mult)
  var updated;
	while(1){

		if(!quantity)
 			return;

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

		if(!it_cart)
 			break;

		if(it_cart.search(new RegExp('(?:^|;)'+id+',\\d+,\\d+(?:\\.\\d+)?;'))!=-1)
    {
 			updateItemQuantity(id, quantity, price);
 			//if (is_log) alert('updated value'+GetCookieValueByName('it_cart'));
 			updated=1;
		}
		break;
	}
	
  if (!updated)
  {
  	//alert('name: '+name+'  id: '+id+'  price: '+price+' quantity: '+quantity);
  	var cookieValue = GetCookieValueByName('it_cart');
  	if (!cookieValue) { /*if (is_log) alert(cookieValue);*/ cookieValue='';};
  	SetCookieForNDays('it_cart',cookieValue + id + ',' + quantity + ',' + price + ';',1, '/');
	}
	document.getElementById('just_'+id).innerHTML=quantity;
	document.getElementById('pl_just_'+id).innerHTML=quantity;
	document.getElementById('pl_sum_'+id).innerHTML=quantity*price;	
 			//document.forms['form_'+id]['summ'].value=0;
     /* document.getElementById('cartnum').value=getAllQuantity();
      document.getElementById('totalprice').value=getAllSum();*/
	showCart();
  return;
}


function addItem2Cart2(name, id, price, quantity)
{
	
  price=price.toFixed(2);
	//alert('name: '+name+'  id: '+id+'  price: '+price);
	var it_cart = GetCookieValueByName('it_cart');
	mult=document.forms['pl_form_'+id]['must_be_num'].value;
  quantity=""+ceil(quantity, mult)
  var updated;
	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);
 			//alert('update');
 			updated=1;
		}
		break;
	}
  if (!updated)
	 SetCookieForNDays('it_cart',GetCookieValueByName('it_cart') + id + ',' + quantity + ',' + price + ';',1, '/');
	document.getElementById('just_'+id).innerHTML=quantity;
	document.getElementById('pl_just_'+id).innerHTML=quantity;
	document.getElementById('pl_sum_'+id).innerHTML=quantity*price;
	showCart();
  return;
}


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_()
{

	total_quantity=document.getElementById('total_quantity');
	total_cost=document.getElementById('total_cost');	
	div_cart=document.getElementById('cart');	
	/*if (!getTotalQuantity())
    div_cart.innerHTML='<div class="lt"></div>
                        <div class="lb"></div>
                        <div class="rt"></div>
                        <div class="rb"></div>
                        <div id="cart_title">Корзина товаров</div>
                        <table style="margin: 30px 0px 20px; font-size: 12px;" cellpadding="0" cellspacing="0" border="0"><tbody><tr><td colspan="2">Ничего не выбрано</td></tr></tbody></table>';
      */                  
}

function floatval(mixed_var) {	// +   original by: Michael White (http://crestidg.com)
	// %		note 1: The native parseFloat() method of JavaScript returns NaN when it encounters a string before an int or float value.

	return (parseFloat(mixed_var) || 0);
}


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


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

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

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


//Увеличивает 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';
 }

 function getBodyScrollTop()  
 {  
     return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);  
 }  
   
 
function show_detail(id, top)
{
  hide_detail();
  // создаешь див
  $('<div id="item_full" onclick="hide_detail(); return false;" style="top: '+getBodyScrollTop()+'"></div>').appendTo('body');
  // внутрь пихаешь ифрейм, либо загружаешь данные аяксом
  $('#item_full').load('/catalogue/detail/?item_id='+id);
   return false;
}

function hide_detail()
{
    $('#item_full').remove();
   return false; 
}


function showCart()
{
	var it_cart = GetCookieValueByName('it_cart');
	//alert(it_cart);
	var div_cart = document.getElementById('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 ='';

  
  var items_q=getTotalQuantity();
  //alert(items_q);
 // var tovars=spell_tovar(items_q);
  if (!items_q)
    div_cart.innerHTML = '<div class="lt"></div><div class="lb"></div><div class="rt"></div><div class="rb"></div><a href="/catalogue/cart/"><div id="cart_title">Корзина товаров</div></a><table style="margin: 30px 0px 20px; font-size: 12px;" cellpadding="0" cellspacing="0" border="0"><tbody><tr> <td colspan="2">Ничего не выбрано</td></tr></tbody></table>';
  else
    div_cart.innerHTML ='<div class="lt"></div><div class="lb"></div><div class="rt"></div><div class="rb"></div><table cellspacing="0" cellpadding="0" border="0" class="button_table"><tr><td class="button_left"></td><td class="button_center"><a style="color:#fff; text-decoration:none;" href="/catalogue/cart/">Корзина товаров</a></td><td class="button_right"></td></tr></table><table style="margin: 30px 0px 20px; font-size: 12px;" cellpadding="0" cellspacing="0" border="0"><tbody><tr> <td>Товаров в корзине:</td> <td style="padding-left: 11px;"><b id="total_quantity">'+items_q+' шт.</b></td></tr><tr> <td>Общая стоимость заказа:</td> <td style="padding-left: 11px;"><b id="total_cost">'+getTotalSum()+' р.</b></td></tr></tbody></table><table class="button_table" cellpadding="0" cellspacing="0" border="0"><tbody><tr> <td class="button_left"></td> <td class="button_center"><a style="color: rgb(255, 255, 255); text-decoration: none;" href="/catalogue/cart/sendcart.php">Оформить заказ</a></td> <td class="button_right"></td></tr></tbody><td class="button_left"></td> <td class="button_center"><a style="color: rgb(255, 255, 255); text-decoration: none;" href="/catalogue/cart/storecart.php">Отложить заказ</a></td> <td class="button_right"></td></table>';
  //<div style="color:#fff;" id="cart_title"></div>
}

function getTotalSum()
{
	var it_cart = GetCookieValueByName('it_cart');

	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;
	}

 	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]);
  }
  return price_sum.toFixed(2);
}


function getTotalQuantity()
{
	var it_cart = GetCookieValueByName('it_cart');

	var count_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;
	}

 	for(var i=0;i<real_items_q;i++)
  {
  	var item = items[i].split(',');
   	count_sum += parseInt(item[1]);
   	//item_sum += parseInt(item[1]);
  }
  return count_sum;
}


var resId=0;
var imgWndw;
function imgOpen(imgLink,Title) {
  if (typeof(window.resizeBy)=='undefined') return true;
  imgWndw=window.open('',imgLink.target,'width=100,height=100'+ ',toolbar=no,menubar=no,location=no,status=no,'+ 'resizable=yes,scrollbars=no,left='+(screen.width>>>2)+ ',top='+(screen.height>>>4));
  self.focus();
  var imgTitle=(Title)?Title:imgLink.href;
  with (imgWndw.document){
    open();
    write('<ht'+'ml><he'+'ad><ti'+'tle>'+imgTitle+'</ti'+'tle>'+ '</he'+'ad><bo'+'dy leftmargin="0" topmargin="0" '+ 'rightmargin="0" bottommargin="0" marginwidth="0" '+ 'style="margin:0;padding:0;position:fixed;overflow:none;" '+ 'marginheight="0"><img src="'+imgLink.href+'" border="0" '+ ' alt="'+imgTitle+'" title="'+imgTitle+'" class="r" /></bo'+ 'dy></ht'+'ml>');
    close();
  }
  resId=setInterval('imgResize()',100);
  return false
}

function imgResize() {
  var w=imgWndw.document.images[0].width;
  if (w>screen.availWidth) w=screen.availWidth;
  var h=imgWndw.document.images[0].height;
  if (h>screen.availHeight) h=screen.availHeight;
  if (w>50 && h>50) {
    var ww=(imgWndw.innerWidth)?imgWndw.innerWidth:((document.body)? imgWndw.document.body.clientWidth:null);
    var wh=(imgWndw.innerHeight)?imgWndw.innerHeight:((document.body)? imgWndw.document.body.clientHeight:null);
    if (ww && wh) { imgWndw.resizeBy(w-ww,h-wh); }
    imgWndw.focus();
    clearInterval(resId)
  }
}

