/****************************************************/
/*                                                  */
/*       Webshop Invoice Controller + Model         */
/*                                                  */
/****************************************************/

var WebshopProductClass = new Class({
	initialize: function (params) {
		this.setParams(params);
		this.bindFinderItemsEvents();
		this.bindSearchSortingEvents();
		this.updateProductListImages();
	},
	
	setParams: function (params) {
		this.params = params;
	},
	
		
	setView: function (view) {
		this.view = view;
	},
	/*-------------Search filter handlers    ----------*/
	/*  change src, set hidden field, form send 
				on server: set that hidden var also, and by it onload change image src
				NB! save that hidden parameter in session also! (default sorting let be by id (desc?))
			*/	
	bindSearchSortingEvents: function () {
		var params = [{'name': 'product_name_desc_sort',  'img': 'down'}, 
					  {'name': 'product_name_asc_sort',   'img': 'up'},
					  {'name': 'product_price_desc_sort', 'img': 'down'},
					  {'name': 'product_price_asc_sort',  'img': 'up'}];
		for (var i = 0; i < params.length; i++) {
			var img = $(params[i].name + '_img');
			if (img) { // at quick search page there are no sorting img
			// set events 
				var makeMouseDownFunction = function (param) {
					return function () {
						for (var k = 0; k < params.length; k++) {
							var is_selected  = (params[k].name == param.name) ? 1 : 0;
							var picture_name = params[k].img == 'up' ? ( is_selected ? 'up_pressed' : 'up') : ( is_selected ? 'down_pressed' : 'down');
							document.getElementById(params[k].name).value = is_selected;
							document.getElementById(params[k].name + '_img').src = '/accounting_res/images/' + picture_name + '.png';
						}
					}
				}
				img.addEvent('mousedown', makeMouseDownFunction(params[i]));
				img.addEvent('click', function () { 
					document.getElementById('product_search_filter_form').submit();
				});
			// set src
				var is_selected = document.getElementById(params[i].name).value == 1;
				var picture_name = params[i].img == 'up' ? ( is_selected ? 'up_pressed' : 'up') : ( is_selected ? 'down_pressed' : 'down');
				img.src = '/accounting_res/images/' + picture_name + '.png';
			}
		}	
	},
	
	updateProductListImages: function () {
		if (LANG == 'is') { 
			var b_buttons = $$('.item .buy');
			for (var i = 0; i < b_buttons.length; i++) {
				b_buttons[i].setStyle('background-image', 'url(/common/products/product_img/button_in_cart_is.gif)');
			}
			
			var b_buttons2 = $$('.product_buttons .buy');
			for (var i = 0; i < b_buttons2.length; i++) {
				b_buttons2[i].setStyle('background-image', 'url(/common/products/product_img/add_to_cart_is.png)');
			}
			
			$$('.add_to_wishlist img').setProperty('src', 'http://wishlist.notando.is/resources/images/love_it_small_is.png');
			
			var det_buttons = $$('.info');
			for (var i = 0; i < det_buttons.length; i++) {
				det_buttons[i].setStyle('background-image', 'url(/common/products/product_img/button_details_is.gif)');
			}
		}
	},
	
	
	
	/*-------------Finder items handlers    ----------*/
	
	bindFinderItemsEvents: function () {
		var b_buttons = $$('.buy'); // 'buy buttons' of items in finder list (including on_promotion div)
		if (typeof b_buttons != 'undefined' && b_buttons.length > 0) {
			for (var i = 0; i < b_buttons.length; i++) {
				var button = b_buttons[i];
				this.initializeWebshopPopup(button);
			}
		}	 
	},
	
	// initialize!	
	initializeWebshopPopup: function (button) {
		var id     = button.getProperty('common_id');
		var hash   = button.getProperty('rand_hash');
		var params = { 'button'   : button,
					   'id'       :'popup_' + id + '_' + hash,
					   'common_id': id
					 };
		if (button.getProperty('is_metacategory') == 1) {
			params.getRemoteData = this.loadAttributesData.bind(this);
			params.onCompleteHandler = this.initializeAttributesForm.bind(this);
		} else {
			params.common_name = button.getProperty('common_name');
			params.autohide = true;
			params.autohide_interval = this.params.autohide_interval;
			params.getRemoteData = this.loadProductData.bind(this);
			params.onCompleteHandler = this.addProduct.bind(this); // will call this.addProduct(response, popup, event)
		}
			
		var popup = WebshopInfoPopups.create(params);
	},
		
		
	initializeAttributesForm: function (data, popup) { // shoud be called for every metacategory onRemoteCall complete
		// TODO cope with all that - as i use only one product_list class and many popups - so have mess :(
		if (_getLength(data) > 0) { 
			this.view.createAttributesFormNode(data, popup);
			this.view.setAttributesByCategoryAttributes();
		} else {
			this.view.showEmptyDataError(popup);
		}
	},
	
	/*-------------- Metacategory filter functions    ----------*/
		
	loadFilteredMetacategoryData: function (type) {
		if (typeof this.attributes == 'undefined') { return; }
	// collect conditions	
		this.view.clearMessages();
		var conditions = this.view.collectAttributeFilterValues(this.attributes);
		if (!conditions || conditions.length == 0) {
			this.view.showError({'text': 'not_all_filters_selected'});
			return;
		}
	// remote call	
		var params = {
			'metacategory_id': this.common_id,
			'conditions' : 	   conditions,
			'warehouse_id':    this.params.warehouse_id,
			'client_id' :      this.client_id,
			'url':             "/products/get_filtered_info"
		};
		this.getRemoteData(params, function(responce) {
	// callback	 
			if (responce.info.id) {
				if (type == 'check_price') {
					this.view.updatePrice(responce.info.price);
				} else if (type == 'buy') {
					if (responce.info.on_stock >= 1 || responce.info.infinity_on_stock == 1 ) {
						responce.info.quantity = 1; // ???? it is right?
						var instance = this;
						this.loadProductData(responce.info.id, this.popup_id, function (info) {
							instance.addProduct(info); // Andrew's global function
						});
						this.view.showMessage({'text': 'product_added'});
					} else { // zero on stock
						this.view.showError({'text': 'no_product_for_attribute_set'});
					}
				}
			} else { // no at all
				this.view.showError({'text': 'no_product_for_attribute_set'});
			}
		}.bind(this));
	},
	
	// getRemote: metacategory case
	loadAttributesData: function (metacategory_id, popup_id, onCompleteHanlder) { // aux. move to another part
		if (parseInt(metacategory_id) > 0) {
			var params = {
				'metacategory_id': metacategory_id,
				'warehouse_id':  this.params.warehouse_id,
				'url': "/products/get_metacategory_info" 
			};
			this.getRemoteData(params, function(responce) {
			// as we do not create popup for every product item on page - we should re-initialize popup params 
				this.popup_id = popup_id
				this.common_id = metacategory_id;
				this.attributes = responce.attributes; 
				onCompleteHanlder(responce);
			}.bind(this));
		}
	},
	
	// getRemote: product case
	loadProductData: function (product_id, popup_id, onCompleteHanlder) {
		if (parseInt(product_id) > 0) {
			var wip = WebshopInfoPopups.get(popup_id); 
			wip.popup.setTitle(wip.common_name);	
			
			addProduct(product_id, function(responce) {
				this.popup_id = popup_id;// as we do not create popup for every product item on page - we should re-initialize popup params
				this.common_id = product_id;
			// NB! this function get Andrew's action XML responce!	
				var qty   = responce.responseXML.getElementsByTagName('count')[0].firstChild.data;
				var price = responce.responseXML.getElementsByTagName('price')[0].firstChild.data;
				var error = responce.responseXML.getElementsByTagName('error')[0];
				onCompleteHanlder({'quantity': qty, 'price': price, 'error': error});
				//this.addProduct({'quantity': qty, 'price': price, 'error': error});
			}.bind(this));
		}
	},
	
	addProduct: function (responce, popup, event) {
		var wip = WebshopInfoPopups.get(this.popup_id);
		this.view.initializeProductNode(wip.popup);

		if (responce.error) {
			this.view.showError({'text': 'zero_on_stock'}); 
		} else {
			updateShortCart(responce.quantity, responce.price);
			if (event) {
				moveBasket(event);
			}
			this.view.showMessage({'text': 'product_added'});
		}
		// set timeout to hide, update basket, if this page == basket => reload!
	},
	
	
	
	
	
	// common
	getRemoteData: function (params, onCompleteHandler) {	
		if (typeof params == 'object' && params != {} && typeof params.url != 'undefined') {		
			new Json.Remote(params.url, { method: 'post',
				onComplete: function(response) { 
					onCompleteHandler(response); 
				}
			}).send(params);
		}	
	}
	
});



