﻿function nodeChildEnableDisable(node, sEnable, sDisable)
{
	var children = new Object();
	var i = new Number();
	var nodename = new String();
	children = node.childNodes;
	for(var i = 0; i < children.length; i++)
		if(children[i].nodeType == 1){ // 1 = Node.ELEMENT_NODE
			//oDebug.innerHTML += children[i].nodeName + ' ' + children[i].nodeName.toLowerCase().indexOf(sEnable.toLowerCase()) + '<br />';
			//oDebug.innerHTML += children[i].nodeName + ' ' + children[i].nodeName.toLowerCase().indexOf(sDisable.toLowerCase()) + '<br />';
			nodename = children[i].nodeName.toLowerCase();
			if(nodename.indexOf(sEnable.toLowerCase()) != -1){
				children[i].className = '';
				var oReturn = new Object(children[i]);
			}
			if(nodename.indexOf(sDisable.toLowerCase()) != -1)
				children[i].className = 'hidden';
		}
	return oReturn;
}

function getBasketSum()
{
	var oSum = document.getElementById("basket_sum");
	var sum = new Number;
	var c = new Number;
	var ids = Array();
	//oDebug.innerHTML = '';
	for(i = 0; i < oForm.length; i++){
		chk = oForm.elements[i].name;
		if(chk.indexOf("item") != -1){
			matches = chk.match(/item\[([0-9]*)\]/i);
			if(oForm.elements[i].checked && oForm.elements[i].style.display != 'none'){
				//oDebug.innerHTML += '[' + oForm.elements[i].style.display + ']&#160;';
				//oDebug.innerHTML += '&#160;-&#160;' + matches[1] + '&#160;' + document.getElementById('price[' + matches[1] + ']').value + '<br />';
				sum += Number(document.getElementById('price[' + matches[1] + ']').value) * Number(document.getElementById('count[' + matches[1] + ']').value);
				document.getElementById('product_' + matches[1]).className = "product";
				c++;
				ids.push(Number(matches[1]));
			} else {
				if(!oForm.elements[i].checked)
					document.getElementById('product_' + matches[1]).className = "product unchecked";
			}
		}
	}
	oSum.innerHTML = (c > 0?(c == 1?'Выбрана <b>' + c + '</b> позиция':((c >= 2 && c <= 4)?'Выбраны <b>' + c + '</b> позиции':'Выбрано <b>' + c + '</b> позиций'))+ ' на сумму <b>' + sum + '</b>&#160;' + document.getElementById('cur_name').value:'Ничего не выбрано');
}

function add2basket(config)
{
	if(typeof config != 'object') return false;
	var id = config.id;
	var oBtn = config.oBtn;
	var sn = config.sn;
	var shuttle_id = config.shuttle_id;
	var preview = config.preview;
	
	var conf = Conf.getConf(id);
	
	a = new sendBox(oBtn, document.getElementById('just_added_img'), preview, showJustAddedImg);
	nodeChildEnableDisable(oBtn, 'img', 'div');
	oBtn.disabled = 'disabled';
	var request = new httpRequest();
	var func = function(){
		var xmldoc = request.responseText;
		oBtn.disabled = '';
		Ys.lightMsg.msg('Отлично', 'Товар добавлен в корзину');
		show_basket(id, sn, oBtn, (sn != undefined && sn != ''?true:false), xmldoc, preview);
	}
	makeRequest(
		request,
		func,
		'/basket/add2basket/',
		'POST',
		//'JsHttpRequest={"id":' + id.toJSONString() + ((!Ext.isEmpty(conf))?',"conf":'+conf:'') + (sn !== undefined && sn != ''?',"sn":"'+sn+'"':'') + (shuttle_id !== undefined && shuttle_id != ''?',"shuttle_id":"'+shuttle_id+'"':'') +'}'
		'JsHttpRequest={"id":'
			+ Ext.encode(id) + ((!Ext.isEmpty(conf))?',"conf":'+conf:'') + (sn !== undefined && sn != ''?',"sn":"'+sn+'"':'') + (shuttle_id !== undefined && shuttle_id != ''?',"shuttle_id":"'+shuttle_id+'"':'') +'}'
	);
}

