
var arr = new Object();
var a;

var request;

function empty(){
}

function CheckCartEmpty(){
	var amount = 0;
	for (company_id in arr){
		for (product_id in arr[company_id]){
			amount = arr[company_id][product_id][1]; // amount			
		}
	}

	if(amount==0){
		alert("Вы не можете оформить заказ, т.к. Ваша корзина пуста!");
		return true;
	}else{
		return false;
	}
}

function CartUpdate(){
	var params = '';
	for (company_id in arr){
		for (product_id in arr[company_id]){
			amount = arr[company_id][product_id][1]; // amount
			params += 'cart[' + company_id + '][' + product_id + '][amount]=' + amount + '&';
			params += 'cart[' + company_id + '][' + product_id + '][comments]=' + escape(document.getElementById('good_comments_' + product_id).value) + '&';
			
		}
	}
	
	//customer
	params += 'customer[fio]=' + escape(document.getElementById('fio').value)+'&';
	params += 'customer[address]=' + escape(document.getElementById('address').value)+'&';
	params += 'customer[email]=' + escape(document.getElementById('email').value)+'&';
	params += 'customer[phone]=' + escape(document.getElementById('phone').value)+'&';
	params += 'customer[fax]=' + escape(document.getElementById('fax').value)+'&';

	params += 'customer[url]=' + escape(document.getElementById('url').value)+'&';
	params += 'customer[rasch_schet]=' + escape(document.getElementById('rasch_schet').value)+'&';
	params += 'customer[kor_schet]=' + escape(document.getElementById('kor_schet').value)+'&';
	params += 'customer[bank]=' + escape(document.getElementById('bank').value)+'&';
	params += 'customer[inn]=' + escape(document.getElementById('inn').value)+'&';
	params += 'customer[kpp]=' + escape(document.getElementById('kpp').value)+'&';
	params += 'customer[bik]=' + escape(document.getElementById('bik').value)+'&';

	params += 'customer[comments]=' + escape(document.getElementById('comments').value)+'&';

	doLoad('/minicart.php?' + params + 'action=cart_update', processRequestChange);
}

function HideEmptyCompany(company_id){
	var amount = 0;
	for (mykey in arr[company_id]){
		amount += parseInt(arr[company_id][mykey][1]);
	}
	
	if(amount == 0){
		document.getElementById('tr_empty_company_' + company_id).style.display = 'none';
		document.getElementById('tr_sum_company_' + company_id).style.display = 'none';
		document.getElementById('tr_company_' + company_id).style.display = 'none';
	}
}

function SetNumbers(company_id){
	var i = 1;
	for (product_id in arr[company_id]){
		if(document.getElementById('tr_' + product_id).style.display == 'none'){
		}else{
			document.getElementById('num_' + product_id).innerHTML = i;
			i++;
		}
	}
}

function DelProduct(product_id, company_id){
	document.getElementById('tr_' + product_id).style.display = 'none';
	document.getElementById('good_amount_' + product_id).value = '0';
	calc_cost(product_id, company_id);
	HideEmptyCompany(company_id);
	SetNumbers(company_id);
}

