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

	epages.cartridges.de_epages.product.widget.ProductTypeAttributeList

*/
dojo.provide("epages.cartridges.de_epages.product.widget.ProductTypeAttributeList");
dojo.require("epages.widget.LocalizedWidget");
dojo.require('epages.cartridges.de_epages.product.widget.ProductTypeAttribute');

dojo.declare("epages.cartridges.de_epages.product.widget.ProductTypeAttributeList",
	[epages.widget.LocalizedWidget], {

		/**
		 * public properties
		 */
		productTypeId     : '',														// string - id of product type
		productTypeName   : '',														// string - name of product type
		productTypeData   : undefined,										// object - product type data
		url               : '?',													//
		changeAction      : 'SaveProductType',						// string - name of change action
		viewAction        : 'View-JSON-ProductTypeData',	// string - name of view action
		objectId          : '',														// string - id of ressource
		currentLanguageId : '',					// string - id of current (display) language
		showVisibileOnly  : '0',				// string - flag to hide not visible attributes
		maxCountAttributes: 0,					// integer - numer of max possible attributes


		/**
		 * public properties
		 */
		_ep_childWidgets  : undefined,	// array   - array with child widgets
		_countAttributes  : 0,					// integer - current count attributes


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

		postMixInProperties: function(){
			this.inherited("postMixInProperties", arguments);
			this._ep_childWidgets = [];
			this.productTypeData = window.epages.vars.productTypeData;
			this.productTypeName = this.productTypeData.name;
			this.showVisibileOnly = epages.string.toBoolean(this.showVisibileOnly);

			if(epages.vars.features) {
				if(! epages.vars.features.ProductTypeAttributes) {
					console.warn("epages.vars.features.ProductTypeAttributes not defined in "+this.declaredClass );
				}
			} else {
				console.warn("epages.vars.features not defined in "+this.declaredClass );
			}
			this.maxCountAttributes = parseInt(epages.vars.features.ProductTypeAttributes.FeatureMaxValue);
		},

		postCreate: function(){
			this.inherited("postCreate", arguments);
			if(window.epages.vars.productTypeData) {
				console.warn('epages.vars.productTypeData not defined in '+this.declaredClass);
				this.productTypeData = window.epages.vars.productTypeData;
				this.productTypeName = this.productTypeData.name;
				this._setUpContent();
			}	else {
				this.onChangeProductType(this.productTypeId);
			}

			dojo.subscribe(this.id+"/attributeRemoved", this, "onAttributeRemoved");
			dojo.subscribe(this.id+"/changeProductType", this, "onChangeProductType");
			dojo.subscribe(this.id+'/changeProductTypeName', this, 'onChangeProductTypeName');
		},

		_setUpContent: function() {
		// summary: create attribute widgets / display feature count message
			for(var key in this.productTypeData.attributes) {
				var data = this.productTypeData.attributes[key];
				if(data.isVisible == "1" || !this.showVisibileOnly) {
					var attributeWidget = new epages.cartridges.de_epages.product.widget.ProductTypeAttribute({
						name : data['name:'+this.currentLanguageId],
						alias : key,
						data: data,
						attributeListId : this.id,
						productObjectID : this.objectId,
						attributeNumber : this._countAttributes
					});
					if(attributeWidget) {
						this.containerNode.appendChild(attributeWidget.domNode);
						this._ep_childWidgets.push(attributeWidget);
					}
				}
				this._countAttributes++;
				if(this._countAttributes >= this.maxCountAttributes ) {
					this.newAttributeNode.style.display="none";
					this.featureLimitExeededNode.style.display = "";
				} else {
					this.newAttributeNode.style.display="";
					this.featureLimitExeededNode.style.display = "none";
				}
			}
		},

		onChangeProductTypeName: function(/* string */name ) {
		// summary: change the name node of productype
			this.nameNode.innerHTML = name;
			document.getElementById("AttributeNameWarning").style.display="none";
		},

		onAddNewAttribute: function() {
		// summary: add ne (empty) attribute widget
			var attributeWidget = new epages.cartridges.de_epages.product.widget.ProductTypeAttribute({
				attributeListId : this.id,
				attributeNumber : this._countAttributes,
				productObjectID : this.objectId
			});
			if(attributeWidget) {
				this._ep_childWidgets.push(attributeWidget);
				this.containerNode.appendChild(attributeWidget.domNode);
				this._countAttributes++;
				if(this._countAttributes >= this.maxCountAttributes ) {
					this.newAttributeNode.style.display="none";
					this.featureLimitExeededNode.style.display = "";
				} else {
					this.newAttributeNode.style.display="";
					this.featureLimitExeededNode.style.display = "none";
				}
			}
		},

		onAttributeRemoved: function(/* object */ opt) {
		// summary: message function - decrease counter ( show / hide feature limit message)
			this._countAttributes--;
			if(this._countAttributes >= this.maxCountAttributes ) {
				this.newAttributeNode.style.display="none";
				this.featureLimitExeededNode.style.display = "";
			} else {
				this.newAttributeNode.style.display="";
				this.featureLimitExeededNode.style.display = "none";
			}
		},

		onChangeProductType : function(/* string*/ productTypeId) {
		// summary: load new product type data by product type id
			var formData = {
				'ChangeAction' : this.changeAction,
				'ViewAction' : this.viewAction,
				'ObjectID' : this.objectId,
				'Class' : productTypeId
			};

			var _this = this;
			var request = new dojo.xhrPost({
				url     : this.url,
				Accept  : 'text/x-json',
				content : formData,
				load    : function(response, args) {
					_this._setNewProductType(response, args);
				},
				error   : this._loadError
			});
		},

		_loadError: function (response, args) {
		// summary: error callback / displays an error message
			var rm = response.message;
			var rn = response.name;
			dojo.publish("uimessage/showErrors", ["IO ERROR", 'loading product type data', [{
				Message : 'Could not load product type data.('+rm+')',
				Reason  : rn
			}
			]]);
			console.error(response, args);
		},

		_setNewProductType : function(response, args) {
		// summary: prepare and setup new prdouctype data / widgets
			this._destroyChildWidgets();
			response = response.replace(/<!--.*-->/g, "");		// remove comments from pagetype
			this.productTypeData = dojo.fromJson(response);
			this._setUpContent();
		},

		_destroyChildWidgets : function() {
		// summary: destroys all childwidgets
			for(var el in this._ep_childWidgets) {
				this._ep_childWidgets[el].destroy();
				delete this._ep_childWidgets[el];
			}
			this._ep_childWidgets = [];
		},

		step: function( step , ObjectID ){
			var saveSubscribe;
			if(step && step.stepData && step.stepData.TemplateName == "Content-Attributes") {
				saveSubscribe = dojo.subscribe( 'ResourceWizard/saveFinished', dojo.hitch( this, function(resultData){
					if(resultData && resultData.Attributes) {
						var attributeWidgets = this._ep_childWidgets;
						var preDefValueObjects = {};
						if(attributeWidgets) {
							// for all attributes that were created by the wizard's changeaction
							dojo.forEach(resultData.Attributes, function(att){
								// for all widgets related to each attribute
								dojo.forEach(attributeWidgets, function(widget){
									var attrType = widget.data.type;
									// depending on the attribute type
									if(widget.newAttributeNameNode.value == att.Alias) {
										// found the correct correlated attribute
										// update widget data (for later value-assignment to resource object)
										widget.data.id = att.ObjectID;
										widget.alias = att.Alias;

										var result; // JSON result
										if(attrType == "PreDefString") {
											// get value nodes of this attribute
											dojo.forEach(widget.valueContainerNode.children, function(divNode) {
												// all inputs in that div
												dojo.query("input[name^='AttributeName'][type$='text']", divNode).forEach(function(input) {
													// send save request for this attribute containing the values
													var params = {
														'ChangeAction'	 : 'SavePreDefAttributes',
														'ObjectID'			 : att.ObjectID,
														'NewAlias'			 : att.Alias,
														'NewPosition'		: 9999,
														'NewValueString' : input.value,
														'Save'					 : 1
													};
													var result = new epages.io.Json().loadSync('?', params);
													if(result && result.error && result.error.data){
														console.warn("todo: handle error", result.error.data);
													} else {
														if(result && result.data) {
															preDefValueObjects[input.value] = result.data.PreDefAttributeChildren[input.value];
															dojo.attr(divNode, "predefobjectid", result.data.PreDefAttributeChildren[input.value]);
														}
													}
												});
											});
										}
										else if (attrType == "PreDefMultiString") {
											// get value nodes of this attribute
											// foreach value block of the attributewidget
											dojo.forEach(widget.valueContainerNode.children, function(divNode) {
												dojo.query("input[name^='AttributeName'][type$='text']", divNode).forEach(function(inputNode) {
													// request skeleton
													var params = {
														'ChangeAction'	 : 'SavePreDefAttributes',
														'ObjectID'			 : att.ObjectID,
														'NewAlias'			 : inputNode.value,
														'NewValueString' : inputNode.value, // only one value for both in wizard
														'NewPosition'		: 9999,
														'Save'					 : 1,
														'ErrorAction'		: 'JSONViewResponse'
													};
													// send save request for this attribute containing the values
													var result = new epages.io.Json().loadSync('?', params);
													if(result && result.error && result.error.data){
														console.warn("todo: handle error", result.error.data);
													} else {
														if(result && result.data) {
															preDefValueObjects[params.NewAlias] = result.data.PreDefAttributeChildren[params.NewAlias];
															dojo.attr(divNode, "predefobjectid", result.data.PreDefAttributeChildren[params.NewAlias]);
														}
													}
												});
											});
										}
										else if (attrType == "PreDefLocalizedString" || attrType == "PreDefMultiLocalizedString" || attrType == "PreDefCustomerString") {
											// get value nodes of this attribute
											// foreach value block of the attributewidget
											dojo.forEach(widget.valueContainerNode.children, function(divNode) {
												var inputNodes = dojo.query("input[name^='AttributeName'][type$='text']", divNode);
												// primary language input
												var firstInputNode = inputNodes.shift();
												var nameValues = firstInputNode.name.split(':');
												if(nameValues[0] != "AttributeName") {
													console.warn("error: attribute name did not match", nameValues[0]);
													return;
												}
												// request skeleton
												var params = {
													'ChangeAction'	 : 'SavePreDefAttributes',
													'ObjectID'			 : att.ObjectID,
													'NewAlias'			 : undefined,
													'NewPosition'		: 9999,
													'Save'					 : 1,
													'ErrorAction'		: 'JSONViewResponse'
												};
												// multiple value fields as arrays
												var NewValueLocStrings = [];
												var NewLanguageIDs = [];
												// fetch langid
												NewLanguageIDs.push(nameValues[1]);
												// assign value to alias (first language-assigned name used as alias) and push value (for primary lang value)
												NewValueLocStrings.push(firstInputNode.value);
												params.NewAlias = firstInputNode.value;

												// all further inputs for all the other languages:
												inputNodes.forEach(function(input) {
													var nameValues = input.name.split(':');
													if(nameValues[0] == "AttributeName") {
														var valueLangId = nameValues[1];
														NewValueLocStrings.push(input.value);
														NewLanguageIDs.push(valueLangId);
													}
												});
												params.NewValueLocString = NewValueLocStrings;
												params.NewLanguageID = NewLanguageIDs;
												// send save request for this attribute containing the values
												var result = new epages.io.Json().loadSync('?', params);
												if(result && result.error && result.error.data){
													console.warn("todo: handle error", result.error.data);
												} else {
													if(result && result.data) {
														preDefValueObjects[params.NewAlias] = result.data.PreDefAttributeChildren[params.NewAlias];
														dojo.attr(divNode, "predefobjectid", result.data.PreDefAttributeChildren[params.NewAlias]);
													}
												}
											});
										}
									} // end if attr type
								});
							});
						}
						// assign selected values to the resource
						if(this.containerNode.children && this.containerNode.children.length > 0) {
							var params = {
								'ChangeAction'	 : 'Save',
								'ObjectID'			 : ObjectID,
								'ErrorAction'		: 'JSONViewResponse',
								'HandleFilesAsStrings' : 1
							};
							var altAttributeIDs = [];
							dojo.forEach(this.containerNode.children, function(widgetNode) {
								var widget = $$(widgetNode.id);
								if(widget && widget.alias && widget.data && widget.data.id) {
									var attrType = widget.data.type;
									// fetch the selected / entered value and assign it to the resource object
									if (attrType == "String" || attrType == "Money" ||
											attrType == "Integer" || attrType == "Float" ||
											attrType == "DateTime" || attrType == "Date" || attrType == "Time" || attrType == "File") {
										params[widget.alias] = [];
										dojo.forEach(widget.valueContainerNode.children, function(divNode) {
											dojo.query("input[name^='AttributeName'][type$='text']", divNode).forEach(function(input) {
												params[widget.alias].push(input.value);
											});
										});
									}
									else if (attrType == "Boolean") {
										params[widget.alias] = [];
										dojo.forEach(widget.valueContainerNode.children, function(divNode) {
											dojo.query("input[name^='AttributeName'][type$='radio']", divNode).forEach(function(input) {
												if(input.checked) {
													params[widget.alias].push(input.value);
												}
											});
										});
									}
									else if(attrType == "LocalizedString"	|| attrType == "LocalizedFile") {
										// needs LanguageID value for each string!
										params[widget.alias] = [];
										params['LanguageID'] = [];
										dojo.forEach(widget.valueContainerNode.children, function(divNode) {
											dojo.query("input[name^='AttributeName'][type$='text']", divNode).forEach(function(input) {

												var nameValues = input.name.split(':');
												if(nameValues[0] != "AttributeName") {
													console.warn("error: attribute name did not match", nameValues[0]);
													return;
												}
												var valueLangId = nameValues[1];
												params[widget.alias].push(input.value);
												params['LanguageID'].push(valueLangId);
											});
										});
									}
									// predef radio values: we need the object ids of the predefattributes
									else if(attrType == "PreDefString" || attrType == "PreDefLocalizedString") {
										// needs LanguageID value for each string!
										params[widget.alias] = [];
										dojo.forEach(widget.valueContainerNode.children, function(divNode) {
											dojo.query("input[name^='RadioAttributeName'][type$='radio']", divNode).forEach(function(radioInput) {
												var preDefObjectID = dojo.attr(divNode, "predefobjectid");
												if(radioInput.checked && preDefObjectID) {
													params[widget.alias].push(preDefObjectID);
												}
											});
										});
									}
									// predef multi values with checkboxes
									else if(attrType == "PreDefCustomerString" || attrType == "PreDefMultiLocalizedString" || attrType == "PreDefMultiString") {
										params[widget.alias] = [];
										dojo.forEach(widget.valueContainerNode.children, function(divNode) {
											dojo.query("input[name^='CheckboxAttributeName'][type$='checkbox']", divNode).forEach(function(cbInput) {
												var preDefObjectID = dojo.attr(divNode, "predefobjectid");
												if(cbInput.checked && preDefObjectID) {
													params[widget.alias].push(preDefObjectID);
												} else {
													params[widget.alias].push('');
												}
											});
										});
									}

									// only add change attribute id if value will be assigned
									if(params[widget.alias] != undefined) {
										altAttributeIDs.push(widget.data.id);
									}

								} else {
									console.warn("error while assigning attribute values", "attr alias", widget.alias, "attr objectid", widget.data.id);
								}
							});
							if(altAttributeIDs.length > 0) {
								params['AltAttributeID'] = altAttributeIDs;
								// send one request for all values
								var result = new epages.io.Json().loadSync('?', params);
								if(result && result.error && result.error.data){
									console.warn("todo: handle error", result.error.data);
								}
							}
						}
					} // end if json result data
					if(saveSubscribe) {
						dojo.unsubscribe(saveSubscribe);
					}
				}));
			}
			else if(saveSubscribe) {
				dojo.unsubscribe(saveSubscribe);
			}

		}
	});