/** The main javascript file for Product Selector Cookie
***	@author Ibrahim Bediz
***/

/* beginning of PSTCookie Class */

var PSTCookie = Class.create();
PSTCookie.prototype = {
	initialize: function(name, value, expire){
		this.name = name;
		this.value = value;
		this.expire = expire;
		this.cookie = new Cookie(name, value, expire);
	},
	
	setCustomCookie: function(name, value, expire){
		 var currentVal = this.cookie.getCookie(name);
		 var newVal = value;
		 var addNew = true;
	
		 if(currentVal != null && currentVal != ""){
			var currentValList = currentVal.split("&");
			for (var i=0; i < currentValList.length; i++) {
				if(value == currentValList[i] && addNew == true){
					addNew = false;
				}
			}
			if(addNew){
				newVal = currentVal+"&"+value; 		
			}else{
				newVal = currentVal;
			}
		 }else{
			newVal = value;
		 }
		 this.cookie.setCookie(name, newVal, expire, '/', '','');
	},
	setBatchCookie: function(name, value, expire){
		 this.cookie.setCookie(name, value, expire, '/', '','');
	},
	removeCustomCookie: function(name, value){
		var currentVal = this.cookie.getCookie(name);
		 var newVal = "";
		 if(currentVal != null){
			var currentValList = currentVal.split("&");
			for (var i=0; i < currentValList.length; i++) {
				if(value != currentValList[i]){
				    if(newVal != ''){
						newVal = newVal + "&" + currentValList[i];
					}else{
						newVal = currentValList[i];
					}
				}
			}
		 this.cookie.setCookie(name, newVal, this.expire, '/', '', '');
		 }		
	},
	
	restoreAllCriterias:function(name){
		var allCookies = this.getArrayFromDelimitedCookie(name, '&');
		if(allCookies){
			var questionIdArray = this.getArrayFromDelimitedString(allCookies[0], ':');		// First one has question ids.
			
			var criteriaIdCookieStringArrayByQuestion = new Array(questionIdArray.length);
			for(var i=0; i<questionIdArray.length; i++) {
				criteriaIdCookieStringArrayByQuestion[i] = this.getArrayFromDelimitedString(allCookies[i+1], ':');
			}
			
			// Start the loop after questionId and criteriaId related cookies.
			var allCriterias = allCookies[questionIdArray.length+1].split('');
			var INCREMENT = 7;
			for(var i=0; i<allCriterias.length; i += INCREMENT){
				var criteriaStates = allCriterias.slice(i, i + INCREMENT);	// Returns criteria id, question id, checkState, ableState, statusState and lastState in an array.
				var encodedCriteriaId = criteriaStates[0]*10 + criteriaStates[1]*1;	// Get encoded criteria id. Make it 2digit number.
				var encodedQuestionId = criteriaStates[2];							// Get encoded question id.
				
				if(criteriaIdCookieStringArrayByQuestion[encodedQuestionId]) {
					var criteriaId = criteriaIdCookieStringArrayByQuestion[encodedQuestionId][encodedCriteriaId];
					var questionId = questionIdArray[encodedQuestionId];
					
					var question = productSelector.getQuestion(questionId);
					var criteria;
					if(question != null && question != ''){
						criteria = question.getCriteria(criteriaId);
					}
					
					var htmlObj = $(criteriaId);
					if(htmlObj) {
						htmlObj.checked = criteriaStates[3]=='1';				// Set the checkState.
						
						var fakeCheckBox = $(htmlObj.id+'-fakeCheckBox');
						if(fakeCheckBox) {
							fakeCheckBox.changeCheckedState();
							fakeCheckBox.changeDisabledState();										
						}
					}
					if(criteria){			
						criteria.setDisabled(criteriaStates[4]=='1');			// Set the ableState.
						criteria.status = criteriaStates[5];					// Set the statusState.
						criteria.lastState = criteriaStates[6]=='1';			// Set the lastState.
					}
				}
			} 
		}
		
		productSelector.currentProducts = productSelector.getCurrentProducts();
	},
	
	loadCheckedItems:function(name){
		var currentValList = this.getArrayFromDelimitedCookie(name, '&');
		var questionIdArray = this.getArrayFromDelimitedString(currentValList[0], ':');
		
		var criteriaIdCookieStringArrayByQuestion = new Array(questionIdArray.length);
		for(var i=0; i<questionIdArray.length; i++) {
			criteriaIdCookieStringArrayByQuestion[i] = this.getArrayFromDelimitedString(currentValList[i+1], ':');
		}
		
		var checkedItemsList = new Array();
		var allCriterias = currentValList[questionIdArray.length+1].split('');
		var INCREMENT = 7;
		var numberOfGenuineCriterias = 0;
		for (var i=0; i < allCriterias.length; i += INCREMENT) {
			var criteriaStates = allCriterias.slice(i, i+INCREMENT);				
			var encodedCriteriaId = criteriaStates[0]*10 + criteriaStates[1]*1;	// Get encoded criteria id. Make it 2digit number.
			var encodedQuestionId = criteriaStates[2];							// Get encoded question id.

			if(criteriaIdCookieStringArrayByQuestion[encodedQuestionId]) {
				var criteriaId = criteriaIdCookieStringArrayByQuestion[encodedQuestionId][encodedCriteriaId];
				
				if(criteriaStates[3] == '1'){	// Control if the criteria is checked.
					checkedItemsList[checkedItemsList.length] = criteriaId;	// Return the id of criteria
				}


				if(criteriaId.indexOf('-C') > 0) {	// Genuine criteria has '-C' string in their id.
					numberOfGenuineCriterias++;
				}
			}
		}
		pstCookieManager.numberOfCriterias = numberOfGenuineCriterias;
		
		return checkedItemsList;
	},
	getArrayFromDelimitedCookie:function(name, delimiter){
		var customCookie = this.getCustomCookie(name);
		return this.getArrayFromDelimitedString(customCookie, delimiter);
	},
	getCustomCookie: function(name){
		return this.cookie.getCookie(name);
	},
	getArrayFromDelimitedString: function(delimitedString, delimiter){
		var returnArray = new Array();
		if(delimitedString != null && delimitedString != '') {
			returnArray = delimitedString.split(delimiter);
		}
		
		return returnArray;
	},
	getVersion: function(name){
		var value = this.cookie.getCookie(name);
		var index = value.lastIndexOf('ver.');
		value = value.substring(index);
		return value;
	},
	
	checkCookie:function(name){
		if(this.cookie.getCookie(name) == null || this.cookie.getCookie(name) == "")
			return true;
		else
			return false;
	},
	
	removeCookie:function(name){
		this.cookie.deleteCookie(name);
	},
	
	isCookiesEnabled:function(){
		return this.cookie.isSupported();
	}
}
 
