var date = new Date();
//date.setFullYear(date.getFullYear()+10);
//var expires=date.toGMTString();

date.setDate(date.getDate()+1);
var expires=date.toGMTString();


function setCookie(tovar_id, tovar_name, tovar_price, form_name) 
{
   	eval("var colvo = document." + form_name + ".colvo" + tovar_id + ".value");
   	
   	if(checkdigits(colvo) == false)
	{
		return false;
	}
		
	if(colvo == 0)
	{
		var text = 'Вы пытаетесь положить в корзину 0 товаров, что невозможно!';
		alert_window('dialog_message', 'dialog_message_text', '', text);
		
		return false;
	}
		
   	var all_price = tovar_price*colvo;
   	
   	all_price = okruglenie(all_price);
   	tovar_price = okruglenie(tovar_price);
   	
   	var oldCookie = getCookie();
	if(oldCookie == '') 
	{
		var curCookie = "report=" + tovar_id + "#"+ colvo +"::"+ tovar_price +"; path=/; expires=" + expires;
		document.cookie = curCookie;
		
		var text = 'Товар "'+ unescape(tovar_name) +'" в количестве '+ colvo +' шт. на сумму '+ all_price +' '+ valuta +' положен в корзину!';
		alert_window('dialog_message', 'dialog_message_text', '', text, '', {'0': {name: 'Продолжить выбор', action: ''}, '1': {name: 'Оформить заказ', action: 'open_link(\'/order.html\');'}}, {width: 400});
			
		document.basket.basket.value = colvo;
		document.basket.basketsumm.value = all_price;
		
		return;
	}
	
	
	var splitCookie = oldCookie.split(',');
	
	var add_colvo = "";
	
	for(var i=0; i<splitCookie.length; i++) 
	{
		var splitCookie_id = splitCookie[i].split('#');    
		
		if(splitCookie_id[0] == tovar_id) 
		{
			var splitCookie_id_col = splitCookie_id[1].split('::');
						
			var splitCookie_id_col_test = splitCookie_id_col[0]*1;
			
			splitCookie_id_col[0] = splitCookie_id_col[0]*1 + colvo*1;
			
			splitCookie_id[1] = splitCookie_id_col.join('::');
			splitCookie[i] = splitCookie_id.join('#');      				
			
			add_colvo = "yes";
			break;
		}
	}
	
	if(add_colvo == "")
	{
		splitCookie[splitCookie.length] = tovar_id + "#" + colvo + "::" + tovar_price;
	}
	
	var text = 'Товар "'+ unescape(tovar_name) +'" в количестве '+ colvo +' шт. на сумму '+ all_price +' '+ valuta +' положен в корзину!';
	alert_window('dialog_message', 'dialog_message_text', '', text, '', {'0': {name: 'Продолжить выбор', action: ''}, '1': {name: 'Оформить заказ', action: 'open_link(\'/order.html\');'}}, {width: 400});
		
	var newCookie = splitCookie.join(',');
	
	var curCookie = "report=" + escape(newCookie) + "; path=/; expires=" + expires;
	document.cookie = curCookie;
	
	var oldCookie = getCookie();
		
	basket_change(oldCookie);
}




