/* cookies.js
 * 
 */

/*
 * =Cookie Support
 * @Does the web browser support cookies?
 */
function cookie_support() {
	var tmpName = "EM_COOKIE_TEST";
	var tmpValue = "Cookies Supported";
	var tmpRet = null;
	setCookie(tmpName,tmpValue,1);
	tmpRet = readCookie(tmpName);
	deleteCookie(tmpName);
	return (tmpRet !== null?1:0);
}

/*
 * =EM Cookie Make
 * @Creates a cookie item from the Points array ID containing layer id, point id, info, notes, lat, long
 */
function em_cookie_make(tmpPointID, tmpVcomments, tmpCookiePos) {
	/*
	 * name=
	 * cookie prefix
	 * Layer ID
	 * point ID
	 *
	 * value=
	 * layer id
	 * point id
	 * point name
	 * notes
	 */
	/* name would be composed like
	 * cookie_prefix+aPoint_layer_id[tmpPointID]+"_"+aPoint_arc_point_id[tmpPointID]
	 *
	 * value would be in the syntax of 
	 * layer_id+cookie_split+point_id+cookie_split+point_name+cookie_split+notes
	 */
	var tmpPos = tmpCookiePos==null?parseInt(aCookies.length==0?0:(aCookies.length)):tmpCookiePos;
	var tmpCookiePos = ((tmpCookiePos > -1)?tmpCookiePos:tmpPos); // change 1 to function that creates the cookies position
	//alert("tmpCookiePos="+tmpCookiePos);
	
	setCookie(cookie_prefix+aPoint_layer_id[tmpPointID]+"_"+aPoint_arc_point_id[tmpPointID],
	    aPoint_layer_id[tmpPointID]+cookie_split+
	    aPoint_arc_point_id[tmpPointID]+cookie_split+
	    aPoint_name[tmpPointID]+' ('+aPoint_city[tmpPointID]+')'+cookie_split+
	    aPoint_latitude[tmpPointID]+cookie_split+
	    aPoint_longitude[tmpPointID]+cookie_split+
	    tmpVcomments+cookie_split+
	    tmpCookiePos,
	    30);
	point_remove_label(aPoint_layer_id[tmpPointID], aPoint_arc_point_id[tmpPointID]);
	point_insert_label(aPoint_layer_id[tmpPointID], aPoint_arc_point_id[tmpPointID],
		 parseInt(aPoint_x[tmpPointID]-pSquareSize/2),
		 parseInt(aPoint_y[tmpPointID]-pSquareSize/2),
		 'Image for Saved point '+aPoint_name[tmpPointID],
		 dir_label_letters+aLetters[tmpCookiePos]+image_label_ext);
}
/*
 *=EM Cookie Save
 *
 */
function em_cookie_save(tmpCookieName, tmpVcomments, tmpCookiePos) {
	//alert("Cookie save "+tmpCookiePos);
	var tmpCookiePos = ((tmpCookiePos!==null)?tmpCookiePos:parseInt(aCookies.length));
	//alert("Cookie save "+tmpCookiePos);
	var aTmp = tmpCookieName.split("_");
	if (tmpVcomments == null) {
		//default to the comments that were already there
		tmpVcomments = em_cookie_parse(tmpCookieName)[6];
	}
	var tmpPointID = getPointIndex(aTmp[1], aTmp[2]);
	if (tmpPointID==null){
		aTmpCookie = em_cookie_parse(tmpCookieName);
		if(aTmpCookie != null) {
			tmpCookieValue = aTmpCookie[1]+cookie_split+
			aTmpCookie[2]+cookie_split+
			aTmpCookie[3]+cookie_split+
			aTmpCookie[4]+cookie_split+
			aTmpCookie[5]+cookie_split+
			tmpVcomments+cookie_split+
			tmpCookiePos;
		} else {
			alert("Error saving Cookie ["+tmpCookieName+"|"+tmpVcomments+"|"+tmpCookiePos+"] aTmpCookie="+aTmpCookie+"");
		}
	} else {
		tmpCookieValue = aPoint_layer_id[tmpPointID]+cookie_split+
		aPoint_arc_point_id[tmpPointID]+cookie_split+
		aPoint_name[tmpPointID]+' ('+aPoint_city[tmpPointID]+')'+cookie_split+
		aPoint_latitude[tmpPointID]+cookie_split+
		aPoint_longitude[tmpPointID]+cookie_split+
		tmpVcomments+cookie_split+
		tmpCookiePos;
	}
	setCookie(tmpCookieName, tmpCookieValue, 30);
}
/*
 *=EM Cookies Parse
 *@Parses ALL EM cookies
 */
