// JsCookieLib
// Stefan Huster - stefan.huster@online.de
// (c) 2009


// INCLUDES:
//		- lib_string


function lib_cookies () {

	/**
	 * Checks if a cookie exisits and contains the searched parameter.
	 * @param param The name of the parameter
	 * @return The value of the parameter of false if no cookie exsists
	 */
	this.getCookieValue = function ( param ) {
		
		if(document.cookie) {
			
			var libString = new lib_string();
			var cookieContent = document.cookie;
			var pva = this.cookieToPva( cookieContent);
			
			for ( var i=0; i < pva.length; i++) {	
				for ( var key in pva[i]) {			
					if ( libString.trim(key) == param ) {
						return pva[i][key];	
					}
				}
			}
			
		}
		
		return false;		
	}
	
	/**
	 * This function will update the value of the given parameter within the cookie.
	 * The parameter will be atached to the cookie if it does not exists so fare
	 * @param param The name of the parameter
	 * @param value The new value
	 */
	this.setCookieValue = function ( param, value ) {
				
		var newValue = param + "=" + value;
		document.cookie = newValue;
		
	}
	
	/**
	 * This function will parse the given parameter value array to a cookie
	 * @param pva The parameter value array
	 */
	this.pvaToCookie = function ( pva ) {
		
		var pvaString = "amarok.deScoring=";
		
		for ( var i=0; i < pva.length; i++) {	
			for ( var key in pva[i]) {			
				pvaString = pvaString + key + "=" + pva[i][key]+";";			
			}	
		}
		
		var now = new Date();
		var expires = new Date(now.getTime() + 30000000000);
		pvaString = pvaString + "expires=" + expires.toGMTString() + ";";
		
		document.cookie = pvaString;
	}
	
	/**
	 * This function will parse the given cookie content into an associative array
	 * @param cookieContent The content of the cookie
	 * @return The parameter value array of the type array[ID][PARAMETERNAME] = VALUE 
	 */
	this.cookieToPva = function ( cookieContent ) {
		
		var paraValuePairs = cookieContent.split(';');
		var pva = new Array(paraValuePairs.length);
		var id = 0;
		
		for ( var i=0; i < paraValuePairs.length; i++) {
		
			var paraValuePair = paraValuePairs[i].split("=");
			
			if (paraValuePair.length == 2) {			
				pva[id] = new Object();
				pva[id][paraValuePair[0]] = paraValuePair[1];									
				id++;			
			}
			
		}
		
		return pva;
	}
	
	/**
	 * This function will create a string version out the parameter value array.
	 * This function is so highly usefull during debuging your system.
	 * @param pa The parameter value array
	 * @return A string representation of pa
	 **/
	this.pvaToString = function ( pva ) {
		
		var pvaString = "";
		
		for ( var i=0; i < pva.length; i++) {	
			for ( var key in pva[i]) {			
				pvaString = pvaString + key + "=" + pva[i][key] + "<br />";			
			}	
		}
		
		return pvaString;
		
	}
	
}
