var ProductSelectionWatcher = Class.create();

ProductSelectionWatcher.prototype = {
	initialize: function(className, toolTipId, options) {
		this.options = Object.extend({
			limit: 5,
			timeout: 5000,
			toolTipOptions: {}
		}, options || {});
		
		var toolTipOptions = Object.extend({
			followMouse: false,
			toolTipId: toolTipId,
			offsetx: 5,
			offsety: -140
		}, this.options.toolTipOptions || {});


		this.selectedCount = 0;
		this.className = className;
		this.toolTip = new ToolTip(toolTipOptions);
		this.checkBoxes = getElementsByClassName(document, className);

		// Getting cookie in initialization to pre-select all products saved in cookie
		var cookieValue = getCookie(this.className);
		var requestedUrl = window.location.href;
		// Getting URL to save to compare if is the current url
		var urlToSave;
		if (requestedUrl.indexOf("pager.offset=")>-1)
			urlToSave = requestedUrl.substr(0,requestedUrl.indexOf("pager.offset=")-1);
		else {
			urlToSave = requestedUrl;
		}
		// Getting value from cookie for the requested url, if has something.
		var savedProductIds = "";
		if (cookieValue!=null) {
			var cookieValueArray = cookieValue.split("|");						
			if (cookieValueArray[0] == urlToSave) {
				savedProductIds = cookieValueArray[1];				
			}
		}

		var tooltip = new ToolTip();
		for (var i = 0; i <  this.checkBoxes.length;i++ )
		{
			// pre-select all products saved in cookie
			if (savedProductIds!=null && savedProductIds!= "" && savedProductIds.indexOf(this.checkBoxes[i].value + "_")>-1) {
				this.checkBoxes[i].checked = true;
			}
			this.checkBoxes[i].onclick = this._onclick.bindAsEventListener(this);
		}
		
		// Initialize Compare Buttons 		
		existImgCompareButton = document.getElementById('imgCompareButton');
		if(existImgCompareButton != null)
		{
			this.imgCompare = document.getElementById('imgCompareButton').value;
			this.imgCompareGray = document.getElementById('imgCompareButtonGray').value;
			
			this.imgCompareText = document.getElementById('imgCompareText').value;
			this.imgCompareGrayText = document.getElementById('imgCompareGrayText').value;
			
			this.scriptFunction = document.getElementById('compareButtonFunction').value;
			this.initButton();
		}		
	},
	_onclick: function(e) {
		var cookieValue = getCookie(this.className);
		var requestedUrl = window.location.href;
		var extraProductsIds = "";
		var savedProductIds = "";
		var obj = e.target || e.srcElement;
		
		//alert("cookieValue: " + cookieValue);
		//alert("requestedUrl: " + requestedUrl);
		
		// Checking URL to save
		var urlToSave;
		//alert("has pager.offset parameter? " + (requestedUrl.indexOf("pager.offset=")>-1));
		if (requestedUrl.indexOf("pager.offset=")>-1)
			urlToSave = requestedUrl.substr(0,requestedUrl.indexOf("pager.offset=")-1);
		else {
			urlToSave = requestedUrl;
		}
		//alert("urlToSave: " + urlToSave);
	
		// Getting value from cookie for the requested url, if has something.
		if (cookieValue!=null) {
			var cookieValueArray = cookieValue.split("|");
			//alert("href is in cookieValue? " + (cookieValueArray[0] == urlToSave));						
			if (cookieValueArray[0] == urlToSave) {
				savedProductIds = cookieValueArray[1];				
				this.selectedCount = cookieValueArray[1].split("_").length -1;
				//alert("this.selectedCount: " + this.selectedCount);
				//alert("this.options.limit: " + this.options.limit);				
				//alert("The same url! Updating cookie value with new selected productIds! ");
				
				if( (obj.checked && this.selectedCount == 0) || (!obj.checked && this.selectedCount == 2) 
		     		|| (!obj.checked && this.selectedCount == 1)  ){
                    this.grayButton();
                }
				if( obj.checked && this.selectedCount == 1){
                    this.compareButton();
                }				
			}
		}else{
		   	this.grayButton();
        }
        
		//alert("savedProductIds: " + savedProductIds);					
	
		// Verifying if the selected item will be allowed or not
		var obj = e.target || e.srcElement;
		if (obj.checked && this.selectedCount == this.options.limit)
		{
			this._showToolTip(e);
			obj.checked = false;
			window.setTimeout(this._hideToolTip.bind(this), this.options.timeout);
		}

		// getting all product ids, checking if is already in the session cookie
		var allSelectedItems;
		for(x = 0; x < this.checkBoxes.length; x++) {
			// if was checked, has value and is not saved in cookie, so prepare to save in cookie
			if(this.checkBoxes[x].checked && this.checkBoxes[x].value!="" && savedProductIds.indexOf(this.checkBoxes[x].value+"_")==-1) {
			  extraProductsIds+=this.checkBoxes[x].value + "_";
			// if was UNchecked, has value and is saved in cookie, so prepare to remove from cookie
			} else if(!this.checkBoxes[x].checked && this.checkBoxes[x].value!="" && savedProductIds.indexOf(this.checkBoxes[x].value+"_")>-1) {
				var savedProductArray = savedProductIds.split("_");
				savedProductIds = "";
				for (y = 0; y < savedProductArray.length; y++) {
					if(savedProductArray[y] != this.checkBoxes[x].value) {
						savedProductIds+=savedProductArray[y] + "_";
					}
				}
				if (savedProductIds.length>0) {
					savedProductIds = savedProductIds.substring(0, savedProductIds.length-1);
				}
			}
		}

		// There are no products selected, then clear cookie value for current url;
		if (extraProductsIds + savedProductIds == "") {
			//alert("Deleting cookie!");
			deleteCookie(this.className);
		} else {
			cookieValue = urlToSave + "|" + extraProductsIds + savedProductIds;
			//alert("Setting cookie = " + cookieValue);
			setCookie(this.className,cookieValue);
		}
	},
	_showToolTip:function(e) {
		this.toolTip.show("", e);
	},
	_hideToolTip:function() {
		this.toolTip.hide();
	},
	
	// Initialize Buttons with apropriated images
    initButton:function(){
		
        var cookieValue = getCookie(this.className);  
        var requestedUrl = window.location.href;
		var extraProductsIds = "";
		var savedProductIds = "";        
        var checkSelectedCount;
        var urlToSave;
		
		if (requestedUrl.indexOf("pager.offset=")>-1)
			urlToSave = requestedUrl.substr(0,requestedUrl.indexOf("pager.offset=")-1);
		else {
			urlToSave = requestedUrl;
		}      
        if (cookieValue!=null) {
            var cookieValueArray = cookieValue.split("|");            						
            if (cookieValueArray[0] == urlToSave) {
                savedProductIds = cookieValueArray[1];				
                checkSelectedCount = cookieValueArray[1].split("_").length -1;
                              
                if(checkSelectedCount == 0 || checkSelectedCount == 1 ){
                    this.grayButton();
                }else{
                    this.compareButton();
                }
            }
        }else{            
            this.grayButton();
        }            
    },
	
	// Change button to Gray button
	grayButton:function(){
		var compareSelectedButtonTop = document.getElementById('compareSelectedButtonTop');
		var compareSelectedButton    =  document.getElementById('compareSelectedButton');
		
		existImgCompareButton = document.getElementById('imgCompareButton');
		if(existImgCompareButton != null)
		{
		    compareSelectedButtonTop.style.cursor = "default";
		    compareSelectedButton.style.cursor    = "default";  
		    
		    compareSelectedButtonTop.alt = this.imgCompareGrayText; 
	    	compareSelectedButton.alt    = this.imgCompareGrayText; 	
		    
		    compareSelectedButtonTop.title = ""; 
	        compareSelectedButton.title    = ""; 
		    
		    compareSelectedButtonTop.onclick = null;
		    compareSelectedButton.onclick    = null;
		    
		    compareSelectedButtonTop.src = this.imgCompareGray; 
		    compareSelectedButton.src    = this.imgCompareGray;             
		}	    
	},

	// Change button to blue button
    compareButton:function(){
		var compareSelectedButtonTop = document.getElementById('compareSelectedButtonTop');
		var compareSelectedButton    =  document.getElementById('compareSelectedButton');
		
		existImgCompareButton     = document.getElementById('imgCompareButton');
		if(existImgCompareButton != null)
		{
		    compareSelectedButtonTop.src = this.imgCompare; 
		    compareSelectedButton.src    = this.imgCompare;
		    
		    compareSelectedButtonTop.alt = this.imgCompareText; 
	    	compareSelectedButton.alt    = this.imgCompareText
	    	
	    	compareSelectedButtonTop.title = this.imgCompareText; 
	    	compareSelectedButton.title    = this.imgCompareText; ; 
		    
		    compareSelectedButtonTop.style.cursor = "pointer";
		    compareSelectedButton.style.cursor    = "pointer";
		    
		    compareSelectedButtonTop.onclick = function(){ eval(document.getElementById('compareButtonFunction').value); } 
		    compareSelectedButton.onclick    =  function(){ eval(document.getElementById('compareButtonFunction').value); }
		}	    
    }    
    
}