/*
	Copyright (c) 2006-2007, ePages GmbH
	All Rights Reserved.

	epages.cartridges.de_epages.product.widget.VariationProductList

*/
dojo.provide("epages.cartridges.de_epages.product.widget.VariationProductList");
dojo.require("epages.cartridges.de_epages.product.widget.VariationAttributeList");
dojo.require("epages.widget.LocalizedWidget");
dojo.require('epages.string');

dojo.declare("epages.cartridges.de_epages.product.widget.VariationProductList",
	[epages.widget.LocalizedWidget],
	{
		/**
		 * public properties
		 */
		productAlias:        "",
		maxListedProducts:   400,
		maxSelectedProducts: 200, // feature ProductMaxSubProducts
		nextButtonId:        "",

		/**
		 * private properties
		 */
		_attributeAliases: undefined,
		_existingProducts: undefined,
		_newProducts:      undefined,
		_existingProductsKey: undefined,
		_newProductsKey:      undefined,
		_currentTable:     undefined,
		_counterExistingProducts: 0,
		_counterNewProductAlias: 0,
		_maxExistingProductReached: false,
		_maxNewProductReached: false,
		_inputs: undefined,

		/**
		 * widget properties
		 */
		templatePath:    dojo.moduleUrl('epages.cartridges.de_epages.product.widget', "templates/VariationProductList.html"),
		translationName: dojo.moduleUrl('epages.cartridges.de_epages.product.widget', 'templates/translation'),
		imagePath:       epages.themeUrl('images'),

		templateTable: ['<table class="ContentList BottomMargin">'+
											'<thead><tr><td class="Checkbox"><input checked="checked" class="Checkbox" dojotype="epages.widget.FormElement" name="selector" value="checkbox" onclick="OnCheckAll(this.form, \'ListItem\', this.checked);" type="text" /></td>', // 0
											'<td>','</td>', // 1 + 2
											'</tr></thead>'+
											'<tfoot><tr><td colspan="','"></tr></tfoot><tbody>','</tbody>'+ // 3+4+5
										'</table>' // 5
									 ],
		templateOldRow: ['<tr','>'+
									'<td class="Checkbox"><input disabled="disabled" class="Checked Checkbox Disabled" type="text" checked="checked" name="ListItem" value="" /></td>'+
									'<td class="MediumColumn NoWrap"><img title="" alt="" src="'+epages.vars.IconsRoot+'/object_ico_s_product.png" />','</td>',
									'<td>','</td>',
									'</tr>'
									],
		templateNewRow: ['<tr','>'+
									'<td class="Checkbox"><input type="text" checked="checked" name="ListItem" value="','" class="Checked Checkbox Disabled" dojotype="epages.widget.FormElement" /></td>' +
									'<td class="MediumColumn NoWrap"><img title="" alt="" src="'+epages.vars.IconsRoot+'/object_ico_s_product.png" /><input class="jsInput" type="text" name="VariationAlias','" value="','" /></td>',
									'<td>','<input type="hidden" name="NewVariationAttributeValues','" value="','" /></td>',
									'</tr>'
									],

		postMixInProperties: function() {
			this.inherited("postMixInProperties", arguments);
			this.maxListedProducts   = Number(this.maxListedProducts);
			this.maxSelectedProducts = Number(this.maxSelectedProducts);
			this._attributeAliases = [];
			this._existingProducts    = {};
			this._existingProductsKey = {};
			this._newProducts    = {};
			this._newProductsKey = {};
		},

		postCreate: function() {
			this.inherited("postCreate", arguments);
			var node = this.targetNode;
			this.connect(node,'onchange', '_onListEvent');
			this.connect(node,'onkeyup', '_onListEvent');
			this.connect(node,'onclick', '_onListEvent');
		},

		addAttribute: function (alias) {
			this._attributeAliases.push(alias);
		},

		buildKey: function(data) {
			return dojo.map(this._attributeAliases, function (el) { return data[el]; }).join("\n");
		},

		addExistingProduct: function (alias, productData) {
			this._existingProducts[alias] = productData;
			this._existingProductsKey[this.buildKey(productData)] = alias;
			this._counterExistingProducts++;
			if (this._counterExistingProducts >= this.maxSelectedProducts) {
				this._maxExistingProductReached = true;
				dojo.removeClass(this.ErrorMaxSubProductsReachedNode,'HideElement');
				return;
			}
		},

		buildNewAlias: function () {
			this._counterNewProductAlias++;
			var s = this._counterNewProductAlias.toString();
			if(s.length==1){
				s="000"+s;
			}
			if(s.length==2){
				s="00"+s;
			}
			if(s.length==3){
				s="0"+s;
			}
			return this.productAlias+'-'+s;
		},

		addNewProduct: function (productData) {
			if(this._maxExistingProductReached){
				return true;
			}
			if(this._counterNewProductAlias >= this.maxListedProducts) {
				if (this._maxNewProductReached){
					return true;
				}
				this._maxNewProductReached = true;
				dojo.removeClass(this.ErrorNewProductsNode,'HideElement');
				dojo.removeClass(this.ErrorNotAllNewProductsInListNode,'HideElement');
				return true;
			}
			var key = this.buildKey(productData);
			if(this._existingProductsKey[key] || this._newProductsKey[key]) {
				return false;
			}
			// find new alias
			var alias = this.buildNewAlias();
			while (this._newProducts[alias] !== undefined || this._existingProducts[alias] !== undefined) {
				alias = this.buildNewAlias();
			}

			// register new product
			this._existingProductsKey[key] = alias;
			this._newProducts[alias] = productData;
			return false;
		},

		showTable: function () {
			// show error MoreNewProductsAsPossible
			if(this._counterNewProductAlias > this.maxSelectedProducts) {
				dojo.removeClass(this.ErrorNewProductsNode,'HideElement');
				dojo.removeClass(this.ErrorMoreNewProductsAsPossibleNode,'HideElement');
			}
			// **** build table ****
			var rows = [];
			var template = this.templateTable;
			rows.push(template[0]);

			// build header
			rows.push(template[1]+this.translate('SKU')+template[2]);
			dojo.forEach(this._attributeAliases, function (el) {
				rows.push(template[1]+el+template[2]);
			}, this);

			// colspan footer
			rows.push(template[3]+(this._attributeAliases.length + 2)+template[4]);

			// build existing products
			template=this.templateOldRow;
			var isAlternate = true;
			for (var alias in this._existingProducts) {
				isAlternate = !isAlternate;
				data = this._existingProducts[alias];
				rows.push(template[0] + (isAlternate ? ' class="alternate" ' : '') + template[1]+alias+template[2]);
				dojo.forEach(this._attributeAliases, function (el) {
					if(data[el]){
						rows.push(template[3]+ epages.string.escapeXml(data[el]) + template[4]);
					}
				});
				rows.push(template[5]);
			}
			// build new products
			var counter = 0;
			template=this.templateNewRow;
			for(var alias in this._newProducts) {
				isAlternate = !isAlternate;
				data = this._newProducts[alias];
				rows.push(template[0] + (isAlternate ? ' class="alternate" ' : '') + template[1]+counter+template[2]+counter+template[3]+alias+template[4]);
				dojo.forEach(this._attributeAliases, function (el) {
					if(data[el]){
						rows.push(template[5]+epages.string.escapeXml(data[el])+template[6]+counter+template[7]+epages.string.escapeXml(data[el])+template[8]);
					}
				});
				rows.push(template[9]);
				counter++;
			}
			rows.push(this.templateTable[5]);
			this.targetNode.innerHTML = rows.join("\n");
			dojo.parser.parse(this.targetNode);
			// clear temp new products, because aliases can be changed, so they can not used longer
			this._existingProductsKey = {};
			this._newProducts = {};
		},

		checkInputAlias: function (input) {
			var v = input.value.toLowerCase();
			var nodes = dojo.filter(dojo.query(".jsInput", this.targetNode), function (el) {
				var checkBoxNode = dojo.query('input[name="ListItem"]',el.parentNode.parentNode)[0];
				if(checkBoxNode && !checkBoxNode.checked){
					return false;
				}
				else{
					return el.value.toLowerCase() == v;
				}
			});
			if (this._existingProducts[v] || nodes.length > 1) {
				if (!dojo.hasClass(input,'DialogError')) {
					dojo.addClass(input,'DialogError');
					this.enableNextButton();
					dojo.removeClass(this.ErrorDuplicateProductAliasNode,'HideElement');
				}
			} else {
				if (dojo.hasClass(input,'DialogError')) {
					dojo.removeClass(input,'DialogError');
					dojo.forEach(dojo.query(".DialogError", this.targetNode), this.checkInputAlias, this);
					if (this._areInputsValid()) {
						dojo.addClass(this.ErrorDuplicateProductAliasNode,'HideElement');
						this.enableNextButton();
					}
				}
			}
		},

		_onListEvent: function (evt) {
			if (evt.target.nodeName != 'INPUT'){
				return;
			}
			var input = evt.target;
			if (input.type == 'text') {
				var checkBoxNode = dojo.query('input[name="ListItem"]',input.parentNode.parentNode)[0];
				if(checkBoxNode && checkBoxNode.checked){
					this.checkInputAlias(input);
				}
			}
			else if(input.type =='checkbox' && input.checked){
				var aliasInput = document.getElementsByName('VariationAlias' + input.value)[0];
				if(aliasInput){
					this.checkInputAlias(aliasInput);
				}
			}
		},

		_areInputsValid: function () {
			var nodes = dojo.query(".DialogError", this.targetNode);
			return nodes.length == 0;
		},

		_areCheckboxesValid: function () {
			return true;
		},

		enableNextButton: function () {
			if (this.nextButtonId == ''){
				return;
			}
			var valid = this._areInputsValid() && this._areCheckboxesValid();

			var b = $$(this.nextButtonId);
			if (b === undefined){
				$(this.nextButtonId).disabled=!valid;
			}else if (valid){
				b.enable();
			}else{
				b.disable();
			}
		},

		resetAttributesList: function () {
			this._attributeAliases = [];
		},

		resetExistingProductKeys: function () {
			this._existingProductsKey = {};
			for (var alias in this._existingProducts) {
				var productData = this._existingProducts[alias];
				this._existingProductsKey[this.buildKey(productData)] = alias;
			}
		},

		resetNewProductList: function () {
			this._counterNewProductAlias = 0;
			this.resetExistingProductKeys();
			this._newProducts = {};
			this._newProductsKey = {};
		},

		createNewProducts: function (attributeWidgets, data) {
			var widgets = [];
			for (var i = 0, length = attributeWidgets.length; i < length; i++){
				if(attributeWidgets[i].useAttribute()){
					widgets.push(attributeWidgets[i]);
				}
			}
			var widget = widgets.shift();
			if (!widget) {
    			return true;
			}
			var values = widget.getValues();
			if (widget.useAttribute() && values.length) {
				var alias = widget.attributeAlias;
				var abort = false;
				dojo.forEach(values, function (value) {
					if (abort){
						return;
					}
					data[alias] = value;
					if (widgets.length) {
						abort = this.createNewProducts(widgets, data);
					} else {
						var copy = {};
						for (var key in data){
							copy[key] = data[key];
						}
						abort = this.addNewProduct(copy);
					}
				}, this);
				return abort;
			}
			if (widgets.length){
				return this.createNewProducts(widgets, data);
			}
			return this.addNewProduct(data);
		},

		buildTable: function (widgets) {
			if (widgets === undefined) {
				widgets = epages.cartridges.de_epages.product.widget.VariationAttributeList.prototype._widgetsOfClass;
			}
			this.resetAttributesList();
			dojo.forEach(widgets, function (el) {
				if(el.useAttribute()){
					this.addAttribute(el.attributeAlias);
				}
			}, this);
			this.resetNewProductList();
			this.createNewProducts(widgets, {});
		},

		setOnExistingProducts: function (alias, value) {
			for (var key in this._existingProducts) {
				var data = this._existingProducts[key];
				data[alias]=value;
			}
		},

		getCountExistingProducts: function () {
			return this._counterExistingProducts;
		}
});