function em_cookies_parse() {
	var aTmpCookie = unescape(document.cookie).split(";");
	var aTmpReturn = new Array();
	/* aTmpCookie; */
	var tmpCookieNumValid = 0;
	for(var i=0, n=aTmpCookie.length;i<n;i++)
    {
        //aTmpReturn[i] = "Cookie "+i+" "+aTmpCookie[i];
        var aTmpNameValue = aTmpCookie[i].split('=');
        if (aTmpNameValue[0].indexOf(cookie_prefix) >= 0) {
        	aTmpReturn[tmpCookieNumValid] = new Array(4);
        	aTmpReturn[tmpCookieNumValid][0] = aTmpNameValue[0]; // key
        	var aTmpValue = aTmpNameValue[1].split(cookie_split);
        	for(var v=0, tmpV=aTmpValue.length;v<tmpV;v++) {
        		aTmpReturn[tmpCookieNumValid][v+1] = xml_entities(aTmpValue[v]);
        	}
        	tmpCookieNumValid += 1;
        }
        /*for(var q=0, tmpNV=aTmpNameValue.length;q<=tmpNV;q=q+2) {
        }*/
    }
    return aTmpReturn;
}
/*
 *=EM Cookie Parse
 *@Parses ONE EM cookies
 */
function em_cookie_parse(tmpCookieName) {
	// test to see if it is a cookie
	var aTmpReturn = new Array();
	var tmpCookie = readCookie(tmpCookieName);
	if (tmpCookie != null) {
        if (tmpCookieName.indexOf(cookie_prefix) >= 0) {
        	aTmpReturn[0] = tmpCookieName;
        	var aTmpValue = tmpCookie.split(cookie_split);
        	for(var v=0,tmpV=aTmpValue.length;v<tmpV;v++) {
        		aTmpReturn[v+1] = xml_entities(aTmpValue[v]);
        	}
        } else {
        	// not an EM cookie ... do nothing
        	//error('Error:em_cookie_parse:'+tmpCookieName+' is Not a cookie');
        	//alert('Error:em_cookie_parse:'+tmpCookieName+' is Not a cookie pos['+tmpCookieName.indexOf(cookie_prefix)+']. Please report this error to webmaster@CattCo.org');
        	return null;
        }
        return aTmpReturn; 
    } else {
    	// it isn't a cookie
    	error('Error:em_cookie_parse:'+tmpCookieName+' is Not a cookie');
    	//alert('Error:em_cookie_parse:'+tmpCookieName+' is Not a cookie. Please report this error to webmaster@CattCo.org');
    	return null;
    }
}
/*
 *=EM Cookies Update
 *@ Repositions/updates the content to all the EM cookies
 */
function em_cookies_update() {
	aTmpReturn = em_cookies_parse();
	if (aTmpReturn !== null) {
		for(var i=0, tmpC=aTmpReturn.length;i<tmpC;i++) {
			em_cookie_save(aTmpReturn[i][0], aTmpReturn[i][6], i);
		}
	} else {
		alert("Error:em_cookies_update");
	}
}
/*
 *
 */