function show_basket(id, sn, oBtn, disable_btn, response,preview){
	if(sn === undefined) sn = 0;
	if(disable_btn === undefined) disable_btn = false;
	var vars = Ext.decode(response);
	if(vars.unical_id !== undefined && vars.unical_id != '') unical_id = vars.unical_id;
	if(oBasket) oBasket.innerHTML = "";
	if(oBasketShuttle) oBasketShuttle.innerHTML = "";
	if(oBasketComiss)	oBasketComiss.innerHTML = "";
	var sum = 0;
	var c = 0;
	var cache, cur_name;
	//Basket
	if(vars.basket.length > 0 && oBasket){
		for(var i in vars.basket){			
			cache = vars.basket[i];
			if(typeof(cache) == 'object' && cache.name_id){
				cur_name = cache.cur_name;
				c++;
				if(!sn && id == cache.name_id){//just added
					oBasketLast.innerHTML = "<div id=\"just_added\" class=\"item added\"><a href=\"/catalog/" + cache.name_id + "/\">"+ cache.name + "</a>&#160;x&#160;" + cache.count + "</div>";
					oBasketLast.style.display = '';
					//vars.basket[i]='';
				}else{
					oBasket.innerHTML += "<div class=\"item\"><a href=\"/catalog/" + cache.name_id + "/\">"+ cache.name + "</a>&#160;x&#160;" + cache.count + "</div>";
				}
				sum += Number(cache.price) * Number(cache.count);
			}
		}
	}

	//basket conf
	if(vars.basket_conf.length > 0){
		for(var i in vars.basket_conf){			
			cache = vars.basket_conf[i];
			if(typeof(cache) == 'object' && cache.name_id){
				cur_name = cache.cur_name;
				c++;
				if(!sn && id == cache.name_id){//just added
					oBasketLast.innerHTML = "<div id=\"just_added\" class=\"item added\"><a href=\"/catalog/" + cache.name_id + "/\">"+ cache.name + "</a>&#160;x&#160;" + cache.count + "</div>";
					oBasketLast.style.display = '';
					//vars.basket[i]='';
				}else{
					oBasket.innerHTML += "<div class=\"item\"><a href=\"/catalog/" + cache.name_id + "/\">"+ cache.name + "</a>&#160;x&#160;" + cache.count + "</div>";
				}
				sum += (Number(cache.conf_summ) + Number(cache.price)) * Number(cache.count);
			}
		}
	}
	
	//comiss
	if(vars.comiss.length > 0){		
		var ci = 0;
		for(var i in vars.comiss){
			cache = vars.comiss[i];
			if(typeof(cache) == 'object' && cache.name_id){
				cur_name = cache.cur_name;
				c++;
				if(sn == cache.sn && id == cache.name_id){
					oBasketLast.innerHTML = "</div><div id=\"just_added\" class=\"item added\">"
						+	"<a href=\"/catalog/" + cache.name_id + "/\">" + cache.name + "</a><br />"
						+	"(с/н: "+cache.sn+")"
						+	"</div>";
					oBasketLast.style.display = 'block';
				}else{
					ci++;
					oBasketComiss.innerHTML += "</div><div class=\"item\">"
						+	"<a href=\"/catalog/" + cache.name_id + "/\">" + cache.name + "</a><br />"
						+	"(с/н: "+cache.sn+")"
						+	"</div>";
				}
				sum += Number(cache.price);
				if(ci>0)
					oBasketComiss.style.display = '';
				else
					oBasketComiss.style.display = 'none';
			}
		}
	}
	//shuttle
		
	if(vars.shuttle.length > 0){
		var cs = 0;
		for(var i in vars.shuttle){
			cache = vars.shuttle[i];
			if(typeof(cache) == 'object'){
				cur_name = cache.cur_name;
				c++;
				if(unical_id == cache.unical_id){
					oBasketLast.style.display = 'block';
					oBasketLast.innerHTML = ""
						+ "<div id=\"just_added\" class=\"item added transparent\">"
						+	"<a href=\"/catalog/" + cache.name_id + "/body_" + i + "/\">" + cache.name + "</a>"
						+	"</div>";		
				}else{
					cs++;
					oBasketShuttle.innerHTML += ""
						+ "<div class=\"item\">"
						+	"<a href=\"/catalog/" + cache.name_id + "/body_" + i + "/\">" + cache.name + "</a>"
						+	"</div>";			
				}		
				sum += Number(cache.price);			
			}			
		}
		if(cs>0){
			oBasketShuttle.style.display = '';
		}else{
			oBasketShuttle.style.display = 'none';
		}
	}
		
	try{
		var ja = document.getElementById('just_added')
		if(ja !== null && typeof ja == 'object'){
			setFadeIn(ja, 30);
		}
	}
	catch(e){
		alert(e);
	}
	
	oBasketSum.innerHTML = 'В корзине ' + (c > 0?(c == 1?'<b>' + c + '</b> позиция':((c >= 2 && c <= 4)?'<b>' + c + '</b> позиции':'<b>' + c + '</b> позиций')):'') + "<p>на сумму <b>" + number_format(Math.ceil(sum), 0, ',', ' ') + "</b>&#160;" + cur_name + '</p>';
	var oDiv = nodeChildEnableDisable(oBtn, 'div', 'img');
	oDiv.innerHTML = oBtn.getAttribute('value_tmp');
	if(!disable_btn)
		oBtn.disabled = '';
	oOrder.disabled = '';
}

