// assumes global 'env' object defined in scope;

function Browser() {
    Browser.MSIE = "MSIE";
    Browser.FIREFOX = "Firefox";
    Browser.OTHER = "browser";
    
    this.type = null;
    
    var ua = navigator.userAgent;
    if(ua.indexOf(Browser.MSIE) >= 0){
        this.type = Browser.MSIE;
    }
    else if(ua.indexOf(Browser.FIREFOX) >= 0){
        this.type = Browser.FIREFOX;
    }
    else{
        this.type = Browser.OTHER;
    }   
    
    Browser.prototype.getType = function (){
        return this.type;
    }
    
    Browser.prototype.isMSIE = function (){
        return this.type == Browser.MSIE;
    }
    
    Browser.prototype.isFirefox = function (){
        return this.type == Browser.FIREFOX;
    }
}

function initLocationList(env, size){
	env.myLocations = new Array(); // Locations	
	maxCount = size;
}

function getLocation(index){
	return env.myLocations[index];
}

//return most recent location
function getTopLocation(){
	if(locCount == 0)
		return null;
	else	
		return env.myLocations[locCount-1];	
}

function getMostRecentTimeStamp(){
	if(locCount == 0)  
		return "0.0.0 at 0:0:0";  //12.02.22 at 12:23:12 
	else	
		return env.myLocations[locCount-1].timeStamp;	
}

function getLocationCount(){
	return locCount;
}

function setLocationCount(count){
	locCount = count;
}

//global locationCount
var locCount = 0;
var maxCount = 100; //default count; set from property in Ae-www.properties locationListSize
function getMaxCount(){
	return maxCount;
}

function addLocation(lat, lng, content){
	if(locCount < getMaxCount())
		env.myLocations[locCount++] = new Location(lat, lng, content);
}

function shiftList(updateCount){
	var i;
	var locCount = getLocationCount();
	var flagId;
	for(i=0; i<locCount-updateCount; i++){
		if(i < updateCount){
			flagId = env.myLocations[i].id;
			AeMap_deregisterFlag(env.myMap, flagId);	
		}
		env.myLocations[i] = env.myLocations[i+updateCount];
	}
	setLocationCount(locCount-updateCount);
}

function deleteTableRows(count){
	var i;
	var tableElem = document.getElementById("LocationTable");
	for(i=1; i <= count; i++){
		try{
		tableElem.deleteRow(getMaxCount()-i);		
		}catch(e){
			//silently ignore; there is a problem
		}
	}
}

function insertLocationInLocationList(loc){

	var tableElem = document.getElementById("LocationTable");
	//create new row insert at top of table
	var trElem = tableElem.insertRow(0);
	//add attributes
	trElem.onclick = function(){ handleOnClick2(loc.lat, loc.lng, loc.radius, loc.timeStamp) };
	
	//trElem.setAttribute("onClick", "javascript:handleOnClick(\"" +loc.lat+ "," +loc.lng + "," +loc.timeStamp +"\")");
	
	//create new cell
	var newTD = trElem.insertCell(0);
	newTD.setAttribute("valign", "midde");
	newTD.setAttribute("align", "center");
	if(myBrowser.isMSIE())
		newTD.setAttribute("className", "tablineseparator");
	else
		newTD.setAttribute("class", "tablineseparator");
	//create content of cell
	var	html = "<a href=\"javascript:void(0)\">\n";
		if (loc != null) html += "<img alt='LOC' width='15' height='15' border='0' src='" + loc.sImg  + "'/>\n";
		html += "</a>\n";
	   
	//add content to td
	newTD.innerHTML = html;
	
	//create new cell
	newTD = trElem.insertCell(1);
	newTD.setAttribute("valign", "top");
	if(myBrowser.isMSIE())
		newTD.setAttribute("className", "tablineseparator");
	else
		newTD.setAttribute("class", "tablineseparator");

	//create content of cell
 	html = loc.content + "<br>";   
 	
 	//add content to td
	newTD.innerHTML = html;

}

function handleOnClick(str){

	var location = str.split(",");
	//AeMap_panToLatLong(env.myMap, location[0], location[1]);
	AeMap_panToLatLongAndPixelDelta(env.myMap, location[0], location[1], 
            env.calloutLocLeft - (env.mapLeft+env.mapWidth/2) + env.calloutLocAnchorX,
            env.calloutLocBottom - (env.mapTop+ env.mapHeight/2) + env.calloutLocAnchorY);
	
	//populate callout and show 
	document.getElementById('calloutLoclat').value = location[0];
	document.getElementById('calloutLoclng').value = location[1];
	
	var time = location[2].split("at");
	document.getElementById('calloutLocdate').value = time[0];
	document.getElementById('calloutLoctime').value = time[1];
	document.getElementById('calloutLocradius').value = location[3];
	
	document.getElementById('calloutLoc').style.visibility = "visible"; 
}