function cookies_saved_position(tmpLayer_id,tmpPoint_arc_id) {
	//
	var aTmpCookie = em_cookie_parse(cookie_prefix+tmpLayer_id+"_"+tmpPoint_arc_id);
	if (aTmpCookie !== null) {
		//alert("cookies_saved_position "+aTmpCookie[7]);
		return aTmpCookie[7];
	} else {
		// return -1 for NOT FOUND
		return -1;
	}
}
/*
 *=EM Cookies clear
 *@
 */
function em_cookies_clear() {
	//document.cookie = "";
}

/*
 *= Points Saved Sort
 *@ Array stores where in the Saved Points a listing is
 *
 */
function points_saved_sort(tmpSpotOld, tmpSpotNew) {
	if (tmpSpotOld == null) {
		// generate
	} else {
		//
	}
}
/*
 *= Points Saved Removed
 *@ Removes entry from Array
 */
function points_saved_removed(tmpSort) {
	if (tmpSort == null) {
		
	}
}

/*
 *= Point Star
 *@ starring a point
 */
function point_star(tmpPointID,tmpPrefix) {
	if (bCookies==1) {
		if (aPoint_star[tmpPointID] == 0) {
			aPoint_star[tmpPointID] = 1;
			//aPoint_sort[tmpPointID] = points_saved_sort(); // sort to the end
			//alert(tmpPointID+" Star!");
			$('star_'+tmpPointID).title= 'Remove '+aPoint_name[tmpPointID]+' from your Saved locations.';
			//$('star_info_'+tmpPointID).title= 'Remove '+aPoint_name[tmpPointID]+' from your Saved locations.';
			em_cookie_make(tmpPointID,"Filler");
			//alert("cookie");
			em_cookies_update();
			savedPointsUpdate();
			//alert("update");
			var sTmpLabel = aLetters[cookies_saved_position(aPoint_layer_id[tmpPointID],aPoint_arc_point_id[tmpPointID])];
			point_remove_label(aPoint_layer_id[tmpPointID], aPoint_arc_point_id[tmpPointID]);
			point_insert_label(
			    aPoint_layer_id[tmpPointID], aPoint_arc_point_id[tmpPointID],
			    aPoint_x[tmpPointID], aPoint_y[tmpPointID],
			    'Label for Saved location letter '+sTmpLabel+' - '+aPoint_name[tmpPointID],
			    dir_label_letters+sTmpLabel+image_label_ext,'letter');
			Element.removeClassName('star_'+tmpPointID, 'star_off');
			//Element.removeClassName('star_info_'+tmpPointID, 'star_off');
			Element.addClassName('star_'+tmpPointID, 'star_on');
			//Element.addClassName('star_info_'+tmpPointID, 'star_on');
			$('star_'+tmpPointID).innerHTML = 'Saved';
		} else {
			aPoint_star[tmpPointID] = 0;
			//points_saved_removed(tmpPointID); // remove from sort
			//alert(tmpPointID+" Un-Star!");
			var el = $('star_'+tmpPointID);
			//alert('Element = '+el);
			if (el != undefined) {
				//alert("Not Undefined");
				$('star_'+tmpPointID).title = 'Add the point '+aPoint_name[tmpPointID]+' to your favorites';
				//$('star_info_'+tmpPointID).title= 'Add the point '+aPoint_name[tmpPointID]+' to your favorites';
			}
			deleteCookie(cookie_prefix+aPoint_layer_id[tmpPointID]+"_"+aPoint_arc_point_id[tmpPointID]);
			//alert("delete");
			em_cookies_update();
			savedPointsUpdate();
			//alert("update");
			point_remove_label(aPoint_layer_id[tmpPointID], aPoint_arc_point_id[tmpPointID]);
			point_insert_label(
			    aPoint_layer_id[tmpPointID], aPoint_arc_point_id[tmpPointID],
			    aPoint_x[tmpPointID], aPoint_y[tmpPointID],
			    'Label for location number '+tmpPointID+' - '+aPoint_name[tmpPointID],
			    dir_label_numbers+(tmpPointID)+image_label_ext,'number');
			Element.removeClassName('star_'+tmpPointID, 'star_on');
			//Element.removeClassName('star_info_'+tmpPointID, 'star_on');
			Element.addClassName('star_'+tmpPointID, 'star_off');
			//Element.addClassName('star_info_'+tmpPointID, 'star_off');
			$('star_'+tmpPointID).innerHTML = 'Save this';
		}
	} else {
		alert("Cookies are NOT supported in your browser at this time!")
	}

}
/*
 * =Saved Points Update
 * @update the 'points_saved' layer with information from the cookie
 */
