var dartFader;
var opp = 0.0;
var cTop = 0;
var x0;
var y0;
var theID;
var theRow;
var theFloater;
var floaters = new Array();
var row;
var oldValues = new Array();
var catItems = new Array();
var enteredValues = new Array();


function dbg(m) {
        document.getElementById("debug").innerHTML += "<b>MSG:</b> " + m + "; ";
}
function addAll() {
	return 0;
	//dbg('add-'+theID);
	myID = theID;
	theInput = document.getElementById('i'+theID);
	theID = 0;
	if (myID && theInput.style.display == '') {
		add(myID);
	}
}
function input(id) {
	addAll();
	theID = id;
	theInput = document.getElementById('i'+id);
	theSpan = document.getElementById('s'+id);
	theSpan.style.display = 'none';
	theInput.className = 'active';
}
function checkValue (id) {
	theInput = document.getElementById('i'+id);
	return 1;
}
function resetInput(id) {
	theInput = document.getElementById('i'+id);

	theSpan = document.getElementById('s'+id);
	theSpan.style.display = 'none';
	theInput.className = 'active';
}
function onChange(id) {
	dbg(curentObj);
	dbg('qwe');
}
function clearImg(obj) {
	return 1;
	id = obj.uid;
	i = document.getElementById('a'+id);
	i.style.border = '1px solid black';
}
function add(id) {
	theInput = document.getElementById('i'+id);
	theValue = myParseInt(theInput.value);
	theTitle = document.getElementById('title'+id);
	thePrice = document.getElementById('price'+id);
	thePic = document.getElementById('pic'+id);
	theComment = document.getElementById('comm'+id);
	theEdizm = document.getElementById('edizm'+id);
	theVupak = document.getElementById('vupak'+id);
	theSpan = document.getElementById('s'+id);
	//dbg(theInput.oldValue);
	//resize(theInput);
	re = /^\d*$/;
	re2 = /\D/g;
/*	if (!re.test(theInput.value)) {
		theInput.className = 'activeB';
		theInput.value = theInput.value.replace(re2,'');
		setTimeout("resetInput("+id+")",500);
	}
*/
//	theInput.style.width = parseInt(theInput.value.length *2/3) + 1 + "em";
	if (theValue > 0 && myParseInt(oldValues[id]) == 0) { 
		theInput.className = 'inactive';
		theSpan.style.display = '';
		//floater(id,'added');
		theInput.oldValue = theInput.value;
		theSpan.innerHTML = theInput.value;
		oldValues[id] = theInput.value;
		realAdd(id,theValue);
	//	hideImg(id);
		document.getElementById('a'+id).src = '/rel/shop/nppomega/images/ajax-loader.gif';
		tx_amashcart_pi1_add({
			uid:id,price:thePrice.innerHTML,quantity:theValue,title:theTitle.innerHTML,image:thePic.innerHTML,edizm:theEdizm.innerHTML,comment:theComment.innerHTML,vupak:theVupak.innerHTML
		});
	}
	else if (theValue > 0) {
		theInput.className = 'inactive';
		theSpan.style.display = '';
		realAdd(id,theValue);
		if (oldValues[id] != theValue) {
			//floater(id,'modified');
			document.getElementById('a'+id).src = '/rel/shop/nppomega/images/ajax-loader.gif';
			tx_amashcart_pi1_changeQuantity({uid:id,quantity:theValue});
		} else {
			hideImg(id);
		}
		theInput.oldValue = theInput.value;
		theSpan.innerHTML = theInput.value;
		oldValues[id] = theInput.value;
	} else {
		theInput.className = 'none';
		document.getElementById('cart'+id).style.display='';
		theSpan.style.display = 'none';
		realAdd(id,0);
	//	hideImg(id);
		if (oldValues[id] != theValue) {
	//		floater(id,'deleted');
			document.getElementById('a'+id).src = '/rel/shop/nppomega/images/ajax-loader.gif';
			tx_amashcart_pi1_remove(id);
		} else {
			hideImg(id);
		}
		theInput.oldValue = '';
		oldValues[id] = 0;
		theSpan.innerHTML = '';
		theInput.value = '';
	}
	return false;
}