function handleOnClick2(lat , lng, radius, timeStamp){

	AeMap_panToLatLongAndPixelDelta(env.myMap, lat, lng, 
            env.calloutLocLeft - (env.mapLeft+env.mapWidth/2) + env.calloutLocAnchorX,
            env.calloutLocBottom - (env.mapTop+ env.mapHeight/2) + env.calloutLocAnchorY);
	
	//populate callout and show 
	document.getElementById('calloutLoclat').value = lat;
	document.getElementById('calloutLoclng').value = lng;
	
	var time = timeStamp.split("at");
	document.getElementById('calloutLocdate').value = time[0];
	document.getElementById('calloutLoctime').value = time[1];
	document.getElementById('calloutLocradius').value = radius;
	document.getElementById('calloutLoc').style.visibility = "visible"; 
}

var TIME_OUT_TIME = 1800000;  //timeout in 30 minutes   
function setTimer(rate){
	refreshTimer = setInterval(updateLocation, rate);
}

function onTimeout(){
	clearInterval(refreshTimer);
}

function updateLocation(){
	
	var url = "MyAjaxLocation.do";
	url += "?timeStamp="+getMostRecentTimeStamp();
	var req = null;
	
	if (window.XMLHttpRequest) { // Non-IE browsers
      req = new XMLHttpRequest();
      try {
        req.open("GET", url, true);
      } catch (e) {
        alert(e);
      }
      req.send(null);
    } else if (window.ActiveXObject) { // IE
      req = new ActiveXObject("Microsoft.XMLHTTP");
      if (req) {
        req.open("GET", url, true);
        req.send();
      }
    }
    if(req)
    	req.onreadystatechange = function (){
    		
    	if (req.readyState == 4) { // Complete
			if (req.status == 200) { // OK response
			//handle response
			var event = req.responseXML.getElementsByTagName("event")[0];
			var action = event.getAttribute("action");
			var status = event.getAttribute("status");
				if (action == "refreshLocation") {
					if (status == "success") {
						var loclist = req.responseXML.getElementsByTagName("locList")[0];
						var locations = loclist.getElementsByTagName("loc");
						var numLocs = locations.length;
						if(numLocs > 0){
							//verify size of LocationList, and update if numLoc 
							//will cause LocationList to be greater than locationListSize
							//also need to delete corresponding locationList rows greater than locationListSize
							var locCount = getLocationCount();
							if(locCount + numLocs > getMaxCount()){
								shiftList(numLocs);
								deleteTableRows(numLocs);
							}
							//add new locations and put them on the page			
							for(i=0; i < numLocs; i++){
								var locElem = locations.item(i);
								//add new location
								addLocation(locElem.getAttribute("lat"), 
										    	   locElem.getAttribute("lng"), 
										    	   locElem.getAttribute("radius"), 
										    	   locElem.getAttribute("timestamp"));
								var loc = getTopLocation();
								//insert location into locationList part of page
								insertLocationInLocationList(loc);
								putFlagOnMap(loc);
							}
						}
					}else{
						//alert("failure");
						//silently ignore
					}
				}		
		 	}
   		}  		
 	 };
}

function updateLocationCallback(){
	if (req.readyState == 4) { // Complete
		if (req.status == 200) { // OK response
			//handle response
			var event = req.responseXML.getElementsByTagName("event")[0];
			var action = event.getAttribute("action");
			var status = event.getAttribute("status");
			if (action == "refreshLocation") {
				if (status == "success") {
					var loclist = req.responseXML.getElementsByTagName("locList")[0];
					var locations = loclist.getElementsByTagName("loc");
					var numLocs = locations.length;
					if(numLocs > 0){
						//verify size of LocationList, and update if numLoc 
						//will cause LocationList to be greater than locationListSize
						//also need to delete corresponding locationList rows greater than locationListSize
						var locCount = getLocationCount();
						if(locCount + numLocs > getMaxCount()){
							shiftList(numLocs);
							deleteTableRows(numLocs);
						}
						//add new locations and put them on the page			
						for(i=0; i < numLocs; i++){
							var locElem = locations.item(i);
							//add new location
							addLocation(locElem.getAttribute("lat"), 
									    	   locElem.getAttribute("lng"), 
									    	   locElem.getAttribute("radius"), 
									    	   locElem.getAttribute("timestamp"));
							var loc = getTopLocation();
							//insert location into locationList part of page
							insertLocationInLocationList(loc);
							putFlagOnMap(loc);
						}
					}
			}else{
				//alert("failure");
				//silently ignore
			}
		}		
	  }
   }
}