function savedPointsUpdate(){
	if (bCookies==1) {
		var tmpTxt = "<ul>";
		aCookies = em_cookies_parse();
		for(var i=0, tmpC=aCookies.length;i<tmpC;i++) {
			tmpTxt += '<li'+(i%2==1?' class="x"':'')+'>';
			var tmpLayerIndex = getLayerIndexByLayerID(aCookies[i][1]);
			
			tmpTxt += (isIE?'<div class="icon_info" id="icon_label_'+aCookies[i][1]+'_'+aCookies[i][2]+'" title="Icon for '+LayerName[tmpLayerIndex]+'"><div style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\''+LayerSwatch[tmpLayerIndex].src+'\')">&nbsp;</div></div>':'<img src="'+LayerSwatch[tmpLayerIndex].src+'" alt="Icon for '+LayerName[tmpLayerIndex]+'" />');
			tmpTxt += aLetters[i]+") ";
			tmpTxt += '<a href="?a=jump&lat='+aCookies[i][4]+'&long='+aCookies[i][5]+'&name='+escape(aCookies[i][3])+'&psort='+aCookies[i][7]+'&lid='+aCookies[i][1]+'&pid='+aCookies[i][2]+'" title="View '+aCookies[i][3]+'" class="cookie_jump">'+aCookies[i][3]+'</a>';
			//tmpTxt += '<p>Lat:'+aCookies[i][4]+', Long:'+aCookies[i][5]+'</p>';
			tmpTxt += '<div class="plisting">\n';
			//tmpTxt += '<div class="cookie_notes"><label>Notes:</label><span>'+aCookies[i][6]+'</span></div>';
			tmpTxt += '<a href="?a=cookie_delete&cname='+aCookies[i][0]+'" class="cookie_delete">Delete</a>';
			//tmpTxt += ' | <a href="?a=cookie_edit&cname='+aCookies[i][0]+'" title="Edit" class="cookie_edit">Edit</a>';
			/*for(var k=0, tmpV=aCookies[i].length;k<tmpV;k++) {
			tmpTxt += aCookies[i][k]+", ";
			}*/
			tmpTxt += "</div></li>";
		}
		tmpTxt += "</ul>";
	} else {
		var tmpTxt = '<p>You can not save points because your web browser does not accept <a href="help/#cookies" class="external">cookies</a>. If you wish to save points and then please <a href="help/#cookies" class="external">get help activating cookies</a>.</p>\n';
	}
	while($('points_saved').firstChild) {
		$('points_saved').removeChild($('points_saved').firstChild);
	}
	new Insertion.Bottom($('points_saved'), tmpTxt);
	Behaviour.apply();
}
//http://maps.cattco.org/website/tourism/viewer.htm?a=jump&lat=1162866.75027578&long=907484.269416659&name=Scotch%20Grove%20Farm%20B%20%26amp%3B%20B%20%28Delevan%29&psort=1&lid=40&pid=7
/*
* =Is Point Cookie
* @Does the Point have a Cookie associated with it?
*/
function isPointCookie(tmpLayer_id, tmpPoint_arc_id) {
	return readCookie(cookie_prefix+tmpLayer_id+"_"+tmpPoint_arc_id);
}
/**
* =SET COOKIE
* @set fValue of cookie
*/
function setCookie(fName, fValue, fTime) {
	var fExp    = "";
	var fDomain = (em_viewer_domain) ? em_viewer_domain : "";
	if (fTime) {
		var fDate   = new Date();
		fDate.setTime((fTime * 60 * 60 * 24 * 1000) + fDate.getTime());// # of days
		fExp        = fDate.toGMTString();
	}
    document.cookie = fName + "=" + entitiesToValues(fValue) + ";expires=" + fExp + ";domain="  + fDomain + ";path="+em_viewer_path+";";
    //alert("Cookie! "+fName + "=" + entitiesToValues(fValue) + ";expires=" + fExp + ";domain="  + fDomain + ";path="+em_viewer_path+";");
    //alert("Cookie! "+fName + "=" + fValue + ";domain="  + fDomain + ";path=" + em_viewer_path +";expires=" + fExp);
}
/**
 * =READ COOKIE
 * @read value of cookie
 */