function showJustAddedImg(preview){
	if(oJustAddedImg) oJustAddedImg.innerHTML = "<img src=\"" + preview + "\"/>";
}

function sendBox(a, b, preview, endFunc){
	
	sendBox.prototype.moveBox = function(){
		this.y = this.k * this.x + this.b;
		//debug('this.y='+this.y);
		this.box.style.top = this.y+'px';
		this.box.style.left = this.x+'px';
		if(this.x >= this.x2){
			window.clearInterval(this.interval);
			document.body.removeChild(this.box);
			endFunc(preview);
			//showProcessingMsg('zlo', '', {x: 100, y: 100} );
		}
		if(this.y < this.pageScroll.top - this.h)
			this.x = this.x2;
		else
			this.x += this.segment_x_d;		
	}

	var thisCopy = this;

	this.w = 60;
	this.h = 60;
	this.segment = 20; // size of segment of line
	
	/*
	this.x1 = a.offsetLeft + a.offsetWidth / 2 - this.w / 2;
	this.y1 = a.offsetTop + a.offsetHeight / 2 - this.h / 2;
	this.x2 = b.offsetLeft + b.offsetWidth / 2 - this.w / 2;
	this.y2 = b.offsetTop + b.offsetHeight / 2 - this.h / 2;
	*/
	var tmp = getAbsolutePos(a);
	this.x1 = tmp.x + a.offsetWidth / 2 - this.w / 2;;
	this.y1 = tmp.y + a.offsetHeight / 2 - this.h / 2;
	tmp = getAbsolutePos(b);
	this.x2 = tmp.x + b.offsetWidth / 2 - this.w / 2;
	this.y2 = tmp.y + b.offsetHeight / 2 - this.h / 2;
	
	// line length
	this.d = Math.sqrt(Math.pow(this.x2 - this.x1, 2) + Math.pow(this.y2 - this.y1, 2));
	// line segments
	this.segments = this.d / this.segment;
	// x = (m2*x1 + m1*x2) / (m1 + m2), where m1/m2 = 1/this.segments, x1, x2 - x coordinates of start and end points. [Vigodsky, page 27]
	this.segment_x = (this.segments * this.x1 + 1 * this.x2)/(1 + this.segments);
	// length of segment on x axis
	this.segment_x_d = this.segment_x - this.x1;
	
	this.k = (this.y2 - this.y1) / (this.x2 - this.x1);
	this.b = this.y1 - this.k * this.x1;
	
	this.box = document.createElement('div');
	this.box.style.position = 'absolute';
	this.box.style.width = this.w;
	this.box.style.height = this.h;
	if(preview !== undefined && preview)
		this.box.style.backgroundImage = 'url('+preview+')';
	else
		this.box.className = 'good2basket';

	//this.box.style.left = 0 - this.w;
	//this.box.style.top = 0 - this.h;
	
	this.x = this.x1;
	
	this.box = document.body.appendChild(this.box);
	

	this.interval = window.setInterval(function(){
		return thisCopy.moveBox();		
	}, 10);
	
	this.pageScroll = getPageScroll();	
	//debug('this.pageScroll.left='+this.pageScroll.left+' '+'this.pageScroll.top='+this.pageScroll.top);
	
	/* document.getElementById('debug').innerHTML += 'x='+this.x+' y='+this.y+'<br />';
	document.getElementById('debug').innerHTML += 'x1='+this.x1+' y1='+this.y1+'<br />';
	document.getElementById('debug').innerHTML += 'x2='+this.x2+' y2='+this.y2+'<br />';
	document.getElementById('debug').innerHTML += 'd='+Math.ceil(this.d)+'<br />';
	document.getElementById('debug').innerHTML += 'segments='+this.segments+'<br />';
	document.getElementById('debug').innerHTML += 'segment_x='+this.segment_x+'<br />';
	document.getElementById('debug').innerHTML += 'segment_x_d='+this.segment_x_d+'<br />';
	document.getElementById('debug').innerHTML += '<br />'; */
}




