function Get_Cookie(name) {
    var start = document.cookie.indexOf(name+"=");
    var len = start+name.length+1;
    if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
    if (start == -1) return null;
    var end = document.cookie.indexOf(";",len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len,end));
}

function getCookie(name,def){
	var str =Get_Cookie(name);
	if(str==null || str.length==0) {
		return def;
	} else return str;
}

function Set_Cookie(name,value,expires,path,domain,secure) {
var today = new Date();
today.setTime( today.getTime() );
t=today.getTime();
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
t+=expires;
}
var expires_date = new Date( t );

cookieStr = name + "=" +escape(value) +
        ( (expires) ? ";expires=" + expires_date.toGMTString() : "") +
        ( (path) ? "; path=" + path : ";path=/") + 
        ( (domain) ? ";domain=" + domain : "") +
        ( (secure) ? ";secure" : "");

document.cookie = cookieStr;
}

function Delete_Cookie(name,path,domain) {
    if (Get_Cookie(name)) document.cookie = name + "=" +
       ( (path) ? ";path=" + path : ";path=/") +
       ( (domain) ? ";domain=" + domain : "") +
       ";expires=Thu, 01-Jan-70 00:00:01 GMT";
}

function setMasterCookie() {
    if (!Get_Cookie('MasterCookie'))
        Set_Cookie('MasterCookie','MasterCookie');
}

function setIntelligentCookieX(name,value,exp) {
    if (Get_Cookie('MasterCookie')) {
        var IntelligentCookie = Get_Cookie(name);
        if ((!IntelligentCookie) || (IntelligentCookie != value)) {
            Set_Cookie(name,value,exp);
            var IntelligentCookie = Get_Cookie(name);
            if ((!IntelligentCookie) || (IntelligentCookie != value)){
                Delete_Cookie('MasterCookie');
	    }
        }
    }
}

function setIntelligentCookie(name,value) {
setIntelligentCookieX(name,value,365);
}


function setCookie(name, value){
setIntelligentCookie(name,value);
}

function deleteCookie(name){
Delete_Cookie(name);
}

function setSessionCookie(name,value){
setIntelligentCookieX(name,value);
}

function forcePageRefresh(name){
	var val = getCookie(name);
	var refresh = false;
	if(val != null){ // we have cookie
		var data = val.split(":");
		if(data.length==2){ // got both dates
			var greater = data[0]; // this val should not be before
			var lesser = data[1]; // this
	
			if(greater<lesser){ // something has triggered reloading the page (next page perhaps?:) )
				refresh = true;
			}
		}
	}
	setMasterCookie();
	setSessionCookie(name,"2:1"); // set indication that this page doesn't need to be refreshed
	if(refresh){
	    doPageRefresh();
	}
}

function doPageRefresh() {
	window.location.href=window.location.href; // this will refresh the page
}

function setPageRefresh(name){
	var val = getCookie(name);
	if(val != null){
		setMasterCookie();
		setSessionCookie(name,"0:1");
	}
}

function cookieForms() {  
	var mode = cookieForms.arguments[0];
	for(f=1; f<cookieForms.arguments.length; f++) {
		formName = cookieForms.arguments[f];
		if(mode == 'open') {	
			cookieValue = getCookie('saved_'+formName);
			if(cookieValue != null) {
				var cookieArray = cookieValue.split('#cf#');
				if(cookieArray.length == document[formName].elements.length) {
					for(i=0; i<document[formName].elements.length; i++) {
						if(cookieArray[i].substring(0,6) == 'select') { document[formName].elements[i].options.selectedIndex = cookieArray[i].substring(7, cookieArray[i].length-1); }
						else if((cookieArray[i] == 'cbtrue') || (cookieArray[i] == 'rbtrue')) { document[formName].elements[i].checked = true; }
						else if((cookieArray[i] == 'cbfalse') || (cookieArray[i] == 'rbfalse')) { document[formName].elements[i].checked = false; }
						else { document[formName].elements[i].value = (cookieArray[i]) ? cookieArray[i] : ''; }
					}
				}
			}
		}
				
		if(mode == 'save') {	
			cookieValue = '';
			for(i=0; i<document[formName].elements.length; i++) {
				fieldType = document[formName].elements[i].type;
			
				if(fieldType == 'password') { passValue = ''; }
				else if(fieldType == 'checkbox') { passValue = 'cb'+document[formName].elements[i].checked; }
				else if(fieldType == 'radio') { passValue = 'rb'+document[formName].elements[i].checked; }
				else if(fieldType == 'select-one') { passValue = 'select'+document[formName].elements[i].options.selectedIndex; }
				else { passValue = document[formName].elements[i].value; }
				if(cookieValue.length>0){
					cookieValue = cookieValue + '#cf#' + passValue;
				} else {
					cookieValue = cookieValue + passValue;
				}
			}
			setSessionCookie('saved_'+formName, cookieValue);		
		}	
	}
}

// value of name is a string of val1/val2/val3/etc form
// this function inserts value in such string if it wasn't already there
// and sets resulting cookie.
function setArraySessionCookie(name,value){
	var str_array = getCookie(name,"");
	var arr = str_array.split("/");
	var output = "";
	var found = false;
	for(var i=0; i<arr.length; i++){
		if(arr[i] == value){
			found = true;
		}
		if(arr[i].length>0){
			output = output + "/" + arr[i];
		}
	}
	if(!found){
		output = output + "/" + value;
	}
//	alert("output: " + output + " and " + value + " was " + (found?"":"not ") + "found");
	setSessionCookie(name, output);
}

// checks if specified array cookie is set and has specified value in it
function hasArrayCookieValue(name,value){
	var str_array = getCookie(name,"");
//	alert("full value: " + str_array);
	var arr = str_array.split("/");
	for(var i =0; i< arr.length; i++){
//		alert("comparing " + arr[i] + " to " + value);
		if(arr[i] == value){
			alert("bingo!");
			return true;
		} else {
//			alert("miss");
		}
	}
	return false;
}

// removes value from array cookie
function removeArraySessionCookie(name,value){
	var str_array = getCookie(name,"");
	var arr = str_array.split("/");
	var output = "";
	for(var i=0; i<arr.length; i++){
		if(arr[i] != value){
			output = output + "/" + arr[i];
		}
	}
	setSessionCookie(name, output);
}

// this function is coupled to java code
// java code clears specific cookie value from the specific cookie
// before displaying the page.
// the page reloads if the cookie is set
// otherwise it sets it.
function ensureReload(name, value){
	setMasterCookie();
	alert("checking " + name + " for " + value);
	if(hasArrayCookieValue(name,value)){
//		alert("aha!");
		doPageRefresh();
	} else {
//		alert("no luck. setting it!");
		setArraySessionCookie(name,value);
	}
}
