/**
* @author Ken Hill <http://www.norwood.com>
* @copyright Norwood Promotional Products <http://www.norwood.com>
* @package Norwood.com
* @require prototype.js, livepipe.js, window.js
* 
* Handle upkeep of product selections for Compare, Export, etc. tool use.
*/

if(typeof(Prototype) == "undefined")
	throw "Selection Manager requires Prototype to be loaded.";
if(typeof(Object.Event) == "undefined")
	throw "Selection Manager requires Object.Event to be loaded.";

var more_box_btns = new Array();

SelectionManager = Class.create({
	// Variable Inits
	debug: false,
	selected: new Array(), // Contains product ids of selected items
	
	compareURL: "/special/compare/Compare Products/",
	builderURL: "/special/flyerbuilder/create/",
	displayURL: "/selection/Show Selection/",
	favoritesURL: "/special/myfavorites/My Favorites",
	
	ie6msg: "This feature requires a newer version of your browser. For your convenience we have provided links to popular browsers at the top of this page.",
	
	initialize: function(skip_init) {
		this.debug = debug;
		
		if (!skip_init) {
			// Add task listeners
			$$('.to_compare').each( function (elm) {
				elm.observe('click', function(event) {
					this.compareSelection(event);
				}.bindAsEventListener(this));
			}.bind(this));
			$$('.to_flyer_builder').each( function(elm) {
				elm.observe('click', function(event) {
					this.createFlyer(event);
				}.bindAsEventListener(this));
			}.bind(this));
			$$('.clear_selection').each( function(elm) {
				elm.observe('click', function(event) {
					this.clearSelection(event);
				}.bindAsEventListener(this));
			}.bind(this));
			
			// Add "More" button window actions
			/* Note: For this to work, the show_more elements must have an href attribute with a junk (#abc) link in it */
			$$('.show_more').each( function(elm) {
				if (is_ie7 || is_ie6) {
					var oLeft = -1;
					var oTop = 18;
				}
				else {
					var oLeft = 0;
					var oTop = 19;
				}
				
				more_box_btns.push(new Control.Window(elm, {
			        position: 'relative',
			        offsetLeft: oLeft,
			        offsetTop: oTop,
			        className: 'show_more_box',
			        slide: true,
			        //iframeshim: false,
			        closeOnClick: elm,
			        
			        beforeOpen: function() {
						// Test if already open, if so, don't try to open again
		        		if ($('show_more_src') != null)
		        			throw $break;
		        		
		        		// TODO: Hide Show Selection btn on the Show Selection page
		        		var more_menu = Builder.node('div', {id: 'show_more_src'}, [
		        			Builder.node('div', {id: 'more_actions_btns'}, [
		        				Builder.node('a', {id: 'show_selection_a', className: 'show_selection anchor_button'}, "Show Selected"),
		        				Builder.node('a', {id: 'select_all_a', className: 'select_all_btn anchor_button'}, "Select All"),
		        				Builder.node('a', {id: 'deselect_all_a', className: 'deselect_all_btn anchor_button'}, "Deselect All")
		        			])
		        		]);
		        		
		        		this.container.insert(more_menu);
		        		
		        		// Add button actions
		        		$('show_selection_a').observe('click', function(event) {
		        			more_box_btns.each(function(obj) { 
			        			obj.close();
				        	});
							sel_mgr.showSelection(event);
						});
		    			$('select_all_a').observe('click', function(event) {
		    				more_box_btns.each(function(obj) { 
			        			obj.close();
				        	});
		    				sel_mgr.selectAll(event);
		    			});
		    			$('deselect_all_a').observe('click', function(event) {
		    				more_box_btns.each(function(obj) { 
			        			obj.close();
				        	});
		    				sel_mgr.deselectAll(event);
		    			});
		        		
		        		// Close any open boxes
			            detail_panes.each(function(obj) { 
			            	obj.close();
			            });
			            favorites_menus.each(function(obj) { 
			            	obj.close();
			            });
			            more_box_btns.each(function(obj) { 
			            	obj.close();
			            });
			        },
			        
			        beforeClose: function() {
			        	Effect.SlideUp(this.container, {
							duration: 0.5,
							afterFinish: function(e) {
			        			if ($('show_more_src') != null)
			        				$('show_more_src').remove();
			        		}
						});
			        }
				}));
			});
			
			more_box_btns.each( function (elm) {
				//elm.container.insert($('show_more_src'));
			});
			
			$$('.prod_select').each( function (elm) {
			    elm.observe('click', function(event, elm) {
			    	var pid = elm.id.replace("select-", "");
			    	this.toggleSelection(pid);
			    }.bindAsEventListener(this, elm));
		    }.bind(this));
		
			this.getSelection();
		}
	},
	
	// Add a selection to the selected list (AJAX)
	toggleSelection: function(pid) {
		new Ajax.Request('/ajax.php',{
			method: 'get',
			parameters: {
				requestType: 'productListing',
				task: 'updateSelection',
				action: 'toggle',
				pid: pid
			},
			onSuccess: function(response) {
				var res = response.responseJSON;
				if (res.selection != null) {
					this.selected = res.selection;
					this.highlightSelection();
				}
				//else
				//	this.clearHighlights();
			}.bind(this),
			onFailure: function(response) {
				this.highlightSelection();
				if (this.debug) alert("AJAX call failed for toggleSelection ");
			}.bind(this)
		});
	},
	
	// Get selections from server (AJAX)
	getSelection: function () {
		new Ajax.Request('/ajax.php',{
			method: 'get',
			parameters: {
				requestType: 'productListing',
				task: 'getSelection'
			},
			onSuccess: function(response) {
				var res = response.responseJSON;
				
				if (res.selection != null) {
					this.selected = res.selection;
					this.highlightSelection();
				}
				else
					this.clearHighlights();
			}.bind(this),
			onFailure: function(response) {
				if (this.debug) alert("AJAX call failed for getSelection ");
			}.bind(this)
		});
	},
	
	// Remove all products from selection (AJAX)
	// Deprecated?
	clearSelection: function (event) {
		if (this.selected.length == 0) return;
		
		// Verify user wants to clear
		if (confirm("Are you sure you want to clear all selected products?")) {
			new Ajax.Request('/ajax.php',{
				method: 'get',
				parameters: {
					requestType: 'productListing',
					task: 'clearSelection'
				},
				onSuccess: function(response) {
					this.selected = new Array();
					this.clearHighlights();
				}.bind(this),
				onFailure: function(response) {
					if (this.debug) alert("AJAX call failed for clearSelection ");
				}.bind(this)
			});
		}
	},
	
	selectAll: function (event) {
		var pids = Array();
		
		// Get PIDs of all products on page
		$$('.searchResults').each(function (elm) {
			var pid = elm.id.replace("prod-","");
			pids.push(pid);
		}.bind(pids));
		
		pids = pids.join(',');
		
		new Ajax.Request('/ajax.php',{
			method: 'get',
			parameters: {
				requestType: 'productListing',
				task: 'updateSelection',
				action: 'select_all',
				pids: pids
			},
			onSuccess: function(response) {
				var res = response.responseJSON;
				if (res.selection != null) {
					this.selected = res.selection;
					this.highlightSelection();
				}
			}.bind(this),
			onFailure: function(response) {
				if (this.debug) alert("AJAX call failed for selectAll");
			}.bind(this)
		});
	},
	
	deselectAll: function (event) {
		var pids = Array();
		
		// Get PIDs of all products on page
		$$('.searchResults').each(function (elm) {
			var pid = elm.id.replace("prod-","");
			pids.push(pid);
		}.bind(pids));
		
		pids = pids.join(',');
		
		new Ajax.Request('/ajax.php',{
			method: 'get',
			parameters: {
				requestType: 'productListing',
				task: 'updateSelection',
				action: 'deselect_all',
				pids: pids
			},
			onSuccess: function(response) {
				var res = response.responseJSON;
				if (res.selection != null) {
					this.selected = res.selection;
					this.highlightSelection();
				}
			}.bind(this),
			onFailure: function(response) {
				if (this.debug) alert("AJAX call failed for deselectAll");
			}.bind(this)
		});
	},
	
	clearHighlights: function () {
		$$('.comparing').each( function (e) {
		    e.removeClassName('comparing');
		    
		    e.down('.prod_select').firstChild.data = "Select Item";
	    });
	},
	
	// Remove all highlighted items then add highlights for selected items
	highlightSelection: function () {
		this.clearHighlights();
		
		this.selected.each( function (pid) {
			if ($('prod-'+pid) != null) {
				$('prod-'+pid).addClassName('comparing');
				
				$('prod-'+pid).down('.prod_select').firstChild.data = "Deselect Item";
				
				//alert($('prod-'+pid).down('.prod_select').outerHTML);
			}
		});
	},
	
	// Tasks
	// setTimeout fixes an IE bug with redirection
	compareSelection: function() {
	    //window.location = this.compareURL;
		var url = this.compareURL;
		setTimeout(function() { window.location = url; }, 0);
	},
	createFlyer: function() {
		//window.location = this.builderURL;
		if (is_ie6) {
			alert(this.ie6msg);
		}
		else {
			var url = this.builderURL;
			setTimeout(function() { window.location = url; }, 0);
		}
	},
	showSelection: function() {
		var url = this.displayURL;
		setTimeout(function() { window.location = url; }, 0);
	}
});