function noNumbers(e, id) {
	var keynum;
	var keychar;
	var numcheck;
	var keycodes = new Array(8,9,13,16,35,36,37,38,39,40,46);
	if(window.event) {
		keynum = e.keyCode;
	} else if(e.which) {
		keynum = e.which;
	}
	//dbg(keynum);
	if (keynum == 13) {
		add(id);
	}
	if (array_search(keycodes, keynum) || keynum != parseInt(keynum) || keynum > 256 ) {
		return 1;
	}
	keychar = String.fromCharCode(keynum);
	numcheck = /\d/;
	if (numcheck.test(keychar)) {
		return true;
	} else {
		document.getElementById('i'+id).className = 'activeB';
		setTimeout ("document.getElementById('i'+"+id+").className = 'active'", 100);
		return false;
	}
}

function array_search(arr, value) {
	for (i=0; i < arr.length; i++) {
		if (arr[i] === value) {
			return true;
		}
	}
}
















var currentActiveId = 0;
var actionsStack = new Array();

// Если тыкаем не на спец символы каталога и при этом активно некое поле, выключаем его
function checkCatField(e){
	e = Common.Event.normalize(e)
	if (
		currentActiveId &&
		e.target.id != 'lab' + currentActiveId && // label in single view
		e.target.id != 'i' + currentActiveId && // input
		e.target.id != 'n' + currentActiveId && // num		
		e.target.id != 'a' + currentActiveId && // arrow
		e.target.id != 'l' + currentActiveId // loader
	) { deactivateField( currentActiveId ); return; }
}


// Включаем поле
function activateField(id) { 

	loader = document.getElementById( 'l' + id )
	input = document.getElementById('i'+id);	
	//arrowSingle = document.getElementById('aS'+id);

	// Вспоминаем, сколько милисекунд назад поле было деактивировано
	// Нужно для исключения мгновенной переактивации поля в SINGLE VIEW по клику на Купить
	d = new Date
	r = d - input.deactivated
	if ( r && r < 100 ) return;
	
	if ( ! loader.style.display ) {
		input.blur()
		return;
	}
	
	del = document.getElementById( 'x' + id )
	if ( del ) del.style.display = 'none'
	
	input.className = 'active';
	input.disabled = false
	input.focus()
	
	num = document.getElementById( 'n' + id )
	num.className = 'num'

	arr = document.getElementById( 'a' + id )
	if (arr) arr.style.display = ''
	
	currentActiveId = id
}


// Выключаем поле
function deactivateField(id){
	input = document.getElementById('i'+id);
	num = document.getElementById( 'n' + id )
	loader = document.getElementById( 'l' + id )
	del = document.getElementById( 'x' + id )
	arrowSingle = document.getElementById( 'aS' + id )
	
	if ( input.value )
		input.value = parseInt(input.value)

	if ( input.value == '0' || input.value == 'NaN' ) input.value = ''
	
	d = new Date()
	input.deactivated = d
	
	// Стрелка 
	arr = document.getElementById( 'a' + id )
	if (arr) arr.style.display = 'none'
	
	if ( ! enteredValues[id] ) enteredValues[id] = ''
	if ( ! input.value ) input.value = ''

	// nc: Не было и нет
	if ( ! enteredValues[id] && ! input.value ){
		input.className = ''
		num.className = 'num'
		if ( del ) del.style.display = ''

	// nc: Было и осталось таким же 
	} else if ( enteredValues[id] && input.value && enteredValues[id] == input.value ) {
		input.className = 'altered'
		num.className = 'num num-active'
		if ( del ) del.style.display = ''

	// add: Не было, но появилось
	} else if ( ! enteredValues[id] && input.value ) {
		enteredValues[id] = input.value
		input.disabled = true
		loader.style.display = ''
		if (arrowSingle) arrowSingle.style.display = 'none'
		catItems[id].quantity = input.value
		addAction( 'add', catItems[id] )


	// change: Было, но изменилось на "не ноль"
	} else if ( enteredValues[id] && input.value && enteredValues[id] != input.value ) {
		enteredValues[id] = input.value
		input.disabled = true
		catItems[id].quantity = input.value
		loader.style.display = ''
		if (arrowSingle) arrowSingle.style.display = 'none'
		addAction( 'change', catItems[id] )
	
	// change: Было и не стало
	} else if ( enteredValues[id] && ! input.value ) {
		enteredValues[id] = input.value
		input.disabled = true
		catItems[id].quantity = 0
		loader.style.display = ''
		if (arrowSingle) arrowSingle.style.display = 'none'
		addAction( 'remove', catItems[id].uid )
	}
	
}

