// JavaScript Document


/*
 *  TOOLTIP DATA FUNCTIONS
 *
 *
v*/
function setTooltipData() {
	if(httpObj.readyState == 4){
	    
	    //If we are in viewing mode and the tooltip hasn't been destroyed
	    //update the tooltip content and size
	    if (!edit && currentHotspot != null) {
	    currentHotspot.popup.contentDiv.innerHTML = httpObj.responseText;
	    currentHotspot.popup.updateSize();
	    } 
	    if (edit && currentHotspot != null) {
            hotspotSelectControl.unselect(currentHotspot);
	        popup = new OpenLayers.Popup.FramedCloud("tooltip", 
                currentHotspot.geometry.getBounds().getCenterLonLat(),
                null,
                httpObj.responseText, 
                null, false, onEditPopupClose);
            currentHotspot.popup = popup;
            map.addPopup(popup);
            
            hotspotSelectControl.deactivate();
            hotspotDragControl.activate();
        } else {
            edit = false;
        }
        
	}
}
function getTooltipData(featureID) {
    //set the currentMarker global to the passed marker ref
	httpObj = getHTTPObject();
	if (httpObj != null) {
	    var requestStr = "/cgi/getHotspotContent.py?hotspot="+featureID;
	    if (edit) {
	        requestStr += "&edit=1";
	    }
	    if (token != null) {
	        requestStr += "&token="+token;
	    }
		httpObj.open("GET",requestStr);
		httpObj.send(null);
		httpObj.onreadystatechange = setTooltipData;
	}
	//DEBUG: alert(markerID);
}

function onFeatureDrag(feature, pixel) {

}

function onFeatureStart(feature, pixel) {
    
    
    //If moving the non-currentHotspot, save location to reset position after drag
    if (currentHotspot.popup != null) {
        
        if (feature != currentHotspot) {
            movingCurrentHotspot = false;
            originalLoc = new OpenLayers.Geometry.Point(feature.geometry.x, feature.geometry.y);
        } else {
            movingCurrentHotspot = true;
        
            //save the current values to transfer to next popup open
            currentDetails.desc = document.forms.editCH.editDesc.value;
            currentDetails.name = document.forms.editCH.editName.value;
            currentDetails.type = document.forms.editCH.editType.value;
        
            map.removePopup(feature.popup);
        }
     } else {
         reloadHotspot();
     }
    
    
}

function onFeatureComplete(feature, pixel) {
    if (feature == null) {
        onEditPopupClose(null);
        return null;
    }
    //Reset marker position if moving the non-current hotspot
    if (!movingCurrentHotspot) {
        hotspotLayer.removeFeatures([feature]);
        feature.geometry = originalLoc;
        originalLoc = null;
        hotspotLayer.addFeatures([feature]);
    } else {
        currentHotspot = feature;
        feature.popup.lonlat = feature.geometry.getBounds().getCenterLonLat();
        map.addPopup(feature.popup);
        
        //restore the current values into the new (this) open popus
        document.forms.editCH.editDesc.value = currentDetails.desc;
        document.forms.editCH.editName.value = currentDetails.name;
        document.forms.editCH.editType.value = currentDetails.type;
    }
    
}

function onEditPopupClose(evt) {
    map.removePopup(currentHotspot.popup);
    edit = false;
    hotspotDragControl.deactivate();
    hotspotSelectControl.activate();
    movingCurrentHotspot = null;
    currentHotspot.style.externalGraphic = icons[currentHotspot.attribute.type];
}



function getEditContent(hs_id) {
    
}

function editHotspot(hs_id) {
    edit = true;
    currentHotspot.style.externalGraphic = icons['edit'];
    getTooltipData(hs_id);
}

function saveHotspot(hs_id) {

    document.getElementById('footerStringTT').innerHTML = "saving... | <a href='javascript:deleteHotspot();'>delete</a>";
    movingCurrentHotspot = null;
    getSaveContent(currentHotspot.id);
    //SEND IT OFF TO DO WHATEVER
}

