/*
  Assumes webserver had directory "/data" where the individual comment files live
  Webserver needs to be set to send 'no-store' header for these files, so they're
  not cached. Otherwise, as a user updates the data, it is not reflected back to him,
  since he'll retrieve an older, cached copy (without his mods).
  <Directory "/fullpath/data/">
     Header set Cache-Control "max-age=0, no-store"
  </Directory>
 */

/* To add a new technology:
   1) add the xml element name (lower case) to TechList
   2) add display name to TechNameList, in same position as TechList
      order is not important, though both lists must have _same_ order
   3) Add to ChargerVisible()
(Note, you'll still need to update the control panel and likely other places)
*/


var PrecisifierURL = "http://www.evchargermaps.com/precisifier.html";

/*
Changed from "http://chargerfinder.com/Projects/GoogleMaps/Precisifier.html";
    by Tom Dowling 5/10/08
*/


var ChargerMarkerArray = new Array();
var TechList =    new Array ("spi", "avc", "othercond", "lpi", "tsl", "dcq", "j1772");
var TechNameList = new Array ("SPI", "Avcon", "Other", "LPI", "TSL", "DCQ", "J1772");

// ******** right click menu *****************
function onMapRightClick(pixel, url, obj) {
    if (obj.charger){
	var m = makeChargerMenu(obj.charger, pixel);
    }
}

function makeChargerMenu(charger, pixel) {
    var m = new Menu(charger.name, charger);
    m.addItem("Report this site as:");
    m.addItemSelectable("...Working", charger.working);
    m.addItemSelectable("...Not Working", charger.notWorking);
    m.addItemSelectable("Add comment...", charger.addComment);
    m.openMenu(pixel, null, charger);
    return m;
}

var MarkerMgr;
function updateChargerDisplay() {
    var vizArray = new Array();
    for (var i=0;i<ChargerMarkerArray.length;i++){
	if (ChargerVisible(ChargerMarkerArray[i].charger)) {
	    vizArray.push(ChargerMarkerArray[i]);
	} // else {
// 	    MyMarkerManager.removeMarker(ChargerMarkerArray[i]);
// 	}
    }
    MyMarkerManager.clearMarkers();
    MyMarkerManager.addMarkers(vizArray, 1);
    MyMarkerManager.refresh();
}

function ChargerVisible(charger) {
    var lpi = $('lpi');
    var spi = $('spi');
    var avc = $('avc');
    var oc  = $('oc');
    var tsl = $('tsl');
    var dcq = $('dcq');
    var j1772 = $('j1772');
    if (charger.lpi && lpi.checked) return true;
    if (charger.tsl && tsl.checked) return true;
    if (charger.spi && spi.checked) return true;
    if (charger.avc && avc.checked) return true;
    if (charger.dcq && dcq.checked) return true;
    if (charger.j1772&&j1772.checked) return true;
    if (charger.othercond && oc.checked) return true;
    
    return false;
}


function Charger(root){
    var latlng = XmlGetValue(root, "latlng");
    
    this.lat = parseFloat(latlng.split(",")[0]);
    this.lng = parseFloat(latlng.split(",")[1]);
    this.point = new GLatLng(this.lat, this.lng);
    this.name = XmlGetValue(root, "name");
    this.id = XmlGetValue(root, "id");
    this.restricted = XmlGetValue(root, "restricted");
    this.address = XmlGetValue(root, "address");
    this.pay = XmlGetValue(root, "pay");
    this.charger = this;
    this.city = XmlGetValue(root, "city");

    for (var t=0;t<TechList.length;t++){
	var list = root.getElementsByTagName(TechList[t]);
	for (var i=0;i<list.length;i++){
	    // we expect either zero or one elements in list
	    eval("this."+TechList[t]+"= new Object(); tl = this."+TechList[t]+";");
	    tl.number = parseInt(list[i].getAttribute("number"));
	    tl.up = parseInt(list[i].getAttribute("up"));
	    tl.down = parseInt(list[i].getAttribute("down"));
	    tl.marginal = parseInt(list[i].getAttribute("marginal"));
	    tl.unknown = tl.number - tl.up - tl.down - tl.marginal;
	}
    }

    this.status = XmlGetValue(root, "status"); // Up, Down, Marginal?
    this.icon = gicons[this.status];
    
    this.title = this.name+": "+ this.status;

    this.marker = new GMarker(this.point, {icon:this.icon, title:this.title});
    this.marker.charger = this;
    this.marker.disableDragging();
    GEvent.bind(this.marker, "click", this, this.onClick);
    return this.marker;
};

var SelectedChargerMarker=null;
Charger.prototype.indexFunction = function(marker, b) {
    // for 'sinking' the spot marker under the balloons
    return GOverlay.getZIndex(marker.getPoint().lat()) - 1000;
};