/* end of PSTCookie Class */

/* beginning of Cookie class */

var Cookie = Class.create();
Cookie.prototype = {
	initialize:function(name, value, expireDays){
		this.name = name;
		this.value = value;
		this.expireDays = expireDays;
	}
	,
	setCookie:function(name, value, days, path, domain, secure){
		var expires = -1;
		if(typeof days == "number" && days >= 0) {
			var d = new Date();
			d.setTime(d.getTime()+(days*24*60*60*1000));
			expires = d.toGMTString();
		}
		value = escape(value);
		document.cookie = name + "=" + value + ";"
			+ (expires != -1 ? " expires=" + expires + ";" : "")
			+ (path ? "path=" + path : "")
			+ (domain ? "; domain=" + domain : "")
			+ (secure ? "; secure" : "");
	}
	,
	getCookie:function(name){
		var idx = document.cookie.lastIndexOf(name+'=');
		if(idx == -1) { return null; }
		var value = document.cookie.substring(idx+name.length+1);
		var end = value.indexOf(';');
		if(end == -1) { end = value.length; }
		value = value.substring(0, end);
		value = unescape(value);
		return value;
	}
	,
	deleteCookie:function(name){
		this.setCookie(name, '', 0, '/', '','');
	}
	,
	isSupported:function(){
		if(typeof navigator.cookieEnabled != "boolean") {
			setCookie("__TestingYourBrowserForCookieSupport__",
				"CookiesAllowed", 90, null);
			var cookieVal = getCookie("__TestingYourBrowserForCookieSupport__");
			navigator.cookieEnabled = (cookieVal == "CookiesAllowed");
			if(navigator.cookieEnabled) {
				// FIXME: should we leave this around?
				this.deleteCookie("__TestingYourBrowserForCookieSupport__");
			}
		}
		return navigator.cookieEnabled;
	}
	
}

/* end of Cookie class */