function getSaveContent(hs_id) {
    httpObj = getHTTPObject();
	if (httpObj != null) {
	    var point = revOsmLonLat(currentHotspot.geometry.x, currentHotspot.geometry.y);
	    var requestStr = "/cgi/setHotspotContent.py"
	    var params = "hotspot="+hs_id;
	    params += "&name="+document.forms.editCH.editName.value;
	    params += "&desc="+document.forms.editCH.editDesc.value;
	    params += "&type="+document.forms.editCH.editType.value;
	    params += "&lon="+point.lon;
	    params += "&lat="+point.lat;
	    if (token != null) {
	        params += "&token="+token;
	    }
	    
		httpObj.open("POST",requestStr, true);
        //Send the proper header information along with the request
        httpObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        httpObj.setRequestHeader("Content-length", params.length);
        httpObj.setRequestHeader("Connection", "close");
        
		httpObj.onreadystatechange = setSaveContent;
        httpObj.send(params);
    }
        
}

function setSaveContent() {
    if (httpObj.readyState == 4) {
        //DEBUG: alert(httpObj.responseText);
        var success = eval("(" + httpObj.responseText + ")"); //the collection of hotspots
        reloadHotspot();
       /* if (success == true) {
            
            hotspotDragControl.deactivate();
            hotspotSelectControl.activate();
            
            //remove the editing popup
            map.removePopup(currentHotspot.popup);
            currentHotspot.popup.destroy();
            currentHotspot.popup = null;
            
            hotspotLayer.drawFeature(currentHotspot);
        } else {
            //TODO: Handle a false save
            
        }
        
        //reload the hotspot
        var hsID = currentHotspot.id;
        hotspotLayer.destroyFeatures(currentHotspot);
        currentHotspot = null;
        addHotspot(hsID);*/
    }
}

function deleteHotspot() {
    document.getElementById('footerStringTT').innerHTML = "<a href='javascript:editHotspot("+currentHotspot.id+");'>edit</a> | deleting...";
    getDeleteHotspot(currentHotspot.id);
    
}

function getDeleteHotspot(hs_id) {
    httpObj = getHTTPObject();
    if (httpObj != null) {
        httpObj.open("GET","/cgi/setDeleteHotspot.py?hotspot="+hs_id+"&token="+token);
        httpObj.send(null);
        httpObj.onreadystatechange = setDeleteHotspot;
    }
}


function setDeleteHotspot() {
    if (httpObj.readyState == 4) {
        var success = eval("(" + httpObj.responseText + ")");
        if (success == true) {
            var hs = currentHotspot;
            hotspotSelectControl.unselect(currentHotspot);
            hotspotLayer.destroyFeatures(hs);
        }
    }
}

function reloadHotspot() {
    edit = false;
    
    hotspotDragControl.deactivate();
    hotspotSelectControl.activate();
    
    //remove the editing popup
    map.removePopup(currentHotspot.popup);
    currentHotspot.popup.destroy();
    currentHotspot.popup = null;
    
    var hsID = currentHotspot.id;
    hotspotLayer.destroyFeatures(currentHotspot);
    currentHotspot = null;
    addHotspot(hsID);
}

function addHotspot(hotspot) {
    httpObj = getHTTPObject();
    if (httpObj != null) {
        httpObj.open("GET","/cgi/getMarkers.py?hotspot="+hotspot);
        httpObj.send(null);
        httpObj.onreadystatechange = setInitHotspots;
    }
}

function addNewHotspot() {

    if (currentHotspot != null) {
        if (edit == true) {
            onEditPopupClose(null);
        } else {
            deselectHotspot();
        }
    }
    
    
    
    var coords = map.getCenter();
    centerLoc = revOsmLonLat(coords.lon, coords.lat);
    httpObj = getHTTPObject();
   
    if (httpObj != null) {
        var requestStr = "/cgi/setNewHotspot.py?region="+currentRegion;
        requestStr += "&lon="+centerLoc.lon;
        requestStr += "&lat="+centerLoc.lat;
        requestStr += "&token="+token; 
        httpObj.open("GET",requestStr);
        httpObj.send(null);
        httpObj.onreadystatechange = setNewHotspot;
    }
}

function setNewHotspot() {
    if (httpObj.readyState == 4) {
        adding = eval("(" + httpObj.responseText + ")");
        if (adding != null) {
            addHotspot(adding);
        }
        
    }
}

/*
 *  HOTSPOT SELECTION
 *
 *
v*/

function deselectHotspot() {
    if (currentHotspot.popup != null) {
        hotspotSelectControl.unselect(currentHotspot);
    }
}