/****************************************************/
/*                                                  */
/*           Webshop Invoice View                   */
/*                                                  */
/****************************************************/

var WebshopProductClassView = new Class({
	initialize: function (params) {
		this.params = params;
	},
	
	setModel: function (model) {
		this.model = model;
	},
	
  /*------------ Messages  ----------*/
  	
	showError: function (params) {
		//var popup = WebshopInfoPopups.get('popup_' + this.model.common_id);
		var popup = WebshopInfoPopups.get(this.model.popup_id);
		var msg = '';
		switch (params.text) {
			case 'no_product_for_attribute_set': 
				msg = 'Threre is no product with given set of attributes on stock'; break;
			case 'not_all_filters_selected': 
				msg = 'Please, select all filters'; break;
			case 'zero_on_stock': 
				msg = 'Sorry, there is no product items on stock. Contact us for product avaiability'; break; 
		}
		var node = popup.getNode();
		var errDiv = node.getElementsBySelector('div.error')[0];
		errDiv.setText(Locale.get(msg)); 
		errDiv.setStyle('display', 'block');
		popup.adjustHeight();
	},
	
	showMessage: function (params) {
		//var popup = WebshopInfoPopups.get('popup_' + this.model.common_id);
		var popup = WebshopInfoPopups.get(this.model.popup_id);
		var msg = '';
		switch (params.text) {
			case 'product_added': 
				msg = 'Product was successfully added to cart'; break;
		}
		var node = popup.getNode();
		var msgDiv = node.getElementsBySelector('div.message')[0];
		msgDiv.setText(Locale.get(msg)); 
		msgDiv.setStyle('display', 'block');
		popup.adjustHeight();
	},
	
	clearMessages: function () {
		var popup = WebshopInfoPopups.get(this.model.popup_id);
		var node = $(popup.getNode());
		
		var errDiv = node.getElementsBySelector('div.error')[0];
		errDiv.setText('');
		errDiv.setStyle('display', 'none');
		
		var msgDiv = node.getElementsBySelector('div.message')[0];
		msgDiv.setText('');
		msgDiv.setStyle('display', 'none');
		
		var priceDiv = node.getElementsBySelector('div.price')[0];
		priceDiv.setText('');
		popup.adjustHeight();
	},
	
	updatePrice: function (price) {
		var popup = WebshopInfoPopups.get(this.model.popup_id);
		var node = popup.getNode();
		var priceDiv = node.getElementsBySelector('div.price')[0];
		var text = price ? price + ' ' + this.model.params.currency_name: '';
		priceDiv.innerHTML = text;
		popup.adjustHeight();
	},
	
 	/*------------ Attributes   ----------*/
 		
	collectAttributeFilterValues: function (attributes) {
		var conditions = [];
		for (var i in attributes) {
			if (typeof attributes[i] == 'function') { continue; }
			var select = document.getElementById('meta_attributes_' + attributes[i].id);
			
			if (select.value == '') { return null; } // ! all conditions are required
			conditions.push({'attribute_id': attributes[i].id, 'value': select.value});
		}
		return conditions;
	},
	
	showEmptyDataError: function (popup) {
		var textNode = new Element('div', {'styles': {'padding': '20px 10px'}});
		var text = Locale.get("Error. Empty product list or attributes for this metaproduct");
		textNode.setText(text); 
		popup.appendChild(textNode);	
	},
	
	// Products
	
	initializeProductNode: function (popup) {
		var container = new Element('div', {'styles': {'padding': '10px'}});
		var err_div   = new Element('div', {'styles': {'color': 'red', 'padding': '20px 0px 20px 40px', 'display': 'none'}, 'class': 'error'});
		var msg_div   = new Element('div', {'styles': {'color': '#92ba20', 'font-weight': 'bold', 'padding': '20px 0px 20px 40px', 'font-size': '14px', 'display': 'none'}, 'class': 'message'});
		var price_div = new Element('div', {'styles': {'text-align' : 'center', 'font-weight': 'bold', 'font-size': '16px', 'color': '#92ba20'}, 'class': 'price'});
		
		container.appendChild(err_div);
		container.appendChild(msg_div);
		container.appendChild(price_div);
		
		popup.appendChild(container);
		popup.attributes_form_node = container; // crasy name. TODO: change it
	},
	
	// Attributes	

	createAttributesFormNode: function (data, popup) {
		var container = new Element('div', {'styles': {'padding': '10px'}});
		var err_div   = new Element('div', {'styles': {'color': 'red', 'padding': '20px 0px 20px 40px', 'display': 'none'}, 'class': 'error'});
		var msg_div   = new Element('div', {'styles': {'color': '#92ba20', 'font-weight': 'bold', 'padding': '20px 0px 20px 40px', 'font-size': '14px', 'display': 'none'}, 'class': 'message'});
		var price_div = new Element('div', {'styles': {'text-align' : 'center', 'font-weight': 'bold', 'font-size': '16px', 'color': '#92ba20'}, 'class': 'price'});
		var attr_div  = new Element('div', {'styles': {'text-align' : 'left'}, 'class': 'attributes'});
		var butt_div  = new Element('div', {'styles': {'text-align' : 'center', 'padding': '5px'}});
		
		var price_butt = new Element('a', {'href': 'javascript:;', 'styles': {'padding': '0px 10px'}});
		price_butt.setText(Locale.get('Check price'));
		price_butt.addEvent('click', function () { this.loadFilteredMetacategoryData('check_price'); }.bind(this.model));
		
		var buy_butt = new Element('a', {'href': 'javascript:;', 'styles': {'padding': '0px 10px'}});
		buy_butt.setText(Locale.get('Add to cart')); 
		buy_butt.addEvent('click', function () { this.loadFilteredMetacategoryData('buy'); }.bind(this.model));
		
		butt_div.appendChild(price_butt);
		butt_div.appendChild(buy_butt);
		attr_div.appendChild(this.createAttributesDomNode(data));
		
		container.appendChild(err_div);
		container.appendChild(msg_div);
		container.appendChild(price_div);
		container.appendChild(attr_div);
		container.appendChild(butt_div);
		
		popup.appendChild(container);
		popup.attributes_form_node = container;
		if (data.metacategory_name) { popup.setTitle(data.metacategory_name); }
	},
	
	clearNode: function (node) {
		// Remove all child nodes
		while (e.firstChild) e.firstChild.removeNode();
	},

	createAttributesDomNode: function (data) {
		var attributes = data.attributes;
		if (attributes) {
			var table = document.createElement('table');
			var tbody = document.createElement('tbody');			

			for (var i in attributes) {
				if (typeof attributes[i] == 'function') { continue; }
				var attr_i = attributes[i];
				
				var node = document.createElement('div');// TODO
				var select = document.createElement('select');
				select.style.width = '220px';
				select.id = "meta_attributes_" + attr_i.id;
				
				var option = new Element('option');
				option.value = '';
				option.setText(' - ');
				select.appendChild(option);
					
				for (var k = 0; k < attr_i.values.length; k++) {
					var option = new Element('option');
					option.value = attr_i.values[k];
					option.setText(attr_i.values[k]);
					select.appendChild(option);
				}
				if (attr_i.values.length == 1) {
					select.options[1].selected = 'selected';
					select.disabled = true;
				}
				node.appendChild(select);
				
				var tr = document.createElement('tr');
				var nameTd = new Element('td');
				nameTd.setText(attributes[i].name);
				tr.appendChild(nameTd);
				
				var nodeTd = new Element('td');
				nodeTd.setAttribute('nowrap', "nowrap");
				nodeTd.appendChild(node);
				tr.appendChild(nodeTd);
				
				tbody.appendChild(tr);
			}
			table.appendChild(tbody);
			return table;	
		}
		return null;
	},

	setAttributesByCategoryAttributes: function () {
		if (typeof this.model.attributes == 'undefined') { return; }
		var attr = this.model.attributes;
		for (var i in attr) {
			if (typeof attr[i] == 'function') { continue; }
			var select = document.getElementById('attributes_' + i); // we do not look for min/max as we require exact value
			if (select != null && typeof select.value != 'undefined') {
				if (attr[i].values.contains(select.value)) {
					var attr_select = document.getElementById('meta_attributes_' + i);
					attr_select.value = select.value;
				}	 
			}
		}	
	}
});

