var disBuy, basketBox, basketTable, basketPrice, basketUpdating;

function TSFProduct(id, name, price, quantity) {
	this.id			= id;
	this.name		= name;
	this.price		= price;
	this.quantity	= quantity;

	this.basket_tr	= null;
	this.count_td	= null;
}

var basketHLFx = Fx.Base.extend({
	initialize: function(el, options){
		this.element = $(el);
		this.parent(options);
	},
	increase: function(){
		if(this.now <=50) {
			var p = (this.now * 100)/50;
			var c = new Color('#fff').mix('#FFCF40', p);
		} else {
			var p = ((this.now-50) * 100)/50;
			var c = new Color('#FFCF40').mix('#fff', p);
		}
		this.element.setStyle('background-color', c);
	}

});

var HLObjs = new Array();
function basketHL(r) {
	var f = function() {
		r.setStyle('background-color', '');
	};
	var x = new basketHLFx(r, {duration: 1500, onStart: function() {
		HLObjs.each(function(xx){ xx.stop();});
	}, onCancel: f, onComplete: function(){
		f();
		if(basketUpdating && $(r).hasClass('basket-row-focus')) basketHL(r);
	}}).start(0, 100);
	HLObjs.push(x);
}

TSF.basket = {
	
	basketProduct:	[],
	updateBasketTimeOut : function()
	{
		var self = this ;
		var req = TSF.simple(basketUrl+'&action=jsProductList',function(r, success)
		{
			if(success)
			{
				self.updateBasketProducts(r);
				setTimeout(self.updateBasketTimeOut.bind(self), 5000);
			}else{
				self.updateBasketTimeOut();
			}
		});
		req.addEvent('onCancel', this.updateBasketTimeOut.bind(self));
		this.basketRequest.push(req);
	},
	basketRequest : [],
	cancelRequests:function()
	{
		this.basketRequest.each(function(req){
			req.cancel();			
		});
	},
	updateBasketProducts : function(r) 
	{
		var self = this ;
		eval( r );
		var productsId = [];
		basketProducts.each(function(p){

			if(productsId.indexOf(p.id) == -1)
			{
				productsId.push(p.id);

				var OriginalCount = 0;
				for(var i=0; i < basketProducts.length; i++) {
					if(basketProducts[i].id == p.id) OriginalCount++;
				}

				var basketCount = self.getCountProduct(p.id);
				if(basketCount > OriginalCount)
				{
					for(var i=0; i < (basketCount - OriginalCount); i++) {
						self.deleteCount(p.id,true);
					}
				}
				else if(basketCount < OriginalCount)
				{
					for(var i=0; i < ( OriginalCount - basketCount ); i++) {
						self.add(p.id,p.name,p.price,p.quantity,true,true);
					}
				}
			}
		});

		var productsId = [];
		this.basketProduct.each(function(p)
		{
			if(productsId.indexOf(p.id) == -1)
			{
				productsId.push(p.id);

				var OriginalCount = 0;
				for(var i=0; i < basketProducts.length; i++) {
					if(basketProducts[i].id == p.id) OriginalCount++;
				}

				if(OriginalCount == 0)
				{
					self.remove(p.id,true);
				}
			}

		});
	},
	
	add: function(pid, name, price, quantity, notsave, notfocus,direct) 
	{
		if( direct == undefined) direct = false;
		if( notsave == undefined) notsave = false;
		if( notfocus == undefined) notfocus = false;
		
		name = stripslashes(name);
		name = htmlspecialchars_decode(name);
		var pobj, count;
		
		var count = this.getCountProduct(pid);
		if(quantity <= 1 && count > 0) {
			this.setDisableButtons(pid);
			this.disableAddDeleteProduct(pid,'add');
			return;
			
		}else if(quantity > 1 && count > 0) {
			if(quantity < this.getProducts(pid).length + 1) {
				this.setDisableButtons(pid);
				this.disableAddDeleteProduct(pid,'add');
				
				return;
			}
		}else if(quantity < 1 && count < 0) {
				this.setDisableButtons(pid);
				this.disableAddDeleteProduct(pid,'add');
				return;
		}

		
		this.enableAddDeleteProduct(pid,'delete');
		this.basketProduct.push( new TSFProduct(pid, name, price, quantity) );
		
		var jsName = addslashes(name)
		jsName = htmlspecialchars(jsName);
		
		var productCountRemove  = '<div class="basket-delete-product i-'+pid+'"  onclick="TSF.basket.deleteCount('+pid+');"></div>';
		var productCountadd 	= '<div class="basket-add-product i-'+pid+'"     onclick="TSF.basket.add('+pid+',\''+jsName
									+'\','+price+','+quantity+', false, true);"></div>';
							
		$$('.basket-row-focus').removeClass('basket-row-focus');
	
		if(count > 0) {
			var f = this.getProducts(pid)[0];
			f.count_td.innerHTML = ((f.count_td.innerHTML).toInt() + 1);

			$(f.basket_tr).addClass('basket-row-focus');
			
		} else {
			var tbl, td, tr
			
			pobj = this.basketProduct.getLast();
			
			tbl  = basketTable, td, tr;
			tr   = tbl.insertRow(tbl.rows.length);
			tr.className   = 'basket-row';
			pobj.basket_tr = tr;
			
			td = tr.insertCell(tr.cells.length);
			td.noWrap = 'nowrap';
			td.title  = name;
			td.innerHTML = '<div style="overflow: hidden; width: 80px;">'+name+'</div>';
			
			
			td = tr.insertCell(tr.cells.length);
			td.innerHTML = this.getCountProduct(pid);
			pobj.count_td = td;
			
			td = tr.insertCell(tr.cells.length);
			td.innerHTML =  productCountadd + productCountRemove;
			pobj.countaction_td = td;
			
			td = tr.insertCell(tr.cells.length);
			td.innerHTML = '<div class="basket-remove-product"  onclick="TSF.basket.remove('+pid+');"></div>';
					
			$(tr).addClass('basket-row-focus');
			
		}
		
		this.setBasketPrice();
		
		if(showBasket) basketBox.setStyle('display', 'block');
		
		if(!notsave) {
			this.saveBasket('add',pid,direct);
			
			//basket focus
			if(!notfocus) {
				var bp = $$('div.basket')[0].getPosition();
				window.scrollTo(bp.x, bp.y);
				
				basketHL( $$('.basket-row-focus')[0] );
			}
		}
		count = this.getCountProduct(pid);
		if(count <= 1)
		{
			this.disableAddDeleteProduct(pid,'delete');
		}
		if(quantity == count){
			this.setDisableButtons(pid);
			this.disableAddDeleteProduct(pid,'add');
			return;
		}

	},
	
	deleteCount : function(id,notsave) 
	{
		if( notsave == undefined) notsave = false;
		this.enableAddDeleteProduct(id,'add');
		
		var f = this.getProducts(id)[0];
		if((f.count_td.innerHTML).toInt() > 1)
		{
			f.count_td.innerHTML = ((f.count_td.innerHTML).toInt() -1 );
			
			for(var i=0; i < this.basketProduct.length; i++) {
				if(this.basketProduct[i].id == id && !this.basketProduct[i].count_td) {
					this.basketProduct.remove(this.basketProduct[i]);
					break;
				}
			}
			
			this.setBasketPrice();
			
			if(!notsave)
			this.saveBasket('deleteCount',id);
			
			this.createAddLink(f);
			this.createAddBuyLink(f);
		}
		
		var count = this.getCountProduct(f.id);
		if(count <= 1){
			this.disableAddDeleteProduct(f.id,'delete');
			return;
		}
	},
	
	getCountProduct: function(id) {
		var c = 0;
		for(var i=0; i < this.basketProduct.length; i++) {
			if(this.basketProduct[i].id == id) c++;
		}
		return c;
	},
	
	getProducts: function(id) {
		var p = [];
		for(var i=0; i < this.basketProduct.length; i++) {
			if(this.basketProduct[i].id == id) p.push(this.basketProduct[i]);
		}
		return p;
	},
	
	setBasketPrice: function() {
		var price = 0;
		for(var i=0; i < this.basketProduct.length; i++) {
			price += this.basketProduct[i].price;
		}
		basketPrice.innerHTML = price;
	},
	
	remove: function(pid,notsave) {
		if( notsave == undefined) notsave = false;
		var tr, pr;
		pr = this.getProducts(pid)[0];
		tr= pr.basket_tr;
		this.basketProduct = this.basketProduct.filter(function(p){
			return p.id != pid;
		});
		this.setBasketPrice();
		$(tr).remove();
		if(!this.basketProduct.length) {
			basketBox.setStyle('display', 'none');
		}
		
		if(!notsave)
		this.saveBasket('remove',pid);
		this.createAddLink(pr);
		this.createAddBuyLink(pr);
	},
	removeAll: function() {
		var pids=[], tr, p;
		for(var i=0; i < this.basketProduct.length; i++) {
			
			p = this.basketProduct[i];
			if(!pids.contains(p.id))
			{
				$(p.basket_tr).remove();
				pids.include(p.id);
				this.createAddLink(p);
				this.createAddBuyLink(p);
			}
		}
		
		this.basketProduct = [];
		
		this.setBasketPrice();
		
		if(!this.basketProduct.length) {
			basketBox.setStyle('display', 'none');
		}
		
		this.saveBasket('removeAll');
	},
	saveBasket: function(actionType,pid,direct) {
		
		if( pid == undefined) pid = '';
		if( direct == undefined) direct = false;
		
		this.cancelRequests();
		
		var data = ['action=save','actionType='+actionType,'pid='+pid], self = this;
		
		$$('.basket-progress').setStyle('display', '');
		basketUpdating = true;
		TSF.post(basketUrl, data.join('&'), function(r, success){
			self.refreshFactor(direct);
			$$('.basket-progress').setStyle('display', 'none');
			if(!success) self.saveBasket(actionType,pid);
			
			basketUpdating = false;
		});
	},
	refreshFactor : function(direct){
		if($('buy_result') != undefined || direct) TSF.page(showFactorUrl);
		return true;
	},
	createAddLink: function(p) {
		
		var jsName = addslashes(p.name)
		jsName = htmlspecialchars(jsName);
		
		$$( this.getBasketButton(p.id) ).setHTML(
			'<a href="javascript:void(0)" onclick="TSF.basket.add('+p.id+', \''+jsName+'\', '+p.price+', '+p.quantity+')">'
			+'<input type="button" class="sabade-kharid" /></a>'
		);	
	},
	createAddBuyLink: function(p) {
		
		var jsName = addslashes(p.name)
		jsName = htmlspecialchars(jsName);
		
		$$( this.getBuyButton(p.id) ).setHTML(
			'<a href="javascript:void(0)" onclick="TSF.basket.add('+p.id+', \''+jsName+'\', '+p.price+', '+p.quantity+',0,0,1)">'
			+'<input type="button" class="direct-buy" /></a>'
		);	
	},
	getBasketButton: function(id, elm) {
		var f = function(b){
			return b.hasClass('i-' + id);
		};
		if(elm) {
			return $(elm).getElements('div.product-basket').filter(f);
		} else {
			return $$('div.product-basket').filter(f);
		}
	},
	getBuyButton: function(id, elm) {
		var f = function(b){
			return b.hasClass('i-' + id);
		};
		if(elm) {
			return $(elm).getElements('div.product-buy').filter(f);
		} else {
			return $$('div.product-buy').filter(f);
		}
	},
	
	getAddDeleteButton: function(id, elm) {
		var f = function(b){
			return b.hasClass('i-' + id);
		};
		return $$(elm).filter(f);
	},
	
	disableAddDeleteProduct:function(pid,type)
	{
		var className 			= (type == 'add') ? 'basket-add-product' : 'basket-delete-product';
		var disableClassName	= className+'-dis';
		
		$$(this.getAddDeleteButton(pid,'div.'+className)).addClass(disableClassName);
		$$(this.getAddDeleteButton(pid,'div.'+className)).removeClass(className);
	},
	enableAddDeleteProduct:function(pid,type)
	{
		var className 			= (type == 'add') ? 'basket-add-product' : 'basket-delete-product';
		var disableClassName	= className+'-dis';
		
		$$(this.getAddDeleteButton(pid,'div.'+disableClassName)).addClass(className);
		$$(this.getAddDeleteButton(pid,'div.'+disableClassName)).removeClass(disableClassName);
	},
	setDisableButtons:function(pid)
	{
		$$(this.getBuyButton(pid)).setHTML(disBuy);
		$$(this.getBasketButton(pid)).setHTML(disBasket);
	}
};