function onFeatureSelect(feature) {
    currentHotspot = feature;
    popup = new OpenLayers.Popup.FramedCloud("tooltip", 
        currentHotspot.geometry.getBounds().getCenterLonLat(),
        null,
        tt_content, 
        null, false, onPopupClose);
        currentHotspot.popup = popup;
        map.addPopup(popup);
        getTooltipData(currentHotspot.attribute.ident);
    
}

function onFeatureUnselect(feature) {
            map.removePopup(feature.popup);
            feature.popup.destroy();
            feature.popup = null;
            if (!edit) {
                currentHotspot = null;
            }
        }
        
function onPopupClose(evt) {
            hotspotSelectControl.unselect(currentHotspot);
}
        
/*
 *  HOTSPOT INITIALISATION
 *
 *
v*/

function getInitHotspots(regionName) {
    httpObj = getHTTPObject();
    if (httpObj != null) {
        httpObj.open("GET","/cgi/getMarkers.py?region="+regionName);
        httpObj.send(null);
        httpObj.onreadystatechange = setInitHotspots;
    }
}

function setInitHotspots() {
    if (httpObj.readyState == 4) {
        var entry = eval("(" + httpObj.responseText + ")"); //the collection of hotspots
        if (entry != null) {
            for (var x in entry) {
                hotspots[x] = createHotspot(osmPoint(entry[x].lng,entry[x].lat),entry[x].id, entry[x].name, entry[x].type);
            }
            hotspotLayer.addFeatures(hotspots);
            if (adding != null) {
                adding = null;
                currentHotspot = hotspots[0];
                hotspotSelectControl.select(currentHotspot);
            
            }
            hotspots = new Array();
        }
    }
}

function createHotspot(point, ident, name, type) {
    var localHotspot = new OpenLayers.Feature.Vector(point);
    localHotspot.style = {};
    localHotspot.style.externalGraphic = icons[type];
    localHotspot.style.graphicWidth = 20;
    localHotspot.style.graphicHeight = 34;
    localHotspot.style.pointRadius = 12;
    localHotspot.attribute = {};
    localHotspot.id = ident;
    localHotspot.attribute.ident = ident;
    localHotspot.attribute.name = name;
    localHotspot.attribute.type = type;
    localHotspot.popup = null;
    return localHotspot;
}
//UTILITY FUNCTIONS




/*
 *  LOGIN FUNCTIONS
 *
 *
v*/

function initLogin() {
    
    if (currentHotspot != null) {
        deselectHotspot();
    }
    
    //initialise token/user details
    token = null;
    currentUser = null;
    
    //content set here, and optionally displays loginMsg (error) should login have
    //failed for whatever reason
    document.getElementById("loginWindow").innerHTML = loginMsg+"<form name='login'><p>Username:<br /><input type='text' name='user' size='15' onKeyPress='checkEnter(event)' /></p><p>Password:<br /><input type='password' name='pass' size='15' onKeyPress='checkEnter(event)' /></p><p><input type='checkbox' name='remember' value='remember' onKeyPress='checkEnter(event)' /> remember me</p><p>[ <a href='http://blog.wifi-in-australia.com/wp-login.php?action=register' target='_blank'>Register</a> | <span id='loginWindowLoader'><a href='javascript:getLogin();'>Login</a> ]</span></p></form>";
    loginMsg = "";
    
    //PROCESS COOKIES
    loadCookies();
}

function loadCookies() {
    var sessionDetails = readCookie('wiau_token');
    var loginDetails = readCookie('wiau_login');
    //DEBUG alert(sessionDetails);
    if (sessionDetails != null) {
       loadSessionCookies(sessionDetails);
    } else if (loginDetails != null) {
        loadLoginCookies(loginDetails);
    }
    
}

function loadSessionCookies(sessionDetails) {
     var sessionTokens = sessionDetails.split("*");
        //DEBUG alert(sessionTokens[0]+"   -    "+sessionTokens[1]);
        currentUser = sessionTokens[0];
        token = sessionTokens[1];
        //DEBUG alert("boo");
        document.getElementById("loginWindow").innerHTML = "<p><strong>Logged in as:</strong><br />"+currentUser+"</p><p>[ <a href='javascript:initLogout();'>logout</a> ]</p>";
        //DEBUG alert("miss");
}

function loadLoginCookies(loginDetails) {
    var loginTokens = loginDetails.split('*');
    createCookie('wiau_login',loginDetails,28);
    getLogin(loginTokens[0],loginTokens[1]);
}

function initLogout() {
    eraseCookie('wiau_token');
    eraseCookie('wiau_login');
    initLogin();
}

