YAHOO.namespace('istore.app');

YAHOO.istore.app.BriefView = function(id, config) {
	YAHOO.istore.app.BriefView.superclass.constructor.call(this, id, config);
}

YAHOO.lang.extend(YAHOO.istore.app.BriefView, YAHOO.istore.app.panel, {
	
	getOptionsValues: function () {
		
		var ret = [];
		
		if (this.options && this.options.length > 0) {
			for (var i = 0, l = this.options.length; o = this.options[i], i < l; i++) {
				ret[i] = o.getValue();
			}
		}
		
		return ret;
	},
	
	onPlacedQtyChangeHandler: function (e, args) {
		
		var vendor = args[0];
		var prodId = args[1];
		var optionsValues = args[2];
		var qty = args[3];
		
		// this options values
		var ov = this.getOptionsValues();
		// this options values string representation
		var ovStr = '';
		if (ov && ov.length > 0) {
			for (var i = 0, l = ov.length; i < l; i++) {
				ovStr += '' +  (i + 1) + ':' + ov[i] + ';';
			}
		}
		
		if (vendor == this.vendor && prodId == this.prodId && optionsValues == ovStr) {
			this.updatePlacedItemsQty(qty);
		}
		
	},
	
	optionChangeHandler: function (e, args) {
		YAHOO.istore.app.Msg.prototype.hideAll();
		
		var price = 0.00; // price modifiers
		var optionsSelected = true; // flag
		
		// if options exists
		if (this.options && this.options.length > 0) {
			
			// looping through them
			for (var i = 0, l = this.options.length; o = this.options[i], i < l; i++) {
				
				switch (o.type) {
					case "select": // combobox type
						
						price += o.getPrice();
						
						if (o.getValue() == -1) {
							optionsSelected = false;
							break;
						}
						
					break;
					case "text": // text type
						
						if (o.getValue() != '') {
							price += o.getPrice() - 0;
						}
						
					break;
				}
				
			} // loop through options
			
		} // if options exists
		
		
		// update price
		this.setPrice(this.initPrice + price);
		
		
		// if all options are selected
		if (optionsSelected) {
			
			// check wether item already exists in cart carousel
			if (typeof cartCarousel !== "undefined" && cartCarousel) {
				var qty = cartCarousel.getItemQtyByProductId(this.vendor, this.prodId, this.getOptionsValues());
				this.updatePlacedItemsQty(qty);
			}
			
			YAHOO.util.Dom.removeClass(this.btnSubmit, 'disabled');
			
		} else {
			this.updatePlacedItemsQty(0);
			YAHOO.util.Dom.addClass(this.btnSubmit, 'disabled');
		}
		
	},
	
	updatePlacedItemsQty: function (qty) {
		if (qty > 0) {
			if (this.getPlacedItemsQty() == 0) {
				this.showPlacedBlock();
			}
			this.setPlacedItemsQty(qty);
		} else {
			this.setPlacedItemsQty(0);
			this.hidePlacedBlock();
		}
	},
	
	getPlacedItemsQty: function () {
		return this.placedQty.innerHTML - 0;
	},
	
	setPlacedItemsQty: function (qty) {
		this.placedQty.innerHTML = qty;
	},
	
	getPrice: function () {
		return this.priceEl.innerHTML - 0;
	},
	
	setPrice: function (val) {
		this.priceEl.innerHTML = YAHOO.extension.funclib.formatCurrency(val);
	},
	
	showPlacedBlock: function () {
		YAHOO.util.Dom.setStyle(this.placedBlock, 'opacity', 0);
		YAHOO.util.Dom.setStyle(this.placedBlock, 'visibility', 'inherit');
		new YAHOO.util.Anim(this.placedBlock, {opacity: {to: 1}}, 0.3).animate();
	},
	
	hidePlacedBlock: function () {
		var anim = new YAHOO.util.Anim(this.placedBlock, {opacity: {to: 0}}, 0.3);
		var onComplete = function () {
			YAHOO.util.Dom.setStyle(this.placedBlock, 'visibility', 'hidden');
		}
		anim.onComplete.subscribe(onComplete, this, true);
		anim.animate();
	},
	
	btnGoClickHandler: function () {
		
		var options = this.getOptionsValues();
		
		// check wether item already exists in cart carousel
		if (typeof cartCarousel !== "undefined" && cartCarousel) {
			if (idx = cartCarousel.getItemIdxByProductId(this.vendor, this.prodId, options)) {
				window.scroll(0, 0);
				if (cartCarousel.isCartCarouselClosed()) {
					cartCarousel.openCartCarousel();
				}
				cartCarousel.scrollTo(idx)
			}
		}
		
	},
	
	// submit handler
	submitHandler : function (e, args) {
		YAHOO.istore.app.Msg.prototype.hideAll();
		
		var oThis = this;
		
		var qty = this.qtyChanger.cfg.getProperty('qty');
		
		var anim;
		
		var msgContext = 'prod-descr-btn-submit-' + this.prodId;
		var icoLoader = YAHOO.util.Dom.getElementsByClassName('ico-loader', 'img', this.element);
		
		YAHOO.util.Dom.setStyle(icoLoader, 'opacity', 0);
		YAHOO.util.Dom.setStyle(icoLoader, 'visibility', 'visible');
		
		// check whether options are selected
		if (this.options && this.options.length > 0) {
			for (var i = 0, l = this.options.length; o = this.options[i], i < l; i++) {
				
				switch (o.type) {
					case 'select':
						
						if (o.getValue() == '-1') {
							msgName = 'prod-descr-msg-warning-' + this.prodId + '-' + i;
							
							if (!(msg = YAHOO.istore.app.Msg.prototype.messages[msgName])) {
								msg = new YAHOO.istore.app.Msg('Please, select value', 
								{
									name : msgName,
									type : 'err',
									context : o.element.parentNode.parentNode.getElementsByTagName('span')[0],
									visible : false
								});
							}
							
							msg.show();
							
							return false;
						}
						
					break;
					case 'text':
						
						if (!YAHOO.istore.utils.Validator.isUrlString(o.getValue())) {
							msgName = 'prod-descr-msg-warning-' + this.prodId + '-' + i;
							
							if (!(msg = YAHOO.istore.app.Msg.prototype.messages[msgName])) {
								msg = new YAHOO.istore.app.Msg("Can contain numbers, letters and characters . , : ! ?", 
								{
									name : msgName,
									type : 'err',
									context : o.element.parentNode.getElementsByTagName('span')[0],
									visible : false
								});
							}
							
							msg.show();
							
							return false;
						}
						
					break;
				}
				
			}
		}
		
		var img = YAHOO.util.Dom.getElementsByClassName('prod-img', 'img', this.element)[0];
		
		this.btnSubmit.getElementsByTagName('input')[0].disabled = true;
		YAHOO.util.Dom.addClass(this.btnSubmit, 'disabled');
		new YAHOO.util.Anim(img, {opacity: {to: 0.1}}, 0.5).animate();
		new YAHOO.util.Anim(icoLoader, {opacity: {to: 1}}, 0.5).animate();
		
		var callback = {
			
			submitSuccessText : oThis.submitSuccessText,
			
			submitFailedText : oThis.submitFailedText,
			
			success: function () {
				
				msgName = 'prod-descr-msg-success-' + oThis.prodId;
				
				if (!(msg = YAHOO.istore.app.Msg.prototype.messages[msgName])) {
					msg = new YAHOO.istore.app.Msg(
						this.submitSuccessText, 
						{
							name : msgName,
							type : 'msg',
							context : oThis.btnSubmit,
							visible : false
						}
					);
				}
				
				msg.show();
				
				if (!YAHOO.util.Dom.hasClass(oThis.placedBlock, 'update') && oThis.getPlacedItemsQty() == 0) {
					oThis.setPlacedItemsQty(qty);
					oThis.showPlacedBlock();
				}
				
				new YAHOO.util.Anim(img, {opacity: {to: 1}}, 0.5).animate();
				new YAHOO.util.Anim(icoLoader, {opacity: {to: 0}}, 0.5).animate();
				YAHOO.util.Dom.removeClass(oThis.btnSubmit, 'disabled');
				oThis.btnSubmit.getElementsByTagName('input')[0].disabled = false;
				
			},
			
			failure: function () {
				
				msgName = 'prod-descr-msg-failed-' + oThis.prodId;
				
				if (!(msg = YAHOO.istore.app.Msg.prototype.messages[msgName])) {
					msg = new YAHOO.istore.app.Msg(
						this.submitFailedText, 
						{
							name : msgName,
							type : 'err',
							context : oThis.btnSubmit,
							visible : false
						}
					);
				}
				
				msg.show();
				
				new YAHOO.util.Anim(img, {opacity: {to: 1}}, 0.5).animate();
				new YAHOO.util.Anim(icoLoader, {opacity: {to: 0}}, 0.5).animate();
				YAHOO.util.Dom.removeClass(oThis.btnSubmit, 'disabled');
				oThis.btnSubmit.getElementsByTagName('input')[0].disabled = false;
				
			}
			
		}
		
		if (this.onSubmitEvt) {
			this.onSubmitEvt.fire(this.prodId, this.vendor, qty, this.options, callback);
		}
	},
	
	
	loadSuccessHandler : function (o) {
		
		var me = this;
		
		this.hidePreloader();
		this.applyContent(o.responseText);
		this.center();
		
		this.priceEl = YAHOO.util.Dom.getElementsByClassName('price-each', 'span', this.element)[0];
		this.initPrice = YAHOO.util.Dom.getElementsByClassName('init-price', 'input', this.element)[0].value - 0;
		this.placedBlock = YAHOO.util.Dom.getElementsByClassName('placed', 'div', this.element)[0];
		this.placedQty = YAHOO.util.Dom.getElementsByClassName('num', 'span', this.placedBlock)[0];
		this.placedBtnGo = this.placedBlock.getElementsByTagName('input')[0];
		this.btnSubmit = YAHOO.util.Dom.getElementsByClassName('btn-submit', 'span', this.element)[0];
		this.btnCancel = YAHOO.util.Dom.getElementsByClassName('btn-cancel', 'span', this.element)[0];
		this.qtyLimit = parseInt(YAHOO.util.Dom.getElementsByClassName('qty-available', 'input', this.element)[0].value);
		this.qtyChanger = new YAHOO.istore.app.qtyChanger(
			'prod-descr-qty-' + this.prodId,
			{
				onChangeHandler: function (e, args) {
					me.onQtyChangeEvt.fire(args);
				},
				limit: this.qtyLimit
			}
		);
		
		
		// processing options
		this.options = [];
		
		// get options elements
		var els = YAHOO.util.Dom.getElementsBy(function(el) {return (el.name && el.name.indexOf('option') == 0)}, null, this.element);
		if (YAHOO.lang.isArray(els) && els.length > 0) {
			
			// is all options selected
			var optionsSelected = true;
			
			for (var i = 0, l = els.length; i < l; i++) {
				
				// option object
				this.options[i] = new YAHOO.istore.app.BriefView.Option(els[i]);
				
				switch (this.options[i].type) {
					case 'text':
						
						// select onChange handler
						this.options[i].onKeyUpEvt.subscribe(this.optionChangeHandler, this, true);
						
					break;
					case 'select':
						
						// select onChange handler
						YAHOO.util.Event.addListener(this.options[i].element, 'change', this.optionChangeHandler, this, true);
						
						if (this.options[i].getValue() == -1) {
							optionsSelected = false;
						}
						
						// init IE hack that fixes width of the combobox
						if (YAHOO.env.ua.ie) {
							new YAHOO.Hack.FixIESelectWidth(els[i].id);
						}
						
						
					break;
				}
				
					
			}
				
			if (!optionsSelected) {
				YAHOO.util.Dom.addClass(this.btnSubmit, 'disabled');
			}
			
		}
		
		
		// check wether item already exists in cart carousel
		if (typeof cartCarousel !== "undefined" && cartCarousel) {
			var qty = cartCarousel.getItemQtyByProductId(this.vendor, this.prodId, this.getOptionsValues());
			if (qty && qty > 0) {
				this.setPlacedItemsQty(qty);
				YAHOO.util.Dom.setStyle(this.placedBlock, 'visibility', 'inherit');
			}
		}
		
		
		YAHOO.util.Event.addListener(this.btnCancel, 'click', this.hide, this, true);
		YAHOO.util.Event.addListener(this.btnSubmit.getElementsByTagName('input')[0], 'click', this.submitHandler, this, true);
		YAHOO.util.Event.addListener(this.placedBtnGo, 'click', this.btnGoClickHandler, this, true);
		
	},
	
	loadFailureHandler : function () {},
	
	load : function () {
		
		var callback = {scope: this, success: this.loadSuccessHandler, failure: this.loadFailureHandler};
		var connObj = YAHOO.util.Connect.asyncRequest('GET', this.ajaxUrl, callback);
		
	},
	
	init : function (id, config) {
		
		// call superclass (YAHOO.istore.app.panel) constructor 
		YAHOO.istore.app.BriefView.superclass.init.call(this, id, config);
		
		if (config.prodId != undefined) this.prodId= config.prodId; 
		if (config.vendor != undefined) this.vendor = config.vendor; 
		if (config.ajaxUrl != undefined) this.ajaxUrl = config.ajaxUrl;
		if (config.submitSuccessText != undefined) this.submitSuccessText = config.submitSuccessText;
		if (config.submitFailedText != undefined) this.submitFailedText = config.submitFailedText;
		
		this.onSubmitEvt = new YAHOO.util.CustomEvent('onSubmit');
		this.onQtyChangeEvt = new YAHOO.util.CustomEvent('onQtyChange');
		
		if (config.onSubmitHandler) {
			this.onSubmitEvt.subscribe(config.onSubmitHandler, this, true);
		}
		
		if (config.onQtyChangeHandler) {
			this.onQtyChangeEvt.subscribe(config.onQtyChangeHandler, this, true);
		}
		
		this.load();
	}
	
});


