var CategoryMenu = Class.create();
CategoryMenu.prototype = {
	initialize: function(el)
	{
		this.el = el;
		
		this.category_records = [];
		this.display = false;
		this.ajax = false;
		
		this.last_update_el = new Element('div').addClassName('text_bold text_smaller').update('&nbsp;');
		
		// Category Tree
		this.tree_area_el = new Element('div').addClassName('container_2 view');
		this.tree_el = new Element('div');
		this.tree = new CategoryTree(this.tree_el);
		this.tree.yui_tree.collapseAll();
		this.tree_area_el.insert(new Element('div').addClassName('common_header').update('Category')).insert(this.last_update_el).insert(this.tree_el);
		
		// Category Product Display
		this.category_product_display = false;
		
		// Download Area
		this.download_area_el = new Element('div').addClassName('container_2 view');
		this.download_body_el = new Element('div');
		this.download_area_el.insert(new Element('div').addClassName('common_header').update('Download')).insert(this.download_body_el);
		
		this.el.insert(this.tree_area_el).insert(this.download_area_el);
		
		// Events
		this.tree.observe('label_click', function(node)
		{
			this.jump(node.data.id);
			this.collapseOtherBranches(node);
			this.el.fire('CategoryMenu:click');
			
		}.bindAsEventListener(this));
		this.tree.observe('node_expand', function(node)
		{
			this.collapseOtherBranches(node);
			
		}.bindAsEventListener(this));
	},
	render: function()
	{
		// Category
		this.category_records.each( function(category_record, category_record_index)
		{
			this.tree.insertNode(category_record.Category);
			
		}.bind(this));
		this.tree.render();
		
		// Download
		this.download_body_el.update('');
		this.download_body_el.update('<a href="/page/download/pricelist_csv"><img src="/img/techexcel/pricelist_excel_icon.jpg" title="Price List (Excel CSV)" alt="Price List (Excel CSV)" /></a>');
		
	},
	jump: function(category_id)
	{
		// Setup category_product_display
		if ( this.display != false && this.category_product_display == false )
		{
			this.ajax = new AjaxController();
			this.category_product_display = new CategoryProductDisplay(this.display);
		}
		
		if ( this.ajax != false && this.category_product_display != false )
		{
			this.category_product_display.showLoading(true);
			
			var data = '';
			var callback = {
				success: function(o)
				{
					var ajax_response = YAHOO.lang.JSON.parse(o.responseText);
					
					this.category_product_display.category_menu = this;
					this.category_product_display.category_record = ajax_response.category_record;
					this.category_product_display.product_records = ajax_response.product_records;
					this.category_product_display.parent_category_records = ajax_response.parent_category_records;
					this.category_product_display.children_category_records = ajax_response.children_category_records;
					this.category_product_display.render();
					
					this.category_product_display.showLoading(false);
					
					this.el.fire('CategoryMenu:load');
					
				}.bind(this)
			};
			this.ajax.request('POST', '/jx/getProductRecords/'+category_id, callback, data);
		}
	},
	collapseOtherBranches: function(node)
	{
		// Collapse non-branch nodes
		var base_node = node;
		while ( !base_node.parent.isRoot() )
		{
			base_node = base_node.parent;
		}
		this.tree.yui_tree.getRoot().children.each( function(each_node, each_node_index)
		{
			if ( each_node != base_node )
			{
				each_node.collapse();
				each_node.collapseAll();
			}
		}.bind(this));
	},
	observe: function(event_string, func)
	{
		switch (event_string)
		{
			case 'loaded':
				this.el.observe('CategoryMenu:load', func);
				break;
				
			case 'clicked':
				this.el.observe('CategoryMenu:click', func);
				break;
		}
	}
}