// setup timer
function onKeyUp(event, oItem, id){
	var keynum;
	if(window.event)
		keynum = event.keyCode;
	else if(event.which)
		keynum = event.which;
	if(!((keynum >= 48 && keynum <= 57) || (keynum >= 96 && keynum <= 105) || keynum == 8 || keynum == 46))
		return false;
	
	if(searchTimeout)
		clearTimeout(searchTimeout);
	searchTimeout = window.setTimeout(
			function(){
				return updateCountItem(oItem, id, 0);
			}
		, 400);

}

// update count to db
function updateCountItem(oItem, id, responseCounter){
	var count = Math.ceil(oItem.value);
	try{
		if(!oItem.hasAttribute('tmp_bg'))
			oItem.setAttribute('tmp_bg', oItem.style.background);
	}
	catch(e){
		if(oItem.tmp_bg === undefined)
			oItem.setAttribute('tmp_bg', oItem.style.background);
	}
	if(Number(count) != 0){
		oItem.style.background = 'orange';
		var request = new httpRequest();
		var func = function(){
			var ret = request.responseText;
			if(ret != '' && isNaN(Number(ret)) === false){
				if(Number(ret) < 1){
					oItem.style.background = oItem.getAttribute('tmp_bg');
					discount = ret;
					oDiscountValue = document.getElementById('discount_value');
					if(oDiscountValue !== null){
						oDiscountValue.innerHTML = number_format(discount * 100, 0, ',', ' ');
						oDiscountValue.style.color = 'red';
					}
				}
				try{
					recalcItems();
				}
				catch(e){
					alert(e);
				}
			}
			else{ // blia...
				oItem.style.backgroundColor = 'red';
				// ... let's try again
				if(responseCounter < 20)
					updateCountItem(oItem, id, ++responseCounter);
			}
		}
		makeRequest(request, func, './recount_item/', 'POST', 'id=' + id + '&count=' + count);
	} else 
		oItem.style.backgroundColor = 'red';
}