Charger.prototype.onClick = function() {
    if (SelectedChargerMarker != null) {
	map.removeOverlay(SelectedChargerMarker);
    }
    SelectedChargerMarker = new GMarker(this.point, {zIndexProcess:this.indexFunction, icon:gicons['spot'], title:"Selected"});
    map.addOverlay(SelectedChargerMarker);

    var pay = "";
    if (this.pay == "yes"){
	pay = "<br/><b>Pay Parking</b>";
    }
    var restricted = "";
    if (this.restricted == "yes") {
	restricted = "<br/><b>Restricted Parking</b>";
    }
    
    var tech = "<table style='border-collapse:collapse;'>";
    for (var t=0;t<TechList.length;t++){
	var thisTech;
	eval("thisTech = this."+TechList[t]+";");
	if (thisTech != null) {
	    var status = "";
	    var status_color = "white";
	    if (thisTech.up == thisTech.number) {
		status_color = "green";
		if (thisTech.number > 1){
		    status = "All working";
		} else {
		    status = "Working";
		}
	    } else if (thisTech.down == thisTech.number){
		status_color = "red";
		if (thisTech.number > 1) {
		    status = "None working";
		} else {
		    status = "Not working";
		}
	    } else {
		status_color = "yellow";
		if (thisTech.up > 0) status += "Up: "+thisTech.up;
		if (thisTech.down > 0) status += "Down: "+thisTech.down;
		if (thisTech.marginal > 0) status += "Marginal: "+thisTech.marginal;
		if (thisTech.unknown > 0) status += "Unknown: "+thisTech.unknown;
	    }
	    tech += "<tr><td><span style='background:"+status_color+"'>&nbsp;</span></td>"+
		"<td><b>"+thisTech.number + " " + TechNameList[t] + "</b>:</td>"+
		"<td>"+status+"</td></tr>";
	}
    }
    tech += "</table>";
    
    
    // I'm thinking that the Precisifier should really be in the detail view, not here...
    //     "<a href='http://chargerfinder.com/Projects/GoogleMaps/Precisifier.html?"+
    //     "SiteID=" + this.id+
    //     ",SiteName=" + encodeURIComponent(this.name)+
    //     ",lng=" + this.point.lng()+
    //     ",lat=" + this.point.lat()+
    //     "' target='Precisifier for " + this.id + "'>(Precisifier)</a>"+
    
    $('selected_site').innerHTML = "<div style='float:left'><img src='"+gicons[this.status].image + "'></div>" +
    "<a " +
    "href=http://www.evchargernews.com/regions/" + this.id + ".htm " +
    "target='EVCN " + this.id + "'>" + this.name + "</a>"+
    "<br />" +this.address + 
    pay +
    restricted +
    tech;
    
    var filename = "/data/"+this.id;
    var name = this.name;
    $('site_details').innerHTML = "<form onsubmit=''>"+
    "<input type='button' value='Add Comment...' onclick='email_status(this.parentNode.parentNode.charger,null)'/>"+
    "<input type='button' value='Precisifier...' onclick='window.open(" +
        '"'+PrecisifierURL+'?SiteID='+this.id+
        ',SiteName='+encodeURIComponent(this.name)+
        ',lng='+this.lng+',lat='+this.lat+'"'+
    ");'/></form>";
    $('site_details').charger = this;
    
    GDownloadUrl(filename, function(data,responseCode) {
	    // Need to check file is returned -- if no file is found, I don't want to
	    // display the "Not Found" message...
	if (responseCode == 200){
	    $('site_details').innerHTML += data;
	} else {
	    $('site_details').innerHTML += "No comments";
	}
	try{
	    console.log("Iscroller refresh");
	    setTimeout(function(){IScroller.refresh();console.log("after refresh");},1000);
	} catch(e) {;}
	});
};

Charger.prototype.working = function(pixel, url, obj) {
    // pixel is valid, url and obj are undefined.
    // 'this' should point to menu item,
    var charger = this.menu.obj;
//     alert(charger.name+" is now set to working");
//     charger.marker.setImage("Markers/mm_20_green.png");
    email_status(charger, "Working");
    this.clicked();
};

Charger.prototype.notWorking = function(pixel, url, obj) {
    // pixel is valid, url and obj are undefined.
    // 'this' should point to menu item
    var charger = this.menu.obj;
//     alert(charger.name+ " is now set to not working");
//     charger.marker.setImage("Markers/mm_20_red.png");
    email_status(charger, "Not Working");
    this.clicked();
};

Charger.prototype.addComment = function (pixel, url,obj){
    // pixel is valid, url and obj are undefined.
    // 'this' should point to menu item
    var charger = this.menu.obj;
    //addComment(charger);
    email_status(charger, "");
    this.clicked();
};


var gicons=[];
var smallIcon = new GIcon();
smallIcon.shadow = "Markers/mm_20_shadow.png"; 
smallIcon.iconSize = new GSize(12, 20); 
smallIcon.shadowSize = new GSize(22, 20); 
smallIcon.iconAnchor = new GPoint(6, 20); 
smallIcon.infoWindowAnchor = new GPoint(5, 1); 

gicons["Up"] = new GIcon(smallIcon, "Markers/mm_20_green.png");
gicons["Down"] = new GIcon(smallIcon, "Markers/mm_20_red.png");
gicons["Marginal"] = new GIcon(smallIcon, "Markers/mm_20_orange.png");
gicons["Unknown"] = new GIcon(smallIcon, "Markers/mm_20_blue.png");

var largeIcon = new GIcon();
largeIcon.shadow = "Markers/shadow50.png";
largeIcon.iconSize = new GSize(20,34);
largeIcon.shadowSize = new GSize(37,34);
largeIcon.iconAnchor = new GPoint(10,34);
largeIcon.infoWindowAnchor = new GPoint(5,1);
gicons['Down_large'] = new GIcon(largeIcon,"Markers/red.png");
gicons['Up_large'] = new GIcon(largeIcon,"Markers/green.png");
gicons['Marginal_large'] = new GIcon(largeIcon,"Markers/orange.png");
gicons['Unknown_large'] = new GIcon(largeIcon,"Markers/blue.png");

var baseIcon = new GIcon();
baseIcon.iconSize = new GSize(15,15);
baseIcon.shadowSize = new GSize(0,0);
baseIcon.iconAnchor = new GPoint(7,7);
gicons["spot"] = new GIcon(baseIcon, "Markers/spot.png");