/***********************************/
/*                                 */
/*     WebshopProductClass factory */
/*                                 */
/***********************************/
WebshopProductClass.implement(new Options);
WebshopProductClass.implement(new Events);

var WebshopProductClasses = new Class({
	instances: {},

	create: function(params) {
		var instance = new WebshopProductClass(params);
		params.id = params.id ? params.id : 'invioce' + Math.round(100000 * Math.random());
		this.instances[params.id] = instance;
		return this.instances[params.id];
	},
	
	get: function(id) {
		if (!this.instances[id]) {
			throw new Error('There is no WebshopProductClass with id = "' + id + '"'); // TODO: check how that works, do we need special class for errors
		}
		return this.instances[id];
	}
});

var WebshopProductClasses = new WebshopProductClasses();
/**************************************/

	
function showAttributesFilterForm (el, is_hidden) {
	var l = $(el);
	if (!l) { return false; }
// define action (hide or show)	
	if (typeof is_hidden == 'undefined') {
		var is_hidden = l.getAttribute('is_filters_hidden');
	}
// change layout
	var div = $('product_filter_form_table');	
	if (is_hidden == 0) {
		l.setText(Locale.get('Show filters'));
		l.setAttribute('is_filters_hidden', 1);
		div.setStyle('display', 'none');
	} else {
		l.setText(Locale.get('Hide filters'));
		l.setAttribute('is_filters_hidden', 0);
		div.setStyle('display', 'block');
	}
	return false;// to not submit form
}	


function showGroupsForm (el) {
	var l = $(el);
	if (!l) { return false; }
	var is_hidden = l.getAttribute('is_groups_hidden');
	var groups = $('product_groups_list');
	if (is_hidden == 0) {
		l.setText(Locale.get('Show groups'));
		l.setAttribute('is_groups_hidden', 1);
		groups.setStyle('display', 'none');	
	} else {
		l.setText(Locale.get('Hide groups'));
		l.setAttribute('is_groups_hidden', 0);
		groups.setStyle('display', 'block');
	}
	return false;// to not submit form
}

function resetSearchFilters () {
	document.getElementById('reset_search_filters').value = 1;
	document.getElementById('product_search_filter_form').submit();
}


function _getLength (object) {
	var length = 0;
	for (var i in object) {
		if (typeof object[i] != 'function' && typeof object[i] != 'undefined') {
			length ++;
		} 
	}
	return length;
}