// update (with new discount, if changed) prices and summ for all items in page
function recalcItems(){
	var sum, sum_old, sum_total = Number(), sum_old_total = Number(), discount_tmp = discount;
	for(v in counts){
		if(typeof counts[v] == 'object'){
			var o = counts[v];
			var this_discount = o.getAttribute('this_discount');
			var price = o.getAttribute('price');
			var price_old = o.getAttribute('price_old');
			if(pvals[v].getAttribute('sn') === null)
				discount = discount_tmp;
			else
				discount = 0;
			if(Number(this_discount) > 0){
				pvals[v].innerHTML = number_format(Math.ceil(price_old - price_old * this_discount), 0, ',', ' ');
				sum = o.value * (price_old - price_old * this_discount);
				svals[v].innerHTML = number_format(Math.ceil(sum), 0, ',', ' ');
				sum_total += sum;
				sum_old = o.value * price_old;
				if(svals_old[v] !== undefined)
					svals_old[v].innerHTML = number_format(Math.ceil(sum_old), 0, ',', ' ');
				sum_old_total += sum_old;
			} else if(discount == 0){//
				pvals[v].innerHTML = number_format(Math.ceil(price), 0, ',', ' ');
				sum = o.value * price;
				svals[v].innerHTML = number_format(Math.ceil(sum), 0, ',', ' ');
				sum_total += sum;
				sum_old = o.value * price_old;
				if(svals_old[v] !== undefined)
					svals_old[v].innerHTML = number_format(Math.ceil(sum_old), 0, ',', ' ');
				sum_old_total += sum_old;
			} else {
				pvals[v].innerHTML = number_format(Math.ceil(price_old - (discount?price_old * discount:0)), 0, ',', ' ');
				sum = o.value * (price_old - (discount?price_old * discount:0))
				svals[v].innerHTML = number_format(Math.ceil(sum), 0, ',', ' ');
				sum_total += sum;
				sum_old = o.value * price_old;
				if(svals_old[v] !== undefined)
					svals_old[v].innerHTML = number_format(Math.ceil(sum_old), 0, ',', ' ');
				sum_old_total += sum_old;
			}
		}
	}
	document.getElementById('summ_bottom_value').innerHTML = number_format(Math.ceil(sum_total), 0, ',', ' ');
	document.getElementById('summ_old_bottom_value').innerHTML = number_format(Math.ceil(sum_old_total), 0, ',', ' ');
}

function deleteItem(oBtn, id, sn, responseCounter, unical_id){
	if(Ext.isEmpty(sn)) sn = '';
	if(Ext.isEmpty(unical_id)){
		var oTr = document.getElementById('tr_' + id+sn);
		unical_id = '';
	}else
		var oTr = document.getElementById(unical_id).parentNode.parentNode;
	//oBtn.setAttribute('tmp', oBtn.innerHTML);
	//oBtn.innerHTML = '<img src="/i/progress_14x14.gif" width="14" height="14" />';
	oBtn.className = oBtn.className + ' process';
	oBtn.setAttribute('disabled', 'disabled');
	oBtn.setAttribute('onclick_tmp', oBtn.onclick);
	oBtn.setAttribute('onclick', 'return false;');
	var request = new httpRequest();
	var func = function(){
		var ret = request.responseText;
		if(ret != '' && isNaN(Number(ret)) === false && Number(ret) < 1){
			discount = ret;
			oDiscountValue = document.getElementById('discount_value');
			if(oDiscountValue !== null){
				oDiscountValue.innerHTML = discount * 100;
				oDiscountValue.style.color = 'red';
			}
			
			var deleteItemFromDOM = function (){
				oTr.parentNode.removeChild(oTr);
				delete counts[id+sn+unical_id];
				delete pvals[id+sn+unical_id];
				delete svals[id+sn+unical_id];
				delete svals_old[id+sn+unical_id];
				recalcItems();
			}
			
			setFadeOut(oTr, 30, deleteItemFromDOM, 20);
			
			/*if(sn)
				var oBasBody = document.getElementById('basket_comiss');
			else if(unical_id)
				var oBasBody = document.getElementById('basket_shuttle');
			else
				var oBasBody = document.getElementById('basket_main');*/
		}
		else{ // blia...
			// ... let's try again
			if(responseCounter < 20)
				deleteItem(oBtn, id, sn, ++responseCounter);
		}
	}
	makeRequest(request, func, './delete/', 'POST', 'id=' + id + (sn?'&sn='+sn:'') + (unical_id?'&unical_id='+unical_id:''));
}