////////////////////////////////////////////////////////////////////////
function checkEmailAddress(field) {
var err = false;
var res, x;
	if (!field)
		return true;

	if (field.value.length == 0) {
		err = true;
	}

	var arrEmail = field.value.replace(/^\s+/, '').replace(/\s+$/, '').split('@');
	if (arrEmail.length != 2 || arrEmail[0].length < 1)
		err = true;
	if (!err) {
		if (arrEmail[0].length > 2)
			res = arrEmail[0].search(/^[-\w][-\.\w]+[-\w]$/gi);
		else
			res = arrEmail[0].search(/^[-\w]+$/gi);
		if (res == -1)
			err = true;
	}
	if (!err) {
		var arr2Email = arrEmail[1].split('.');
		if (arr2Email.length < 2)
			err = true;
	}
	if (!err) {
		var domenTail = arr2Email[arr2Email.length-1];
		var _arr2Email = new Array();
		for (x = 0; x < arr2Email.length-1; x++)
			_arr2Email[x] = arr2Email[x];
		arr2Email = _arr2Email;
		var domen = arr2Email.join('.');
		res = domen.search(/^[-!#\$%&*+\\\/=?\.\w^`{|}~]+$/gi);
		if (res == -1)
			err = true;
		res = domenTail.search(/^[a-zA-Z]+$/gi);
		if (res == -1 || domenTail.length < 2 || domenTail.length > 6)
			err = true;
	}
//	/^([-\w][-\.\w]*)?[-\w]@([-!#\$%&*+\\\/=?\w^`{|}~]+\.)+[a-zA-Z]{2,6}$/gi

	if (err) {
		alert('Поле E-mail заполнено не верно!');
		field.focus();
		field.select();
	}
	return !err;
}

function ValidateCartForm(){
	if(document.getElementById('fio').value.length==0 ){
		alert('Поле ФИО/Организация заполнено не верно!');
		document.getElementById('fio').focus();
		document.getElementById('fio').select();
		return false;
	}

	if(document.getElementById('address').value.length==0 ){
		alert('Поле Адрес заполнено не верно!');
		document.getElementById('address').focus();
		document.getElementById('address').select();
		return false;
	}

	if(document.getElementById('email').value.length != 0){
		if( !checkEmailAddress(document.getElementById('email')) ){
			return false;
		}
	}

	if( (document.getElementById('email').value.length == 0) && (document.getElementById('phone').value.length == 0) ){
		alert('Необходимо заполнить либо E-mail, либо Телефон!');
		document.getElementById('email').focus();
		document.getElementById('email').select();
		return false;
	}

	return true;
}

////////////////////////////////////////////////////////////////////////

function calc_cost(good_id, company_id){
	var amount = parseInt(document.getElementById('good_amount_' + good_id).value);
	if(amount < 0){
		amount = 0;
		document.getElementById('good_amount_' + good_id).value = '0';
	}
	if(isNaN(amount)){
		amount = 0;
	}
//	alert(amount);
	arr[company_id][good_id][1] = amount;
	var mykey;
	var company_amount = 0;
	var company_sum = 0;
	for (mykey in arr[company_id]){
		company_amount += parseInt(arr[company_id][mykey][1]);
		company_sum += parseInt(arr[company_id][mykey][1])*parseFloat(arr[company_id][mykey][2]);
	}
	document.getElementById('company_amount_' + company_id).innerHTML = '<b>' + company_amount + '</b>';
	document.getElementById('company_sum_' + company_id).innerHTML = '<b>' + company_sum + '</b>';
	document.getElementById('product_full_price_' + good_id).innerHTML = '' + parseInt(arr[company_id][good_id][1])*parseFloat(arr[company_id][good_id][2]);

	var all_amount = 0;
	var all_sum = 0;
	for (company_id in arr){
		for (mykey in arr[company_id]){
			all_amount += parseInt(arr[company_id][mykey][1]);
			all_sum += parseInt(arr[company_id][mykey][1])*parseFloat(arr[company_id][mykey][2]);
		}
	}
	document.getElementById('all_amount').innerHTML = '<b>' + all_amount + '</b>';
	document.getElementById('all_sum').innerHTML = '<b>' + all_sum + '</b>';
	
}

function doLoad(url, func) {
	var i = url.indexOf('?');
	if(i!=-1){
		var url_ = url.substr(0, i);
		var params = url.substr(i+1, url.length-i);
	}
	if (window.XMLHttpRequest) {
		if(i!=-1){
			url = url_;
		}
		request = new XMLHttpRequest();
		request.onreadystatechange = func;
		if(i!=-1){
			request.open("POST", url, true);
			request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			request.setRequestHeader("Content-length", params.length);
			request.setRequestHeader("Connection", "close");
		}else{
			request.open("GET", url, true);
		}
		request.send(params);
	} else if (window.ActiveXObject) {
		request = new ActiveXObject("Microsoft.XMLHTTP");
		if (request) {
			request.onreadystatechange = func;
			request.open("POST", url, true);
			request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			request.send(); 
		}
	}
}

function getRequestStateText(code) {
	switch (code) {
		case 0: return "Uninitialized."; break;
		case 1: return "Loading..."; break;
		case 2: return "Loaded."; break;
		case 3: return "Interactive..."; break;
		case 4: return "Complete."; break;
	}
}

function processRequestChange() {
//	alert(11111);
	abortRequest = window.setTimeout("request.abort();", 10000000);
	// если выполнен
	if (request.readyState == 4) {
		clearTimeout(abortRequest);
		// если успешно
		if (request.status == 200) {
			var text = request.responseText;
			document.getElementById("minicart").innerHTML = text;
			var b = text.indexOf('<script');
			if(b != -1){
				b = text.indexOf('>', b)+1;
				var e = text.indexOf('</script>')-1;
				var s = text.substr(b, e - b + 1);
				eval(s);
			}
		} else {
			alert("Ошибка при добавлении в корзину");
		}  
		//document.getElementById("loading").style.display = 'none';  
	}  
	// иначе, если идет загрузка или в процессе - показываем слой "Загружаются данные"  
	else if (request.readyState == 3 || request.readyState == 1) {  
		//document.getElementById("loading").style.display = 'block';  
	}
//	alert(1);
}


function AddProductFormContent(id) {
	text =	'<form action="" method="POST">' +
				'<input type="hidden" name="id" id="add_product_id" value="'+id+'">' +
				'Количество:<br><input type="text" name="amount" id="add_product_amount" value="1" style="width: 100%;">' +
				'Комментарии к покупке:<br><textarea rows="3" style="width: 100%;" name="comments" id="add_product_comments"></textarea><br><br>' +
				'<input type="button" value="Добавить в корзину" onClick="Dialog.closeInfo();AddProductSave();">' +
				'<input type="button" value="Отменить" onClick="Dialog.closeInfo();">' +
			'</form>';
return text;
}


function SubmitCartData() {
	alert('shneck');
return true;
}

function AddProductSave(){
	doLoad('/minicart.php?id='+document.getElementById('add_product_id').value+'&amount='+document.getElementById('add_product_amount').value+'&comments='+escape(document.getElementById('add_product_comments').value), processRequestChange);
//	alert(1);
//	document.getElementById('add_product_form').style.display = 'none';
	Dialog.closeInfo();
return false;
}