//Utility function called by getCookie( )
function getCookieVal(offset) {
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1) {
        endstr = document.cookie.length;
    }
    return unescape(document.cookie.substring(offset, endstr));
}

/*
 * Returns all the cookies available from this domain that correspond
 * to previously saved tracks
 */
 function getTracks(){
	 var clen = document.cookie.length;
	 $rawCookies = document.cookie.split(';');
	 $cookies = new Array();
	 //console.log(document.cookie);
	 
	 for(i=0;i<$rawCookies.length;i++){
		 $cookie = $rawCookies[i];
		 $cookie = unescape($cookie);//unescape the escaped cookie
		 
		 $delimIndex = $cookie.indexOf('=');
		 $cname = $cookie.substr(0, $delimIndex);//get the name of the cookie
		 $cval = $cookie.substr($delimIndex+1);
		 
		 //console.log("Cookie name: "+$cname);
		 
		 //check if this cookie is one that pertains to a track/song
		 $isTrack = $cname.indexOf('fg-') >= 0 ? true : false;
		 if($isTrack){
		 	//console.log('Track '+$cname+" : "+$cval);
			$obj = string2Object($cval);
			$cookies.push($obj);
		 }else{
			 //console.log('Not a track: '+$rawCookies[i]);
		 }
	 }
	 
	 return $cookies;
 }

/*
 *Primary function to retrieve cookie by name
 * e.g: var styleCookie = getCookie("fontSize");
 */
function getCookie(name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) {
            return getCookieVal(j);
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break; 
    }
    return "";
}

/*
 *Store cookie value with optional details as needed
 * e.g: setCookie ("userID", document.entryForm.username.value);
 * 		setCookie("fontSize", styleID, getExpDate(180, 0, 0));
 */
function setCookie(name, value, expires, path, domain, secure) {
	//save the cookie for one year from now
	var expDate = new Date();
	var oneYrFromNow = expDate.getTime() + (365 * 24 * 60 * 60 * 1000);
	expDate.setTime(oneYrFromNow);
	var expStr = expDate.toGMTString();
	
	path = (path) ? path : '/';
	
	expires = expStr;
	
    document.cookie = name + "=" + escape (value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "/") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

//Remove the cookie by setting ancient expiration date
function deleteCookie(name,path,domain) {
	//set the expiry date to an hour ago
	var date = new Date();
	date.setTime(date.getTime() + (-1 * 24 * 60 * 60 * 1000));
	
    if (getCookie(name)) {
        document.cookie = name + "=" + ((path) ? "; path=" + path : "; path=/") + ((domain) ? "; domain=" + domain : "") + "; expires="+date.toUTCString();
    }else{
		//console.log("Cookie "+name+" not found for deletion");
	}
}

 function object2String(obj) {
    var val, output = "";
    if (obj) {    
        output += "{";
        for (var i in obj) {
            val = obj[i];
            switch (typeof val) {
                case ("object"):
                    if (val[0]) {
                        output += i + ":" + array2String(val) + ",";
                    } else {
                        output += i + ":" + object2String(val) + ",";
                    }
                    break;
                case ("string"):
                    output += i + ":'" + escape(val) + "',";
                    break;
                default:
                    output += i + ":" + val + ",";
            }
        }
        output = output.substring(0, output.length-1) + "}";
    }
    return output;
}

/*
 *Converts an array into a string
 */
 function array2String(array) {
    var output = "";
    if (array) {
        output += "[";
        for (var i in array) {
            val = array[i];
            switch (typeof val) {
                case ("object"):
                    if (val[0]) {
                        output += array2String(val) + ",";
                    } else {
                        output += object2String(val) + ",";
                    }
                    break;
                case ("string"):
                    output += "'" + escape(val) + "',";
                    break;
                default:
                    output += val + ",";
            }
        }
        output = output.substring(0, output.length-1) + "]";
    }
    return output;
 }
 
 function string2Object(string) {
    eval("var result = " + string);
    return result;
 }
   
 function string2Array(string) {
    eval("var result = " + string);
    return result;
 }