var flagId = 0;
function Location(lat, lng, content) {
	this.id = flagId++;
    this.lat = lat;
	this.lng = lng;
	this.content = content;
    this.sImg = setFlagImage(this);
}

function getTime(str){
  //12.02.22 at 12:23:12
  	if(str == null)
  		return new Date();
  		 
 	str = str.replace(" at ", "."); 
 	str = str.replace(/:/g, "."); 
 	var date1 = str.split(".");
  		
 	return new Date(date1[0], date1[1]-1, date1[2], date1[3], date1[4], date1[5]);
}

function setFlagImage(loc) {
	var sImg;
    sImg = 'http://www.alertpedia.com/images/icon_quake.GIF';
    return sImg;
}

function clearAe(gMsg) {
    
}

function initializeMyHomePageMap() {
  
    env.myMap = AeMap_initializeMyHomePage(env.mapName, env.defLat, env.defLong, env.defZoom, 
            	env.mapToolsX, env.mapToolsY, env.defStyle);
    //setupMapEventHandlers();
    
    var lastLat = 0;
    var lastLong = 0;
    var lastZoom = 0;

    var bb = findLocationBoundingBox();
    var delta = 0.01;
    if (env.myLocations.length > 1){
       AeMap_setView(env.myMap, bb.maxLat+delta, bb.minLong-delta, 
          bb.minLat-delta, bb.maxLong+delta);
    }
    putLocationsOnMap();
}

function initializeMap() {
    env.myMap = AeMap_initialize(env.mapName, env.defLat, env.defLong, env.defZoom, 
            	env.mapToolsX, env.mapToolsY, env.defStyle);
//    setupMapEventHandlers();
    
    var lastLat = 0;
    var lastLong = 0;
    var lastZoom = 0;

    var bb = findLocationBoundingBox();
    var delta = 0.01;
    if (env.myLocations.length > 1){
       AeMap_setView(env.myMap, bb.maxLat+delta, bb.minLong-delta, 
          bb.minLat-delta, bb.maxLong+delta);
    }
    putLocationsOnMap();
}

function locationBoundingBox(maxLat, minLong, minLat, maxLong) {
    this.maxLat = parseFloat(maxLat);
    this.minLong = parseFloat(minLong);
    this.minLat = parseFloat(minLat);
    this.maxLong = parseFloat(maxLong);
}

function findLocationBoundingBox() {
    var i;
    var minLat = parseFloat(90.0);
    var maxLat = parseFloat(-90.0);
    var minLong = parseFloat(180.0);
    var maxLong = parseFloat(-180.0);
    
    for (i=0; i< env.myLocations.length; i++){
        var loc = env.myLocations[i];
        if(parseFloat(loc.lat) < minLat){
            minLat = parseFloat(loc.lat);
        }
        if(parseFloat(loc.lat) > maxLat){
            maxLat = parseFloat(loc.lat);
        }
        if(parseFloat(loc.lng) < minLong){
            minLong = parseFloat(loc.lng);
        }
        if(parseFloat(loc.lng) > maxLong){
            maxLong = parseFloat(loc.lng);
        }
    }
    return new locationBoundingBox(maxLat, minLong, minLat, maxLong);
}


function putFlagOnMap(loc) {

    var sImg = setFlagImage(loc);
    var alt = loc.content;
 
    AeMap_registerFlag(env.myMap, loc.id, loc.lat, loc.lng,
            sImg, null, alt);
}

function putLocationsOnMap() {
    var i, loc;

    for (i=0; i< env.myLocations.length; i++){
        loc = env.myLocations[i];
        putFlagOnMap(loc);
    }
}

function setupMapEventHandlers() {
    var map = document.getElementById(env.mapName);
    addEventHandler(map, "mousedown", mapMouseDownHandler, false);
    
//    AeMap_setPanBeginCallback(env.myMap, hideAeForm);
//   AeMap_setZoomBeginCallback(env.myMap, hideAeForm);
    AeMap_setMapStyleCallback(env.myMap, setLocMapStyleAjax);
}


function addEventHandler(elmt, evType, handler, fCapture){
    if(elmt.addEventListener){
        elmt.addEventListener(evType, handler, fCapture);
    }
    else if(elmt.xattachEvent){
        elmt.attachEvent("on"+evType, handler);
    }
    else{
        elmt["oldon"+evType] = elmt["on"+evType]; //save
        elmt["on"+evType] = handler;
    }
}