function removeItem(id){
	del = document.getElementById( 'x' + id )
	del.style.display = 'none'
	loader = document.getElementById( 'l' + id )
	loader.style.display = ''
	addAction( 'remove', id )
}

// Добавить действие в очередь
function addAction( type, param ){
	actionsStack.push( { type: type, param : param } )
	makeActions()
}


var actionsInProgress = 0

// Выполняем действия
function makeActions(){
	if (actionsInProgress) { setTimeout ( "makeActions()", 10 ); return; }
	if ( actionsStack.length ) {
		actionsInProgress = 1
		action = actionsStack.shift()

		switch (action.type)
		{			
			case 'add': product_add(action.param); break;
			case 'change': product_change(action.param); break;
			case 'remove': product_remove(action.param); break;
		}
	
		setTimeout ( "makeActions()", 10 );
	}
}

/* NISH */
var send_count = 0;
var parms;
function product_add (obj)
{
	parms = obj;
	$.post('/basket/add/'+parms.pid+'/?ajax=1&quantity='+enteredValues[parms.pid], function(data){
		if(data!='')
		{
			basket_upd(data);
			itemAdded(parms);
		}	
	});	
}
function product_change (obj)
{
	parms = obj;
	$.post('/basket/delete/'+parms.pid+'/?ajax=1', function(data){
		if(data!='')
		{
			$.post('/basket/add/'+parms.pid+'/?ajax=1&quantity='+enteredValues[parms.pid], function(data){
				if(data!='')
				{
					basket_upd(data);
					itemChanged(parms);					
				}
			});	
		}	
	});		
}
function product_remove (id)
{
	del = document.getElementById( 'x' + id );
	del.style.display = 'none';
	loader = document.getElementById( 'l' + id );
	loader.style.display = '';	

	parms = id;
	//alert(id);
	$.post('/basket/delete/'+id+'/?ajax=1', function(data){
		if(data!='')
		{
			//itemRemoved(parms);
			//basket_upd(parms);
			catItems[parms]='';
			$('#tx_amashcart_pi1_item_'+parms).fadeOut(300);
			basket_upd(data);
		}	
	});		
	
}

function basket_upd(bascount)
{	
	var total = 0;
	var countP = 0;

	for ( id in catItems )
	{
		
		if(!isNaN(parseFloat(catItems[id].price)) && !isNaN(parseFloat(catItems[id].quantity)))
		{	
			countP = parseInt(countP) + parseFloat(catItems[id].quantity);
			var sum = parseFloat(catItems[id].price)*parseFloat(catItems[id].quantity);
			$('#tx_amashcart_pi1_view_besket_row_total_'+id).html(sum+'&nbsp;');
			if(!isNaN(sum))	total = parseFloat(total)+parseFloat(sum);
		}
	}

	if(total==0)
	{
		$('#tx_amashcart_pi1_basket_container').fadeOut(300, function(){$(this).parent().html('<p>Ваша корзина пуста</p>')});
	}
	else
	$('#tx_amashcart_pi1_view_besket_total').html(total+'&nbsp;');
	
	
	if($('#theCartText a').html()==null)
	{
		$('#Cart').css('background-image', 'url("/rel/shop/nppomega/images/cat-theCart.jpg")');
		$('#Cart').html('<div style="margin-left: 36px; padding-top: 8px; color: rgb(255, 255, 255);"><span style="line-height: 25px; font-size: 12px;">В вашей корзине</span><br><span style="font-size: 18px;" id="theCartText"><span style="font-size: 12px;">Всего товаров:&nbsp;</span><a id="blockbasket_count" href="/basket/" style="color: rgb(255, 255, 255);">'+countP+'</a>&nbsp;&nbsp;<a href="/basket/"><img src="/rel/shop/nppomega/images/cat-arrow2.gif" alt="" style="margin-bottom: -4px; margin-left: 7px;"></a></span></div>');
	}
	else			
	{
		//alert($('#theCartText a').html());
			//alert(parseInt(bascount)+' '+bascount);
		$('#theCartText a#blockbasket_count').html(parseInt(bascount));
	}

}
/* NISH */


function itemAdded(obj){
	id = obj.uid
	input = document.getElementById('i'+id);
	num = document.getElementById( 'n' + id )
	loader = document.getElementById('l'+id);
	loader.style.display='none';
	input.className = 'altered'
	input.disabled = false
	num.innerHTML = input.value
	num.className = 'num num-active'

	arrowSingle = document.getElementById( 'aS' + id )
	if (arrowSingle) arrowSingle.style.display = ''

	del = document.getElementById( 'x' + id )
	if ( del ) del.style.display = ''
	
	actionsInProgress = 0;
}