var CategoryProductDisplay = Class.create();
CategoryProductDisplay.prototype = {
	initialize: function(el)
	{
		this.el = el;
		
		this.category_menu = false;
		
		this.product_records = [];
		this.category_record = false;
		this.parent_category_records = [];
		this.children_category_records = [];
		
		this.header_el = new Element('div').addClassName('header');
		this.subcategories_view_el = new Element('div').addClassName('subcategories_view');
		this.category_product_table_el = new Element('div').addClassName('category_product_table');
		
		// Loading screen
		this.loading_el = new Element('div').addClassName('view text_align_center').update('<img src="/img/loading.gif" /><br />Loading, Please wait...');
		
		// Category Product Table
		this.category_product_table = new CategoryProductTable(this.category_product_table_el);
		this.category_product_table.category_product_display = this;
		
		this.el.insert(this.header_el).insert(this.subcategories_view_el).insert(this.loading_el).insert(this.category_product_table_el);
	},
	clear: function()
	{
					
		this.header_el.update('');
		this.subcategories_view_el.update('');
	},
	showLoading: function(flag)
	{
		(flag ? ( this.loading_el.show() & this.category_product_table_el.hide() ) : (this.loading_el.hide() & this.category_product_table_el.show() ) );
	},
	render: function()
	{
		this.clear();

		// Header
		var header_h1_el = new Element('h1').update(this.category_record.Category.label);
		
		// Parent categories
		var parent_categories_view_el = new Element('div').addClassName('text_align_right').update('&nbsp;'); var delim = '';
		this.parent_category_records.each( function(parent_category_record, parent_category_record_index)
		{
			var parent_category_link_el = new Element('a', {href:'#'}).update(parent_category_record.Category.label);
			
			parent_categories_view_el.insert(new Element('span').update(delim)).insert(parent_category_link_el);
			delim = ' &lt; ';
			
			// Events
			parent_category_link_el.observe('click', function(event)
			{
				if ( this.category_menu != false )
				{
					this.category_menu.jump(parent_category_record.Category.id);	
				}
			}.bindAsEventListener(this));
			
		}.bind(this));
		this.header_el.insert(header_h1_el).insert(parent_categories_view_el);
		
		
		// Subcategories
		var subcategories_ul_el = new Element('ul');
		this.children_category_records.each( function(children_category_record, children_category_record_index)
		{
			var subcategory_link_el = new Element('a', {href:'#'}).update(children_category_record.Category.label);
			var subcategory_li_el = new Element('li').insert(subcategory_link_el);
			subcategories_ul_el.insert(subcategory_li_el);
			
			// Events
			subcategory_link_el.observe('click', function(event)
			{
				if ( this.category_menu != false )
				{
					this.category_menu.jump(children_category_record.Category.id);	
				}
			}.bindAsEventListener(this));
			
		}.bind(this));
		this.subcategories_view_el.insert(subcategories_ul_el);
		
		// Render table of products
		this.category_product_table.product_records = this.product_records;
		this.category_product_table.render();
	}
};