function calcBasketSum(){
	var summ = Number(0);
	var c = 0;
	var oTbl = document.getElementById('basket_detailed');
	var inputs = oTbl.getElementsByTagName('input');
	for(var i = 0; i < inputs.length; i++){
		//oDebug.innerHTML += i + ' ' + inputs[i] + ' ' + inputs[i].name + ' ' + inputs[i].nodeType + '<br />';
		if(inputs[i].nodeType == 1){
			c++;
			var name_id = inputs[i].getAttribute('name_id');
			var price = Number(inputs[i].getAttribute('price'));
			var count = Number(inputs[i].value);
			//oDebug.innerHTML += 'name_id=' + name_id + ' price=' + price + ' count=' + count + '<br />';
			summ += Math.ceil(Math.ceil(price) * count);
		}
	}
	if(c > 0){
		var osumm_bottom = document.getElementById('summ_bottom');
		osumm_bottom.innerHTML = number_format(Math.ceil(summ), 0, ',', ' ');
		/*var ocount_bottom = document.getElementById('count_bottom');
		ocount_bottom.innerHTML = c + ' (' + c_all + ')';*/
	} else {
		oTbl.className = 'hidden';
	}
}

function calc_discount(func){
	var request = new httpRequest();
	var func = function(){
		var ret = request.responseText;
		if(ret){
			document.getElementById('discount_value').innerHTML = ret * 100;
			discount = ret;
			//calcBasketSum();
		}
	}
	makeRequest(request, func, '/basket/calc_discount/');
}

function showHideShuttleItems(o, unical_id){
	var items = document.getElementById(unical_id);
	if(items.offsetHeight){
		items.style.display = 'none';
		o.src = '/i/node_close.gif';
	} else {
		items.style.display = '';
		o.src = '/i/node_open.gif';
	}
}

var searchTimeout;
var discount = 0;
var oForm = document.getElementById('basket_form');
var oDebug = document.getElementById('debug');
var oBasket = document.getElementById('basket');
var oBasketLast = document.getElementById('basket_last');
var oJustAddedImg = document.getElementById('just_added_img');
var oBasketComiss = document.getElementById('basket_comiss');
var oBasketShuttle = document.getElementById('basket_shuttle');
var oBasketSum = document.getElementById('basket_sum');
var oOrder = document.getElementById('create_order');
var pvals = Object(),// price values
		svals = Object(),// summ values
		svals_old = Object(),// summ old valuer
		counts = Object();// count values
var sn_tmp = null, unical_id_tmp = null;

// begin get all spans and inputs for recalc
var oSpans = document.getElementsByTagName('span');
for(var i = 0; i < oSpans.length; i++){
	var v = oSpans[i];
	if(typeof v == 'object'){
		sn_tmp = v.getAttribute('sn');
		unical_id_tmp = v.getAttribute('unical_id');
		//alert(unical_id_tmp);
		//alert(v.innerHTML+' ['+v.getAttribute('name_id')+(sn_tmp === null?'':String(sn_tmp))+(unical_id_tmp === null?'':String(unical_id_tmp))+']');
		if(v.getAttribute('name') == 'price_value'){
			pvals[v.getAttribute('name_id')+(sn_tmp === null?'':String(sn_tmp))+(unical_id_tmp === null?'':String(unical_id_tmp))] = v;
			//alert('sn_tmp='+sn_tmp+' unical_id_tmp='+unical_id_tmp+' '+pvals[v.getAttribute('name_id')+(sn_tmp === null?'':String(sn_tmp))+(unical_id_tmp === null?'':String(unical_id_tmp))]+' '+v.getAttribute(''));
		}else if(v.getAttribute('name') == 'sum_value'){
			svals[v.getAttribute('name_id')+(sn_tmp === null?'':String(sn_tmp))+(unical_id_tmp === null?'':String(unical_id_tmp))] = v;
		}else if(v.getAttribute('name') == 'sum_old_value'){
			svals_old[v.getAttribute('name_id')+(sn_tmp === null?'':String(sn_tmp))+(unical_id_tmp === null?'':String(unical_id_tmp))] = v;
		}
	}
}

var oInputs = document.getElementsByTagName('input');
for(var i = 0; i < oInputs.length; i++){
	var v = oInputs[i];
	if(typeof v == 'object'){
		if(v.getAttribute('name') == 'count'){
			sn_tmp = v.getAttribute('sn');
			unical_id_tmp = v.getAttribute('unical_id');
			counts[v.getAttribute('name_id')+(sn_tmp === null?'':String(sn_tmp))+(unical_id_tmp === null?'':String(unical_id_tmp))] = v;
		}
	}
}
// end get all spans and inputs for recalc