function itemChanged(obj){
	id = obj.uid
	input = document.getElementById('i'+id);
	num = document.getElementById( 'n' + id )
	loader = document.getElementById('l'+id);
	loader.style.display='none';
	input.className = 'altered'
	input.disabled = false
	num.innerHTML = input.value
	num.className = 'num num-active'

	arrowSingle = document.getElementById( 'aS' + id )
	if (arrowSingle) arrowSingle.style.display = ''

	del = document.getElementById( 'x' + id )
	if ( del ) del.style.display = ''

	actionsInProgress = 0;
}

function itemRemoved(obj){
	id = obj.uid

	loader = document.getElementById('l' + id);
	if (loader) loader.style.display='none';

	input = document.getElementById('i'+id);
	if (input) {
		input.className = ''
		input.disabled = false
	}

	num = document.getElementById( 'n' + id )
	if ( num ) {
		num.className = 'num'
		num.innerHTML = ''
	}

	arrowSingle = document.getElementById( 'aS' + id )
	if (arrowSingle) arrowSingle.style.display = ''

	del = document.getElementById('x'+id)
	if ( del ) del.style.display = ''

	actionsInProgress = 0;
}


function updateItems(obj){
	for ( id in obj ){
		enteredValues[id] = obj[id].quantity
		input = document.getElementById('i'+id);
		input.className = 'altered'
		input.value = obj[id].quantity
		num = document.getElementById( 'n' + id )
		num.innerHTML = obj[id].quantity
		num.className = 'num num-active'		
	}
	
	// Выбираем все лоадеры
	for ( key in catItems ){ 
		 if (!isNaN(key)) {
			loader = document.getElementById('l'+key);
			loader.style.display = 'none'			
		}
	}
}





function floater(id,action) {
	//dbg(id);
	hideImg(id);
	document.getElementById('a'+id).src = '/rel/shop/nppomega/images/cat-arrow1.gif';
	theForm = document.getElementById('s'+id);
	if (action == 'deleted') {
		theForm = document.getElementById('cart'+id);
	}
	mydivHolder = document.getElementById('divHolder');
	source = '/rel/shop/nppomega/images/cat-' + action + '.png';
	X = findPosX(theForm) - 55;
	Y = findPos(theForm) - 12;
	if (document.getElementById('f'+id)) {
		img = document.getElementById('f'+id);
	} else {
		img = document.createElement('img');
		img.id = 'f'+id;
		img.src = source;
		img.style.position = 'absolute';
		img.style.filter = 'alpha(opacity=10)';
		img.style.opacity = 0.1;
		img.opp = 0.1
		img.style.zIndex = '8';
		img.style.top = Y - 4 + 'px';
		img.cTop = Y - 4 ;
		img.style.left = X + 20 +  'px';
		mydivHolder.appendChild(img);
		//dartFader = img;
		doFadeUp(id);
	}
}

function myParseInt (n) {
	if (isNaN(n)) {
		return 0;
	} else {
		return n;
	}
}
function doFadeUp(id) {
	//dbg(id);
	el = document.getElementById('f'+id);
//	dbg('f'+id);
//	el.style.border = "1px solid #000"
	if (el.opp > 0.9 && el.parentNode) {
	//	doMove(el);
	//	el.parentNode.removeChild(el);
		setTimeout('doFadeDown('+eval(id)+')',1500);
	} else {
		el.opp += 0.15;
		el.cTop -= 2;
		el.style.filter = 'alpha(opacity=' + (el.opp * 10) + ')';
		el.style.opacity = el.opp;
		el.style.top = el.cTop + 'px';
	//	dbg(eval(id));
		setTimeout("doFadeUp("+eval(id)+")",50);
	}
}


function doFadeDown(id) {
	el = document.getElementById('f'+id);
	
	if (el) {
	if (el.opp < 0.1 && el.parentNode) {
	//	doMove(el);
		el.parentNode.removeChild(el);
		el.style.display = 'none';
	} else {
		el.opp -= 0.15;
		el.cTop += 2;
		el.style.filter = 'alpha(opacity=' + (el.opp * 10) + ')';
		el.style.opacity = el.opp;
		el.style.top = el.cTop + 'px';
		setTimeout('doFadeDown('+eval(id)+')',50);
	}
	}
}



