﻿
var personalItems = function($){
    var priv = {
        lists   : new Array(),
        myPersonalItems : "#my-personal-items",
        
        cookieExpires	: 365,	//number of days that cookie remains valid
		maxCookieItems	: 185,	//avoids cookie getting bigger than 4kB, 185 is a save number
        
        /**
		 * object that contains cookie item information
		 * @param {int} id, identifier for object
		 * @param {number} date, milliseconds since 1 1 1970
		 */
		cookieItem	: function(id, date){
			this.id		= id;
			this.date	= date;
		},
        
        /**
		 * saves the cookieItems to the cookie 
		 * @param {String} cookieName, the name for the cookie
		 */
		saveCookieItems	: function(cookieName){
			//first make sure we have the requested list
			if(!priv.lists[cookieName]){
			    logic.writeDebug("trying to save to cookie '" + cookieName + "', no such list exists", 2);
			    return false;
			}
			var cookieStr = "";
			
			//make sure we do not exceed the priv.maxCookieItems
			priv.lists[cookieName] = priv.checkMaxCookieItems(priv.lists[cookieName]);
						
			//make sorting by Id before adding to cookie
			//priv.lists[cookieName].sort(priv.sortCookieItemsById);
			
			//create string for cookie, in format: ID1_millisecs1,ID2_millisecs2, .....
			for(i=0; i<priv.lists[cookieName].length; i++){
			    //make sure we are not inserting corrupted items
			    if(!isNaN(parseInt(priv.lists[cookieName][i].id)) && priv.lists[cookieName][i].date){
				    cookieStr += priv.lists[cookieName][i].id + "_" + priv.lists[cookieName][i].date + ",";
				}
			}
			
			$.cookie(logic.CookiePrefix + "" + cookieName, cookieStr, { expires: priv.cookieExpires, path: '/' });
		},
		
		/**
		 * loads the cookieItems from the given cookie
		 * @param {String} cookieName, the name of the cookie to get
		 */
		loadCookieItems	: function(cookieName){			
			//check wether we had already loaded this array, if so return that array
			if(priv.lists[cookieName] && priv.lists[cookieName].length > 0){
			    return priv.lists[cookieName];
			}
			
			priv.lists[cookieName] = new Array();
			//fill temp array
			//get the favoritesCookie
			//markup like accoId1_timemillisecs1,accoId2_timemillisecs2,
			
			var cookieStr = $.cookie(logic.CookiePrefix + "" + cookieName);
		
			logic.writeDebug(cookieName + ":\n" + cookieStr);
						
			if(cookieStr && cookieStr.length > 1){
				//cookie exists and contains data
				var cookieArr = cookieStr.split(",");
				//strip last item (always emtpy because of trailing ",")
				cookieArr.length = cookieArr.length - 1;
				
				//get push the cookie into the items array
				for(i=0; i<cookieArr.length; i++){
					thisItem = cookieArr[i].split("_");
					priv.lists[cookieName].push(new priv.cookieItem(thisItem[0], thisItem[1]));
				}
				priv.lists[cookieName].sort(priv.sortCookieItemsById);
			}
			
			return priv.lists[cookieName];
		},
				
		/**
		 * Custom sort function used to sort arrays of cookieItem objects by id
		 */
		sortCookieItemsById	: function(a, b){
			returnValue = 0;
			try {
				returnValue = (a.id - b.id);
			}
			catch(err){
				logic.writeDebug("Error: sortCookieItemsById:\n" + err);
			}
			return (isNaN(returnValue) ? 0 : returnValue);
		},
		
		/**
		 * Custom sort function used to sort arrays of cookieItem objects by id
		 */
		sortCookieItemsByDate	: function(a, b){
			returnValue = 0;
			try {
				returnValue = (b.date - a.date);
			}
			catch(err){
				logic.writeDebug("Error: sortCookieItemsByDate:\n" + err);
			}
			return returnValue;
		},
		
		/**
		 * returns string: formated to the timestamp for the cookie
		 * @param {Object} date (optional)
		 */
		getDateForCookie	: function(date){
			if(typeof(date) == "undefined"){
				var currDate	= new Date();
			}
			else {
				var currDate = date;
			}
			
			returnDate = Date.parse(currDate);
			return returnDate;
		},
		
		/**
		 * returns Date object with date from string
		 * @param {String} cookieDate
		 */
		getDateFromCookie	: function(cookieDate){						
			var returnDate = new Date();
			returnDate.setTime(cookieDate);
			
			logic.writeDebug(returnDate.toString());
			return returnDate;
		},
		
		/**
		 * Checks that we not exceed the priv.maxCookieItems
		 * if priv.maxCookieItems is exceeded, strips oldest items, and returns newest
		 * @param {Array} cookieItems, the array with cookieItem objects to test
		 * 
		 * @return array with correct amount of cookieItems
		 */
		checkMaxCookieItems	: function(cookieItems){
			//if the array is bigger than defined maximum, strip oldest items
			if(cookieItems.length > priv.maxCookieItems){
				logic.writeDebug("Stripping oldest cookieItems from array");
				//sort by date, strip the oldest items
				cookieItems.sort(priv.sortCookieItemsByDate);
				cookieItems.length = priv.maxCookieItems;
			}
						
			return cookieItems;
		}
    };
    
    return {
        Load : function(cookieName){
            //logic.writeDebug("Loaded " + cookieName);
            return priv.loadCookieItems(cookieName);
        },
        
        /**
		 * Adds or updates the current array with the Id and Current Date stamp
		 * and saves the cookie after updating
		 * @param {String} cookieName, the name of the list to store
		 * @param {Int} matchId, the id of the item to store
		 */
        Add : function(cookieName, matchId){
            var timer = new Timer();
            //check wether we already had this list
            if(!priv.lists[cookieName]){
                //create the list
                priv.lists[cookieName] = new Array();
            }
                        
            //check wether we already had this item
			//if found in the array, only update the date field
			var exists = false;
			for(i=0; i<priv.lists[cookieName].length; i++){
				if(priv.lists[cookieName][i].id == matchId){
					priv.lists[cookieName][i].date = priv.getDateForCookie();
					exists = true;
					logic.writeDebug("updating item '" + matchId + "' in list '" + cookieName + "'");
					break;
				}	
			}
			
			//if the item was not found in the array, insert new item
			if(!exists){
				priv.lists[cookieName].push(new priv.cookieItem(matchId, priv.getDateForCookie()));
				logic.writeDebug("add new item '" + matchId + "' in list '" + cookieName + "'");
			}
			
			priv.saveCookieItems(cookieName);
			logic.writeDebug("saving cookie took: " + timer.Stop() + " ms", -1);
        },
        
        /**
		 * Removes an item from the given list and saves the cookie
		 * and saves the cookie after updating
		 * @param {String} cookieName, the name of the list from which to remove
		 * @param {Int} matchId, the id of the item to remove
		 */
        Remove  : function(cookieName, matchId){
            //remove element
			//get the correct array index, and remove
			for(i=0; i<priv.lists[cookieName].length; i++){
				if(priv.lists[cookieName][i].id == matchId){
					priv.lists[cookieName].splice(i, 1);
					break;	
				}
			}
			logic.writeDebug("removed item '" + matchId + "' from list '" + cookieName + "'");
			priv.saveCookieItems(cookieName);
        },
        
        /**
		 * Removes the cookie for the given name
		 * @param {String} cookieName, the name of the list from which to remove
		 */
        RemoveAll  : function(cookieName){
            //remove cookie
            priv.lists[cookieName].length = 0;
			logic.writeDebug("removed all from list '" + cookieName + "'");
			priv.saveCookieItems(cookieName);
        },
        
        /**
		 * Tests wether a certain item exists in the given array
		 * @param {String} cookieName, the name of the list from which to remove
		 * @param {Int} matchId, the id of the item to remove
		 * 
		 * returns {bool}
		 */
        Contains  : function(cookieName, matchId){
			//make sure the array has been loaded
			this.Load(cookieName);
			
			//check if the id exists in the array
			for(i=0; i<priv.lists[cookieName].length; i++){
				if(priv.lists[cookieName][i].id == matchId){
					//if found, return true
					return true;
				}
			}
			//not found, return false
			return false;
        },
        
        /**
		 * returns Date object with date from string
		 * @param {String} cookieDate
		 */
        GetDate : function(cookieDate){
            return priv.getDateFromCookie(cookieDate);
        },
        
        /**
        * Shows the links for the personal items, and (re)calculates the counters
        */
        ShowItemLinks   : function(){
            for(cookieName in priv.lists){                
                var $item = $("#my-" + cookieName.toLowerCase() + "-items");
                var $counter = $("#my-" + cookieName.toLowerCase() + "-count");
                
	            if($item.attr("id") && priv.lists[cookieName].length > 0){
	                logic.writeDebug("showing personal link: " + $item.attr("id") + " with count: " + priv.lists[cookieName].length);
	                
	                $counter.html("(" + priv.lists[cookieName].length + ")").css("visibility", "visible").removeClass("inactive");
	                $item.removeClass("inactive");
	                if(cookieName == 'favorites'){
	                    $item.attr('href',resources.path_prefix + "/search.aspx?N=0&personal=" + cookieName);
	                }
		            
		            //if the item has visibility:hidden style, show, and set bindings
		            if($item.css("visibility") == "hidden"){
		                if($item.attr('class') == 'drillsel'){
		                    $item.css("visibility", "visible").bind("click", 
				                function(){
					                document.location.href = resources.path_prefix + "/search.aspx?N=0";
					                return false;
				                }
				            );
		                } else {
		                    $item.css("visibility", "visible").bind("click", 
				                function(){
					                //to make the redirect: 
					                //strip current querystring (if any)
					                //var newUrl = document.location.href.substring(0, document.location.href.indexOf("?"));
                					
            					    cookieName = this.id.substring(this.id.indexOf("-") + 1, this.id.lastIndexOf("-"));
					                //add favorites parameter
					                document.location.href = resources.path_prefix + "/search.aspx?N=0&personal=" + cookieName;
					                return false;
				                }
				            );
				        }
				    }
	            }
	            else {
	                //hide the links if array is emtpy
	                //$item.css("visibility", "hidden");
	                //$counter.css("visibility", "hidden");
	                
	                //show the links, even when the count is 0
	                //but do not make them active
                    $item.css("visibility", "visible").addClass("inactive");
                    $counter.html("(0)").css("visibility", "visible").addClass("inactive");
	            }
	        }
        }
    };
}(jQuery);