function cheskBuyButton(e) {
	setTimeout(function() {
		
		var ch = [];
		for(var i=0; i < TSF.basket.basketProduct.length; i++) {
			var p = TSF.basket.basketProduct[i];
			if(ch.contains(p.id)) continue;
			var c = TSF.basket.getCountProduct( p.id );
			if(p.quantity <= c) {
				$$(TSF.basket.getBuyButton(p.id, e)).setHTML(disBuy);
				$$(TSF.basket.getBasketButton(p.id, e)).setHTML(disBasket);
			}
			ch.push(p.id);
		}
	}, 200);
}

window.addEvent('domready', function(){
	basketBox = $$('div.basket')[0];
	basketTable = basketBox.getElements('.basket_content')[0];
	basketPrice = basketBox.getElements('.basket-price')[0];
	
	disBuy 	= '<a><img src="'+themeUrl+'images/direct-buy-off.png" /></a>';
	disBasket = '<a><img src="'+themeUrl+'images/go2basket-n.gif" /></a>';
	disDelete = 'true';
});

function addslashes(str) {
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\0/g,'\\0');
	return str;
}
function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\0/g,'\0');
	str=str.replace(/\\\\/g,'\\');
	return str;
}

function htmlspecialchars_decode(name) {
	name = name.replace(/&quot;/g, '"');
	name = name.replace(/&#039;/g, '\'');
	
	return name;
}

function htmlspecialchars(name) {
	name = name.replace(/"/g, '&quot;');
	name = name.replace(/'/g, '&#039;');
	
	return name;
}