var CategoryProductTable = Class.create();
CategoryProductTable.prototype = {
	initialize: function(el)
	{
		this.el = el.addClassName('text_smaller');
		this.category_product_display = false;
		
		this.product_records = [];
		
		this.table_sorter = false;
		this.table_el = new TableElement({num_cols: 7, num_rows:1}).addClassName('table');
		this.table_el.getCell(0, 0).addClassName('table_header').update('Product');
		this.table_el.getCell(0, 1).addClassName('table_header width_20').update('Manufacturer');
		this.table_el.getCell(0, 2).addClassName('table_header width_15').update('Warranty');
		this.table_el.getCell(0, 3).addClassName('table_header width_20 text_align_right').update( root.display_gst ? 'RRP InGST' : 'ExGST' );
		this.table_el.getCell(0, 4).addClassName('table_header width_5 text_align_right').update('&nbsp;');
		this.table_el.getCell(0, 5).addClassName('table_header width_10 text_align_right').update('&nbsp;');
		this.table_el.getCell(0, 6).addClassName('table_header width_10 text_align_right').update('Actions');
		
		this.rows = new Hash();
		
		this.counter_row_el = new Element('div').addClassName('view');
		
		this.el.insert(this.table_el).insert(this.counter_row_el);
		
	},
	clear: function()
	{
		if ( this.table_sorter != false )
		{
			this.table_sorter.clearEvents();
			this.table_sorter = false;
		}
		this.table_el.setNumRows(1);
		this.rows = new Hash();
	},
	render: function()
	{
		this.clear();
		
		this.table_el.setNumRows(this.product_records.length+1);
		this.product_records.each( function(product_record, product_record_index)
		{
			var product_description_link_el = new Element('a', {href: '#'}).update(product_record.Product.description);
			var warranty_link_el = new Element('a', {href: '#'}).update(product_record.Product.warranty);
			var add_to_cart_icon_el = new Element('span').addClassName('add_to_cart_icon image_button').update('<img src="/img/techexcel/cart_add_icon.gif" title="Add To Cart" alt="Add To Cart" />');
			var tick_icon_el = new Element('span').addClassName('tick_icon').update('<img src="/img/techexcel/tick.gif" title="Added" alt="Added" />');
			var price_change_icon_el = new Element('span').update('-');
			var price_last_icon_el = new Element('span').update('&nbsp;');
			
			if ( product_record.Price.length == 1 && new Date().getUSDate(product_record.Price[0].datetime).shift( 7 * 24 * 60 * 60) > new Date() )
			{
				// New
				this.table_el.getRow(product_record_index + 1).addClassName('product_new');
				price_last_icon_el.update('<img src="/img/techexcel/new.gif" />');
			}
			else if ( product_record.Price.length > 1 )
			{
				// Compare is less
				if ( product_record.Price[0][root.current_use_price] < product_record.Price[1][root.current_use_price] )
				{
					this.table_el.getRow(product_record_index + 1).addClassName('product_price_down');
					price_change_icon_el.update('<img src="/img/techexcel/down.gif" /> $'+( root.display_gst ? number_format((product_record.Price[1][root.current_use_price] - product_record.Price[0][root.current_use_price]) * 1.1, 2) : number_format(product_record.Price[1][root.current_use_price] - product_record.Price[0][root.current_use_price], 2) )+' ');
				}
			}
			
			// Special, Clearance
			var product_status = ( product_record.Product.product_status != '' ? YAHOO.lang.JSON.parse(product_record.Product.product_status) : {on_special: 'false', clearance: 'false'} );
			if ( product_status.on_special == 'true' )
			{
				this.table_el.getRow(product_record_index + 1).addClassName('product_special');
				price_last_icon_el.update('<img src="/img/techexcel/special.gif" />');
			}
			if ( product_status.clearance == 'true' )
			{
				this.table_el.getRow(product_record_index + 1).addClassName('product_clearance');
				price_last_icon_el.update('<img src="/img/techexcel/clearance.gif" />');
			}
			
			this.rows.set(product_record.Product.id, this.table_el.getRow(product_record_index + 1));
			
			this.table_el.getCell(product_record_index + 1, 0).addClassName('table_field nowrap').update(product_description_link_el);
			this.table_el.getCell(product_record_index + 1, 1).addClassName('table_field nowrap').update(product_record.Manufacturer.name);
			this.table_el.getCell(product_record_index + 1, 2).addClassName('table_field nowrap').update(warranty_link_el);
			this.table_el.getCell(product_record_index + 1, 3).addClassName('table_field nowrap text_align_right').update('$'+( root.display_gst ? number_format(product_record.Price[0][root.current_use_price] * 1.1, 2) : number_format(product_record.Price[0][root.current_use_price], 2) ) );
			this.table_el.getCell(product_record_index + 1, 4).addClassName('table_field nowrap text_align_right').insert(price_change_icon_el);
			this.table_el.getCell(product_record_index + 1, 5).addClassName('table_field nowrap').update(price_last_icon_el);
			this.table_el.getCell(product_record_index + 1, 6).addClassName('table_field nowrap text_align_right').insert(add_to_cart_icon_el).insert(tick_icon_el.hide());
			
			// Events
			product_description_link_el.observe('click', function(event)
			{
				if ( root.product_viewer != false )
				{
					root.product_viewer.display(product_record);
				}
			}.bindAsEventListener(this));
			warranty_link_el.observe('click', function(event)
			{
				if ( root.warranty_viewer_el != false )
				{
					lightbox.display('warranty_viewer');
				}
			}.bindAsEventListener(this));
			add_to_cart_icon_el.observe('click', function(event)
			{
				if ( confirm('Add "'+product_record.Product.description+'" into cart?') )
				{
					// Global shopping cart
					if ( root.cart != false )
					{
						root.cart.addProduct(product_record);
					}
					if ( root.cart_display != false )
					{
						root.lightbox.display('cart_display');
					}	
				}
			}.bindAsEventListener(this));
			
		}.bind(this));
		
		// Sortable
		this.table_sorter = new TableSorter(this.table_el);
		this.table_sorter.compare_func = this.tableSorterCompareFunc;
		
		this.counter_row_el.update('<br />'+( this.product_records.length == 0 ? 'No' : this.product_records.length )+' products found in this category.');
		
		this.el.fire('CategoryProductTable:render');
	},
	clearFlag: function()
	{
		this.rows.each( function(row_pair, row_pair_el)
		{
			row_pair.value.removeClassName('in_cart');
			row_pair.value.select('.add_to_cart_icon').invoke('show');
			row_pair.value.select('.tick_icon').invoke('hide');
			
		}.bind(this));
	},
	setFlag: function(flag, product_id)
	{
		this.rows.each( function(row_pair, row_pair_el)
		{
			if ( row_pair.key == product_id )
			{
				switch(flag)
				{
					case 'in_cart':
						row_pair.value.addClassName('in_cart');
						row_pair.value.select('.add_to_cart_icon').invoke('hide');
						row_pair.value.select('.tick_icon').invoke('show');
						break;
						
					default:
						break;
				}
				throw $break;
			}
		}.bind(this));
		
	},
	tableSorterCompareFunc: function(src_row, dest_row)
	{
		var result = 0;
		var src_value = this._getMostDeepValue(src_row.cells[this.current_selected_col_index]).nodeValue;
		var dest_value = this._getMostDeepValue(dest_row.cells[this.current_selected_col_index]).nodeValue;
		
		switch( this.current_selected_col_index )
		{	
			case 3:
			case '3':
				src_value = parseFloat(src_value.substring(1).replace(/,/g, ''));
				dest_value = parseFloat(dest_value.substring(1).replace(/,/g, ''));
				break;
				
			case 4:
			case '4':
				if ( src_row.hasClassName('product_price_down') )
				{
					src_value = parseFloat(src_row.cells[this.current_selected_col_index].innerHTML.stripTags().strip().substring(1).replace(/,/g, ''));
				}
				else
				{
					src_value = -1;
				}
				if ( dest_row.hasClassName('product_price_down') )
				{
					dest_value = parseFloat(dest_row.cells[this.current_selected_col_index].innerHTML.stripTags().strip().substring(1).replace(/,/g, ''));
				}
				else
				{
					dest_value = -1;
				}
				break;
				
			case 5:
			case '5':
				break;
				
			default:
				break;
		}
		if ( src_value < dest_value )
		{
			result = -1;
		}
		else if ( src_value == dest_value )
		{
			result = 0;
		}
		else if ( src_value > dest_value )
		{
			result = 1;
		}
		return result;
	},
	observe: function(event_string, func)
	{
		switch (event_string)
		{
			case 'rendered':
				this.el.observe('CategoryProductTable:render', func);
				break;
		}
	}
};