YAHOO.istore.app.BriefView.Option = function(el) {
	return this.init(el);
}

YAHOO.istore.app.BriefView.Option.prototype = {
	
	getValue: function () {
		return YAHOO.lang.trim(this.element.value);
	},
	
	getValueText: function () {
		
		switch (this.type) {
			case 'select':
				return this.element.options[this.element.selectedIndex].innerHTML;
			break;
			case 'text':
				return this.getValue();
			break;
		}
		
	},
	
	getPrice: function () {
		
		switch (this.type) {
			case 'select':
				
				// selected option
				var opt = this.element.options[this.element.selectedIndex];
				return opt.getAttribute('title') - 0;
				
			break;
			case 'text':
				
				return this.element.getAttribute('title') - 0;
				
			break;
		}
		
	},
	
	onKeyUpHandler: function (e, args) {
		
		var me = this;
		
		clearTimeout(this.onKeyUpTimeout);
		
		this.onKeyUpTimeout = setTimeout(function () {me.onKeyUpEvt.fire()}, 500);
		
	},
	
	init: function (el) {
		
		this.type = (el.tagName.toLowerCase() == 'select') ? 'select' : 'text',
		
		this.element = el;
		
		this.id = this.element.id.substr(this.element.id.lastIndexOf('-') + 1)
		
		this.onKeyUpEvt = new YAHOO.util.CustomEvent('on key up custom event');
		
		if (this.type == 'text') {
			
			YAHOO.util.Event.addListener(this.element, 'keyup', this.onKeyUpHandler, this, true);
		
		}
		
	}
	
}