function getNewMap(validMap) {
    
    //alert('submitted');
    
    var msgElement = document.getElementById('addMapMessage');
    msgElement.style.display = "none";
    msgElement.innerHTML = '';
    
    if (validMap == false) {
        msgElement.style.display = "block";
        msgElement.innerHTML = '<p class="failure">Map name is not valid, or already exists - choose another</p>';
        return false;
    }
    
    httpObj = getHTTPObject();
	if (httpObj != null) {
	    var point = revOsmLonLat(map.getCenter().lon, map.getCenter().lat);
	    var requestStr = "/cgi/setNewMap.py"
	    var params = "state="+document.forms.newmap.state.value;
	    params += "&longname="+document.forms.newmap.longname.value;
	    params += "&shortname="+document.forms.newmap.shortname.value;
	    params += "&desc="+document.forms.newmap.desc.value;
	    params += "&lon="+point.lon;
	    params += "&lat="+point.lat;
	    params += "&zoom="+map.getZoom();
	    if (token != null) {
	        params += "&token="+token;
	    }
	    
		httpObj.open("POST",requestStr, true);
        //Send the proper header information along with the request
        httpObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        httpObj.setRequestHeader("Content-length", params.length);
        httpObj.setRequestHeader("Connection", "close");
        
		httpObj.onreadystatechange = setNewMap;
        httpObj.send(params);
    }
}

function setNewMap() {
    if (httpObj.readyState == 4) {
        var result = httpObj.responseText;
        var msgElement = document.getElementById('addMapMessage');
        msgElement.style.display = "block";
        msgElement.innerHTML = result;
        //If success, store token and name in page and session variables
        
    }
}

function getLogin(inUser,inPass) {
    var username = inUser;
    var password = inPass;
    
    //Deselect hotspots for the sake of logging in, makes life easier
    if (currentHotspot != null) {
        deselectHotspot();
    }
    
    //Load the username/password combo from the form if cookie not exists
    //Also sets the new login cookie if requested (28 days)
    if (username == undefined && password == undefined){
        username = document.forms.login.user.value;
        password = SHA1(document.forms.login.pass.value);
        if (document.forms.login.remember.checked) {
            createCookie('wiau_login',username+'*'+password,28);
        }
    }
    
    loginMsg = "";
    document.getElementById("loginWindowLoader").innerHTML = "loading...";
    httpObj = getHTTPObject();
	if (httpObj != null) {
		httpObj.open("GET","/cgi/getLogin.py?u="+username+"&p="+password);
		httpObj.send(null);
		httpObj.onreadystatechange = setLogin;
	}
}

function setLogin() {
    if (httpObj.readyState == 4) {
        var result = eval("(" + httpObj.responseText + ")");
        
        //If success, store token and name in page and session variables
        if (result.token != null) {
            currentUser = result.username;
            token = result.token;
            createCookie('wiau_token',currentUser+'*'+token,0);
            //DEBUG: alert(currentUser+'*'+token);
            
            document.getElementById("loginWindow").innerHTML = "<p><strong>Logged in as:</strong><br />"+currentUser+"</p><p>[<a href='javascript:initLogout();'>logout</a>]</p>";
            //TODO: delete cookie on logout
        } else {
            
            loginMsg = "<p><span class='loginMsg'>Incorrect Details</span></p>";
            initLogout();
        }
    }
}

//
//  UTILITY FUNCTIONS AHOY...
//  ...for handling cookies, keystrokes, AJAX calls, that kinda jazz
//

//This function is for the ENTER button submission of "submitless" forms

function checkEnter(e){ 
    var characterCode //literal character code will be stored in this variable

    if(e && e.which){ //if which property of event object is supported (NN4)
        characterCode = e.which;
    } else{
        characterCode = e.keyCode;
    }

    if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
        getLogin(); 
        return false;
    } else {
        return true;
    }

}

// AJAX HTTP OBJECT - FOR AJAX FUNCTIONS - TRY NOT TO TOUCH :)
//
// TODO: fix 
function getHTTPObject(){

	if (window.ActiveXObject) 
	   return new ActiveXObject("Microsoft.XMLHTTP");
	else if (window.XMLHttpRequest) 
		return new XMLHttpRequest();
	else {
		alert("Your browser does not support AJAX.");
		return null;
	}
}

//give day = 0 for browser session only
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

//returns null if cookie not found, otherwise returns value (string)
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
