var NSU = window.NSU || {};

(function(){
 
        var historyTest = /history\-trail=\[.*\]($|; )/.exec(document.cookie);

        var history = [];
		
        var now = new Date();

        // Phase 2 R6 - Update expiration to 30 days.
        var expirationDate = new Date(now.setDate(now.getDate()+30)).toUTCString();


        if(!historyTest){

          document.cookie = 'history-trail=[];expires=' + expirationDate + '; path=/'

        }else{

          history = (new Function("return " + historyTest[0].substring(14)))();

        }
		
		var temphistoryUrl = "";
		//check if this history element exists or will throw error
        if (typeof history[0] != 'undefined')
        {
            temphistoryUrl = history[0]
        }
		if((history.length > 0 &&  temphistoryUrl.url != window.document.location) || history.length == 0){
		
		
	    var documentTitle = escape(document.title);
		
		history.unshift({title:documentTitle,url:window.document.location});
		
		}
		var historySerialized = [];
		
		var validCount = 0;
		var i = -1;
		
		/* loop until we have 5 valid or reached the end of history */
		while (validCount < 5  && i < (history.length - 1) )
		{
		    //increment loop counter
            i++;
            
		    //if history[i] is undefined or has no title, do not include
            if (typeof history[i] != 'undefined')
            {
                if(history[i].title.length > 0)
                {
                    // Phase 2, R6 - Don't add 'Home' or 'error' pages to recent links.
                  // Strip off the first 4 characters of the page title as this will
                  //  be where 'Home' is stored.
                  var trunc = history[i].title.substr(0,4);
                                   
                  if(trunc.toLowerCase() != 'home' && trunc.toLowerCase() != 'erro')  
                  {
                
		              // Kim:NSU0186 - dont add duplicates since we are no longer sorting output
		              var added = false;
		              //always add first valid element
		              if(validCount == 0)
		              {
		              	historySerialized[validCount] = '{title:"'
				
					+ history[i].title

					+ '",url:"'

					+ history[i].url

					+ '"}';
				added = true;
		              }
		              else
		              {
				      //use AddToArray so duplicates wont be added
				      added= AddToArray(historySerialized, '{title:"'

					+ history[i].title

					+ '",url:"'

					+ history[i].url

					+ '"}');
		                
		                }
		                //increment number of valid serialized entries if a valid, non-duplicate entry was added
		                if(added)
		                {
		                	validCount++;
		                }
		         }
                }
            }            
		}		

		document.cookie = "history-trail=["

		  + historySerialized.join(",")

		  + "];expires="

		  + expirationDate

		  + "; path=/";

		NSU.history = history;
	
 
})();

function renderLinks()
{
	if(NSU.history)
	{
		if (NSU.history.length > 1)
		{
			// Need to hide the most popular links div and show the recent links panel
			var ele = document.getElementById("mostPopularLinksPanel");
			ele.style.display = "none";
			
			// Phase 2 R6 - If using recent links, change Panel name to 'Recently visited'
			var mostPopularPanel = document.getElementById("mostpopular").innerHTML = "<h4>Recently visited</h4>";
            
			document.write("<ul>");
			
            // Kim:NSU0186 no longer checking history for duplicates since duplicates won't be added  
            var deDupArray = DeDupArray(NSU.history);
			for(var i = 0; i < deDupArray.length; i++)
			{
                //split on the '#' char
                var split = deDupArray[i].split('#');
                document.write("<li><a href='" + unescape(split[0]) + "' title='" + unescape(split[1]) + "'>" + unescape(split[1]) + "</a></li>");

			}
			document.write("</ul>");
		}
	}
}

function DeDupArray(a)
{
    // Kim:NSU0186 no longer checking history for duplicates since duplicates won't be added
    //create new array to sort by. Will be sorting by url. Elements are appended url and title.
    var arrUrl = new Array();
    for (var i = 1; i < a.length; i++)
    {
        //need to exclude pages where history is not properly set.
        //this includes discussion pages - these have no title property
        if (typeof a[i] != 'undefined')
        {
            //ensure title is present
            if(a[i].title.length > 0)
            {
                //strip all chars out after the '|' character in Title (as URL encoded, is actually '%7C')
                var trunc = a[i].title.split('%7C', 1);   
                //build a '#' delimited string of url and title to pass back to calling function
                arrUrl[i-1] = a[i].url + '#' + trunc;
            }
        }
    }
    
    return arrUrl;
}

function AddToArray(arrayToAddTo,element)
{
	//only adds the element if not already present
	
	var len = arrayToAddTo.length;
	
	var found = false;
	for (var i=0; i<len; i++)
	{
		if (arrayToAddTo[i] == element)
		{
			found = true;
			break;
		}	
	}
	
	if (!found)
	{
		arrayToAddTo.push(element);
	}
	
	return !found;
}