function getCookie() 
{
	var prefix = "report=";
	var cookieStartIndex = document.cookie.indexOf(prefix);
	if (cookieStartIndex == -1)
               return "";
	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 checkdigits(colvo) 
{
   	if(!check_symbols_digits(colvo, "1#2#3#4#5#6#7#8#9#0"))
	{
  		alert('Количество введено неправильно!')
		//eval(item +".value = 1");
		return false;
	}
	else
	{
		if(colvo > 1000)
		{
			alert('Разрешается одновременно класть не более 1000 товаров!')
  			//eval(item +".value = 1000");
  			return false;
  		}
  		else
  		{
  			return true;
  		}
	}
}



function check_symbols_digits(input,elements)
{
	var elements = elements.split('#');  
		
   	var ok = false;
	   
	for (var i = 0; i < input.length; i++)
    {
    	var chr = input.charAt(i);
		   
		var found = false;
		   
		for (var j = 0; j < elements.length; j++)
        {
			if(chr == elements[j]){found = true; break;}else{found = false;}
		}
		   
		
		if(found)
		{
			ok = true;
		}
		else
		{
			return false
		};

	}
  	
	return ok;
}


function okruglenie(price)
{
	if(okruglenie_count > 0)
   	{
   		var okruglenie_koef = 10 ^ okruglenie_count;
   	
   		if(okruglenie_koef > 0)
	   	{
	   		price = Math.round(price*okruglenie_koef)/okruglenie_koef;
	
			var test = /\\./;
	
			if(!test.test(price))
			{
				var nulls = "";
				
				for(var i=0; i<okruglenie_count; i++)
				{
					nulls += '0';
				}
				
				price = price + '.' + nulls;
			}
	
			price = price + '';
			price = price.split('.');
    
			price_00 = price[1].split('');
	
			if(price_00.length < okruglenie_count)
			{
				var count_length = price_00.length;
				while(count_length < okruglenie_count)
				{
				 	price[1] = price[1] + '0';
					count_length++;
				}
			}
	
			price = price.join('.');
		}	
	}	

	return price; 
}



function basket_change(oldCookie)
{
	if(oldCookie != '') 
	{
	 	var basket = 0;
	 	var allbasketsumm = 0;
		var splitCookie = oldCookie.split(',');
		
		for(var i=0; i<splitCookie.length; i++) 
		{			
		 	var splitCookie_id = splitCookie[i].split('#');
		 	var splitCookie_id_col = splitCookie_id[1].split('::');
			
			basket = basket + splitCookie_id_col[0]*1;
			basketsumm = splitCookie_id_col[0]*splitCookie_id_col[1];	 		
			
			allbasketsumm = basketsumm + allbasketsumm;
		}
		
		allbasketsumm = okruglenie(allbasketsumm);
		
		document.basket.basket.value = basket;
		document.basket.basketsumm.value = allbasketsumm;
	}
	else
	{
		document.basket.basket.value = '0';
		document.basket.basketsumm.value = '0';
	}
}


/*
аналог alert() и confirm()
для использования требуется подключить модуль jquery-ui свойство dialog
*/
function alert_window(id, text_id, title, text, function_load_on_true, buttons, options)
{
	buttons = buttons || '';
		
	$('#'+ text_id).html(text);
	
	$('#'+ id).attr('class', '');
	
	if(title != '')
	{
		$('#'+ id).attr('title', title);
		$('#ui-dialog-title-'+ id).html(title);
	}	
	
	if(buttons == '')
	{    	
    	$('#'+ id).dialog({buttons: [
        	{
        		text: 'Ok',
        		click: function() {
        			$(this).dialog('close'); 
					
					if(function_load_on_true != '')
					{
						eval(function_load_on_true);
					}
       			}
       		}	
    	]}, {modal: true}, options);	
	}
	else
	{
		$('#'+ id).dialog({buttons: [
			{
        	 	text: buttons['0']['name'],
        		click: function() {
        			$(this).dialog('close'); 
					
					if(buttons['0']['action'] != '')
					{
						eval(buttons['0']['action']);
					}
       			}
    		},
    		{
        		text: buttons['1']['name'],
        		click: function() {
        			$(this).dialog('close'); 
					
					if(buttons['1']['action'] != '')
					{
						eval(buttons['1']['action']);
					}
       			}
    		}
   		]}, {modal: true}, options);	
	}
	
	return false;
}


/*
открытие ссылки через onclick с наличием http_refrer в IE
*/
function open_link(url, target, timeout)
{
	target = target || '';
	timeout = timeout || 1;
	
	setTimeout("open_link_func('"+ url +"', '"+ target +"')", timeout);	
}

function open_link_func(url, _target)
{ 
	_target = _target || '_self';
    	
	var fakeLink = document.createElement('a');

	if(typeof(fakeLink.click) == 'undefined')
	{
		if(_target == '_blank')
		{
			w_open(url, '', '', 'all_enable');	
		}
		else
		{
			window.location.href = url;
		}
	}
	else
	{
		fakeLink.target = _target;
		fakeLink.href = url;
		document.body.appendChild(fakeLink);
		fakeLink.click();
	}
} 


/* Открытие нового окна */
function w_open()
{
	var url = w_open.arguments[0];
	
	var w;
	var h;
	var settings;
	
	if(w_open.arguments[1]) 
	{
		w = w_open.arguments[1];
	} 
	else
	{
		w = screen.width - 100;
	} 
	
	if(w_open.arguments[2]) 
	{
		var h = w_open.arguments[2];
	} 
	else
	{
		h = screen.height - 200;
	}
	
	var wn = 'wname' + Math.round(Math.random() * 10000);
	
	if(w_open.arguments[3] == 'all_enable')
	{
		settings = 'toolbar=yes, location=yes, directories=yes, status=yes, menubar=yes, scrollbars=yes, resizable=yes, fullscreen=yes, target=_blank';	
	}
	else if(w_open.arguments[3])
	{
		settings = w_open.arguments[3];	
	}
	else
	{
		settings = 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, status=no, fullscreen=no, left=40, top=40, width='+w+',height='+h+', target=_blank';	
	}

	var openedWindow = window.open(url, wn, settings);

	if(openedWindow.opener == null) openedWindow.opener = self;
	openedWindow.focus();
}