function readCookie(fName) {
    var cookieName  = fName + "=";
    var cookieArray = document.cookie.split(';');
    for (var i=0, n=cookieArray.length;i<n;i++) {
        var cookie = cookieArray[i];
        while (cookie.charAt(0) == ' ') {
            cookie = cookie.substring(1, cookie.length);
        }
        if (cookie.indexOf(cookieName) == 0) {
        	//alert('cookie '+cookieName+' found');
            return cookie.substring(cookieName.length, cookie.length);
        }
    }
    //alert("cookie "+cookieName+" not found");
    return null;
} //readCookie()

/**
 * =DELETE COOKIE
 * @remove value of cookie
 */
function deleteCookie(fName) {
    setCookie(fName, "", -1);
} //deleteCookie()

/*
 *=jump to point
 *@creates a map that has the point's layer on and
 * opens the information layer about that point
 */
function jumpToPoint(xIn, yIn, tmpLayerID, tmpPointID, pointName) {
	// parse cookie to turn on layer
	/* aTmpC[0] // layer ID, aTmpC[1] // point ID */
	//alert('layerID_pointID='+tmpLayerID+'_'+tmpPointID);

	oPointFlagged['layerID'] = tmpLayerID;
	oPointFlagged['pointID'] = tmpPointID;
	// generate XML for request
	var mMarginW = 0;
	var mMarginH = 0;
    mMarginW = Math.abs(maxX_limit-minX_limit) * selectPointMargin;
	mMarginH = Math.abs(maxY_limit-minY_limit) * selectPointMargin;
	var xNum = parseFloat(xIn);
	var yNum = parseFloat(yIn);
	var tmpEnv = '<ENVELOPE minx="' + (xNum - mMarginW) + '" miny="' + (yNum - mMarginH) +'" maxx="' + (xNum + mMarginW) +'" maxy="' + (yNum + mMarginH) + '" />';
	labels_toggle('saved', true);
	// showGeocode = true;
	// geocode = geocodeGenerate((tmpLayerID+'_'+tmpPointID), pointName, xNum, yNum, '6,86,6', '20', '255,255,255', '255,255,255');
	//alert(tmpLayerID+'_'+tmpPointID+' '+ pointName+' '+xNum+' '+yNum);
	getMap(tmpEnv, true);
}
/*
 *=zoom to point
 *@taken from the original viewer ... NEEDS to be modified for this viewer
 * ie. zoomToPoint(1089904.96250504,820077.21987169, true, '303 COURT ST')
 */
function zoomToPoint(xIn, yIn, drawIt,theLabel) {
	// alert(xIn + "," + yIn);
	var mWMargin = 0;
	var mHMargin = 0;
	mWMargin = Math.abs(limitRight-limitLeft) * selectPointMargin;
	mHMargin = Math.abs(limitTop-limitBottom) * selectPointMargin;
	var xNum = parseFloat(xIn);
	var yNum = parseFloat(yIn);
	saveLastExtent();
	eLeft = xNum - mWMargin;
	eRight = xNum + mWMargin;
	eTop = yNum + mHMargin;
	eBottom = yNum - mHMargin;
	if (drawIt) {
		showGeocode=true;
		geocodeX=xNum;
		geocodeY=yNum;
		geocodeLabel=theLabel;
	}
	sendMapXML();
}
//alert("Cookies");