/**
* $Id: miniBasket.js,v 1.59 2009/09/29 10:30:23 nmelgarejo Exp $
* @author Eber Herrera
*
*/

function GSI_Widget_Minibasket(){
	
	this.name = 'minibasket';
	this.loadOrder = 9;
	var firstAttemp = false;
	
	var open = false;
	var _mthis = this;
	
	var loadSteps = 1;
	
	this.getLoadSteps = function(){
		return loadSteps;
	}
	
	var load = function(){
		var tRes = true;
		try{
			if (typeof GSI=="undefined") return false;
			if (!GSI.functions.isset(GSI.SID)) {
				GSI.setError('Widget: '+_this.name+' -> GSI.SID missing','WARNING');
				tRes = false;
				}
			if ($('#minicart').length !=1) {
				GSI.setError('Widget: '+_this.name+' -> template missing','WARNING');
				tRes = false;
				}
			}
			catch(e){
			return false;
			}
		return tRes;
	};
	
	this.loader = function(on){
		if(on){
			$('#mini-cart-left', this).addClass('mini-cart-loading');
			_mthis.status('<span class="remarked">LOADING...</span>');
		}
		else{
			$('#mini-cart-left', this).removeClass('mini-cart-loading');
			_mthis.status('OK');
		}
	};
	
	this.status=function(str){
		$('#mini-cart-left-text').html(str);
	};
	
	this.addToBasket = function(callback){
		 var addToBasketFeedback = function(){
			var tOffr = tItem.getData('offrprice');
			var unitPrice = tOffr ? tOffr : tItem.getData('orgprice');
			var itemSku = tItem.getData('id');
			var name = tItem.getData('name');
			var qty = tItem.quantity;
			if (GSI.metrics) GSI.metrics.addToBasketAction(itemSku, name, qty, unitPrice, null);
			_mthis.showLastAddedItem();
			callback();
			}
		_mthis.loader(true);
		try{
			var tItem = GSI.activeItem;
			GSI.basket.add(tItem, addToBasketFeedback);
			}catch(e){
				_mthis.status('ERROR: '+e.message);
		}
	};
	
	
	this.removeFromBasket = function(lineNum, callback){
		var removeFromBasketFeedback = function (){
		_mthis.loader(false);
		_mthis.draw();
		};
		var tItem = GSI.basket.getItemByLineNumber(lineNum);
		if (!tItem) return false;
		_mthis.loader(true);
		try{
			GSI.basket.remove(tItem, removeFromBasketFeedback);
			}catch(e){
				_mthis.status('ERROR: '+e.message);
		}
		
	};
	
	this.refresh = function(callback, onlyHeader){
		var refreshFeedback = function(){
		_mthis.loader(false);
		if (onlyHeader) _mthis.draw(0, true);
		else _mthis.draw();
		if (callback) callback();
		};
		_mthis.loader(true);
		try{
			GSI.basket.retrieve(refreshFeedback);
			}catch(e){
				_mthis.status('ERROR: '+e.message);
		}
	};
	
	this.show = function(callback){
		if (!callback) callback = function(){};
		var endShow = function(){
			open = true;
			callback();
		};
		if (!open) $("#minicart-slide").slideDown("slow", endShow);
	};
	
	this.hide = function(callback){
		if (!callback) callback = function(){};
		var endHide = function(){
			open = false;
			callback();
		};
		if (open) $("#minicart-slide").slideUp("slow", endHide);
	};
	
	
	this.draw = function(limit, onlyHeader){
		var onlyHeader = onlyHeader;
		var endRetrieve = function(){_mthis.loader(false);if (_mthis.draw(limit)) _mthis.show();}; 
		if (!GSI.basket.loaded) {
			_mthis.loader(true);
			try{
			if (firstAttemp) GSI.basket.retrieve(endRetrieve);
			firstAttemp = false;
			}catch(e){
				_mthis.status('ERROR: '+e.message);
			}
			return false;
			}
		var totalLength = GSI.functions.count(GSI.basket.data['LINES']);
		if (totalLength <=0) {
			_mthis.hide();
			_mthis.status(getStatusString());
			$('#mini-cart-right,#mini-cart-left').removeClass('enabled').addClass('disabled');
			return false;
		} else{
			$('#mini-cart-right a').attr('href', 'checkout?SID='+GSI.SID);
			$('#mini-cart-right, #mini-cart-left').addClass('enabled').removeClass('disabled');
			$('#mini-cart-right span').css("display", "none");
			$("#mini-cart-right a").hover(
				function(){
					$('#mini-cart-right').addClass('on').removeClass('off');

					}, function(){
					$('#mini-cart-right').addClass('off').removeClass('on');
				});
		}
		
		if (!GSI.functions.isset(limit)) limit = totalLength;
		else limit = (limit > totalLength) ? totalLength : limit;
		function initMiniBasketLine(item){
			var template = $('.minicart-line.ajax-template').clone().removeClass('ajax-template').html();
			var activeLine = item['lineposition'];
			try{
		
				var tItem = item;
				var tLi = '';
				for(var aProp in item['PROPERTIES']){
					if (aProp=='indexOf') continue;
					if (aProp=='PRIMARY_COLOR') continue;
					tLi +='<li>'+GSI.dict.getText('property', aProp.toLowerCase())+': <strong>'+item['PROPERTIES'][aProp]+'</strong></li>';
				}
				//
				
				var imgSrc = GSI_CATALOG_IMG_PATH+"mini/" + item['extinfo']['basket_img'];
				var imgSwatch = GSI_CATALOG_IMG_PATH+"swatch/" + item['extinfo']['swatch_img'];
				var price = item['currencyid']+' '+item['itemprice_currency'];
				var itemSku = item['item_sku'];
				var linePrice = GSI.functions.moneyFormat(item['linetotal_currency'],item['currencyid']);
				var name = item['itemname'];
				var html = template.replace(/src=".*__itemImage__"/g, 'src="' + imgSrc + '"');
				
				html = html.replace(/__itemName__/g, name);
				html = html.replace(/__itemSku__/g, itemSku);
				html = html.replace(/__itemPrice__/g, price);
				html = html.replace(/__linePrice__/g, linePrice);
				html = html.replace(/src=".*__itemSwatch__"/g, 'src="' + imgSwatch + '"');
				
				var tDiv = $(html);
				$('ul', tDiv).empty();
				$('ul', tDiv).append(tLi);
				$('#minicart-lines').append(tDiv);
			} catch(e){
				var html = template.replace(/__itemImage__/g,'NOK');
				html = html.replace(/__itemName__/g, 'NOK');
				html = html.replace(/__itemSize__/g, 'NOK');
				html = html.replace(/__itemPrice__/g, 'NOK');
				html = html.replace(/__basketLine__/g,activeLine);	
				$('.minicart-line-content', tDiv).append(html)
				if (!GSI.functions.isset(onlyHeader)) $('#minicart-lines').append(tDiv);
			}
			return true;
		};
		
		if (!GSI.functions.isset(onlyHeader)) $('#minicart-lines').empty();
		for(var aLine = totalLength-1; aLine>=(totalLength-limit); aLine--){
			if (GSI.basket.data['LINES'][aLine]['extra_data']['VOUCHER']) {
				if (limit < totalLength) limit++;
				continue;
			} 
			initMiniBasketLine(GSI.basket.data['LINES'][aLine]);
		}
		
		_mthis.status(getStatusString());
		var total = GSI.basket.data.grandtotal;
		if (total == undefined) total = 0;
		$(".subtotal-quantity", "#minicart").html(GSI.functions.moneyFormat(total, GSI.basket.data.currencyid));
		
		return true;
	};
	
	var getStatusString=function(){
		 var totalLength = GSI.functions.count(GSI.basket.data['LINES']);
		 var totalItems = 0;
		 var total = GSI.basket.data.grandtotal;
		
		 for(var aLine = totalLength-1; aLine>=0; aLine--){
			 if (GSI.basket.data['LINES'][aLine]['extra_data']['VOUCHER']) continue;
			 if (GSI.basket.data['LINES'][aLine]['item_sku'] == 'HEMMING') continue;
			 	totalItems += parseInt(GSI.basket.data['LINES'][aLine]['quantity']);
		 }
		
		 if (total == undefined) total = 0;
		 if (totalItems == 0) tRes = GSI.dict.getText('basket', 'basket is empty');
		 else tRes = '<span class="remarked">'+totalItems+'</span> '+GSI.dict.getText("basket", "items in basket")+' <span class="remarked">'+GSI.functions.moneyFormat(total, GSI.basket.data.currencyid)+'</span>';
		 return tRes;
	};
	
	this.showLastAddedItem = function(){
		var cartHidden = GSI.functions.getScrollXY()[1]  >=71 ? true : false;
		
		if ($.browser.msie && browserVersion == 6) {
			document.location.href="#";
			cartHidden = false;
		}
			
		if (cartHidden) {
			$("#minicart-slide").css(
				{
					position: "fixed",
					right: "2px",
					left : 'auto',
					top : '0px',
					"z-index" : "102"
				}
			);
			
			if (!$.browser.msie) $("#minicart-slide").prependTo(document.body);
			
			$('.minicart-line-loader').css('padding', '10px').html(GSI.dict.getText('basket', 'added to basket'));
		}
		$('.minicart-slide-line-info').show();
		_mthis.draw(1);
		_mthis.status(GSI.dict.getText('basket', 'added to basket'));
		_mthis.show();

		var endShow = function(){
			
			_mthis.hide(function(){
				if (cartHidden) {
					$("#minicart-slide").css(
						{
							position: "relative",
							left: "2px",
							right: 'auto',
							top : '24px'	
						});
					if (!$.browser.msie) $("#minicart-slide").appendTo('#minicart');
					$('.minicart-line-loader').empty();
				}
			_mthis.status(getStatusString());
			
			});
		}
		setTimeout(endShow,3000);
	};
	
	this.init = function(){
		if (!load()) {
			GSI.updateProgressBar(_mthis.name +" "+ GSI.dict.getText('JSAPI', 'widget_initiation_error'));
			return false;
		}
		$("#mini-cart-left").click(function () {
			if (!open) {
				if (_mthis.draw(5)) {
				_mthis.show();
				}
			} else {
				_mthis.hide();
			}
					
		},
		function(){});
		
		$("#mini-cart-left").hover(function(){
			if (!$(this).hasClass('disabled')){
			$(this).addClass('mini-cart-left-hover-on');
			}
		},
		function(){
			$(this).removeClass('mini-cart-left-hover-on');
		});
		
		var refreshFeedBack = function(){
			_mthis.loaded = true;
		}
		
		_mthis.refresh(refreshFeedBack, true);
		GSI.updateProgressBar(_mthis.name +" "+ GSI.dict.getText('JSAPI', 'widget_initiated'));	
		return true;
	};
}
GSI_Widget_Minibasket.prototype=new GSI_Widget();

var tW = new GSI_Widget_Minibasket();
GSI.widgets.loadWidget(tW);