function removeEventHandler(elmt, evType, handler, fCapture) {
    if(elmt.removeEventListener){
        elmt.removeEventListener(evType, handler, fCapture);
    }
    else if(elmt.xdetachEvent){
        elmt.detachEvent("on"+evType, handler);
    }
    else{
        elmt["on"+evType] = elmt["oldon"+evType]; //restore
    }
}

function cancelBubbling(evt) {
    if(evt.stopPropagation) evt.stopPropagation();
    else evt.cancelBubble = true;
}


function stopDefaultAction(evt) {
    if(evt.preventDefault) evt.preventDefault();
    else evt.returnValue = false;
}


function getEvent(evt) {
    return evt?evt:window.event;
}


function getKey(evt) {
    return myBrowser.isFirefox()?evt.which:evt.keyCode;
}


function getStyle(elmt) {
    if(document.defaultView){
        return document.defaultView.getComputedStyle(elmt, null);
    }
    else{
        return elmt.currentStyle;
    }
}


function getEventElement(evt, elmt) {
    if(document.addEventListener){
        return evt.currentTarget;
    }
    else if(document.xattachEvent){
        return evt.srcElement;
    }
    else{
        return elmt;
    }   
}


function mapMouseDownHandler(evt) {
   }


function mapMouseUpHandler(evt) {
   }


function mapMouseMoveHandler(evt) {
  
}


function flagMouseDownHandler(evt) {
   
}


function flagMouseUpHandler(evt) {
   
}


function flagMouseMoveHandler(evt) {
    
}

function flagMouseClickHandler(evt) {
   
}


function getServerErrorMessages() {
    var sErrors = document.getElementById(env.AeErrorDivName).innerText.split("\n");
    env.serverErrorMsgs = "";
    var x, s;
    for(x = 0; x<sErrors.length; x++){
        s = sErrors[x].replace(/\s+/g, " ");
        if(s != "" && s != " "){
            env.serverErrorMsgs += (s + "\n");
        }
    }
    return env.serverErrorMsgs;
}

// clear server error messages
function clearServerErrorMessages() {
	document.getElementById("pageErrors").innerText = "";
    env.serverErrorMsgs = "";
    clearErrors();
}

function checkAndHandleServerErrors() {
    if(getServerErrorMessages() == "")
        return;
        
}

function markBadUserNames(fieldValue, delimiter, badEntries)
{
	var marker = "\"";
	var nameArray = fieldValue.split(delimiter);
	var newFieldValue = "";
	
	for(i=0;i<nameArray.length;i++) {
		for(j=0;j<badEntries.length;j++) {
			if (nameArray[i] == badEntries[j]) {
				newFieldValue += marker + nameArray[i] + marker; break;	
			}
		}
		if (j == badEntries.length) {
			newFieldValue += nameArray[i];
		}
		if (i < nameArray.length-1)
			newFieldValue += delimiter;
	}
	return newFieldValue;
}

//clear error message area
function clearErrors() {
    document.getElementById('pageErrors').innerText = "";
    document.getElementById('targetError').innerHTML = "";
    document.getElementById('messageError').innerHTML = "";
    document.getElementById('startDateError').innerHTML = "";
    document.getElementById('endDateError').innerHTML = "";
    document.getElementById('radiusError').innerHTML = "";
    clearPredicateErrors();
}

var prevKey;
function inMessageCapacityD(evt, elmt) {
    if(myBrowser.isFirefox()){
        if(elmt.value.length < env.AeMaxLength){
            return true;
        }
        if(getSelection().length>0){
            return true;
        }
        var keyCd = getKey(evt);
        var okChars = new Array(8, 37, 38, 39, 40, 46);
        for(var i=0;i<okChars.length;i++) 
            if(okChars[i]==keyCd){
                return true;
            }
        if((keyCd == 65 || keyCd == 67) && prevKey == 17){
            return true;
        }
        prevKey=keyCd;
        return false;
    }
    else{
        return true;
    }
}


function inMessageCapacityP(evt, elmt) {
    if(myBrowser.isMSIE()){
        return adjustedLength(elmt.value) < env.AeMaxLength;
    }
    return true;
}


function adjustedLength(str) {
    return str.replace(/\r/g,'').length;
    if(myBrowser.isMSIE()){
    }
    else{
        return str.length;
    }
}


function showMessageCapacity(evt, elmt, ctrName) {
    var len = adjustedLength(elmt.value);
    document.getElementById(ctrName).value = env.AeMaxLength - len;
}



function updateImage(imageName, imageSource) {
	if ((img=Ae_findObj(imageName)) != null) img.src = imageSource;
}




