var points = new Array();
var counter = 0;
var poi_id = "p";
var map;
var output_types = new Array();
output_types['RDF'] = 0;
output_types['API'] = 1;
output_types['JS']  = 2;
output_types['EZ']  = 3;
var out_form = output_types['RDF'];

if (navigator.appName == 'Microsoft Internet Explorer') {
    document.ondblclick = handleDblClick;
} else {
    window.ondblclick = handleDblClick;
}

function handleDblClick(e) {
    removeLatestPoint();
}

function start() {
    document.getElementById('loading').style.display='none';
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById('map'));
        var center = new GLatLng(42.35430908203125,-71.05899463560769);
        map.setCenter(center);
        map.setZoom(12);
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        GEvent.addListener(map, "click", function(overlay, point) {
            if (overlay) {
                var overlayId = getId(overlay);
                var frag = makeInfoWindow(overlayId);
                overlay.openInfoWindowHtml(frag);
            } else if (point) {
	        var marker = new GMarker(point);
                map.addOverlay(marker);
                addPoint(poi_id, marker);
                generate();
            }
        });
    }
}

function generate() {
    var out = document.getElementById('output');
    if (out_form == output_types['RDF']) {
        out.value = processRDF(points);
    } else if (out_form == output_types['API']) {
        out.value = processAPI(points);
    } else if (out_form == output_types['JS']) {
        out.value = processJS(points);
    } else if (out_form == output_types['EZ']) {
        out.value = processEZ(points);
    }
}

function changeOutput(obj) {
    var idx = obj.selectedIndex;
    out_form = output_types[obj.options[idx].value];
    generate();
}

function processRDF(p) {
    var answer = "";
    answer += "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n";
    answer += "@prefix rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n";
    answer += "@prefix loc:  <http://simile.mit.edu/2005/05/ontologies/location#> .\n";
    for (point in p) {
        if (p[point] != null && point != 'clear') {
            answer += "_:" + point + " rdf:type loc:Point ; \n";
            if (p[point]['label'] != "") {
                answer += "  rdfs:label \"" + p[point]['label'] + "\" ;\n";
            }
            if (p[point]['address'] != "") {
                answer += "  loc:address \"" + p[point]['address'] + "\" ;\n";
            }
            answer += "  loc:coordinates \"" + p[point]['marker'].getPoint().lat() + "," + p[point]['marker'].getPoint().lng()  + "\" . \n\n";
        }
    }
    return answer;
}

function processAPI(p) {
    var answer = "";
    answer += "// call somewhere in your code after making a GMap\n";
    answer += "function draw(map) {\n";
    for (point in p) {
        if (p[point] != null && point !=  'clear') {
            answer += "  var " + point + " = new GLatLng(" + p[point]['marker'].getPoint().lat() + "," + p[point]['marker'].getPoint().lng() + ");\n";
            answer += "  var m_" + point + " = new GMarker(" + point + ");\n";
            if (p[point]['label'] != '') {
                answer += "  GEvent.addListener(m_" + point + ", 'click', function() {\n    m_" + point + ".openInfoWindowHtml('" + p[point]['label'] + "');\n    map.panTo(" + point + ");\n  });\n";
            }
            answer += "  map.addOverlay(m_" + point + ");\n";
        }
    }
    answer += "}\n";
    return answer;
}

function processJS(p) {
    var answer = "// process the array as you see fit\n";
    answer += "var points = new Array();\n";
    for (point in p) {
        if (p[point] != null && point !=  'clear') {
            answer += "points['" + point + "'] = {\n";
            answer += " 'LOC': [" + p[point]['marker'].getPoint().lat() + "," + p[point]['marker'].getPoint().lng() + "]";
            if (p[point]['label'] != '') {
                answer += ",\n 'NAME': '" + p[point]['label'] + "'\n";
            } else {
                answer += "\n";
            }
            if (p[point]['address'] != '') {
                answer += ",\n 'ADDRESS': '" + p[point]['address'] + "'\n";
            } else {
                answer += "\n";
            }
            answer += "};\n";
        }
    }
    return answer;
}

function processEZ(p) {
    var answer = "<!-- see http://bluweb.com/us/chouser/gmapez/docs.html -->\n";
    answer += "<div class=\"GMapEZ\">\n";
    for (point in p) {
        if (p[point] != null && point !=  'clear') {
            answer += " <a href=\"http://maps.google.com/maps?ll=" + p[point]['marker'].getPoint().lat() + "," + p[point]['marker'].getPoint().lng() + "&amp;hl=en\">\n";
            if (p[point]['label'] != '') {
                answer += "  <div>" + p[point]['label'] + "</div>\n";
            }
            answer += " </a>\n";
        }
    }    
    answer += "</div>\n";
    return answer;
}

function addPoint(id, obj) {
    var ident = id + counter++;
    points[ident] = new Array();
    points[ident]['marker'] = obj;
    points[ident]['label'] = "";
    points[ident]['address'] = "";
    return points[ident];
}

function removePoint(obj) {
    map.closeInfoWindow();
    map.removeOverlay(points[obj.parentNode.getAttribute("id")]['marker']);
    points[obj.parentNode.getAttribute("id")] = null;
    generate();
}

function removeLatestPoint() {
    map.removeOverlay(points[poi_id + (counter - 1)]['marker']);
    points[poi_id + (counter - 1)] = null;
    map.removeOverlay(points[poi_id + (counter - 2)]['marker']);
    points[poi_id + (counter - 2)] = null;
    generate();
}

function setLabel(obj) {
    var txt = obj.parentNode.childNodes[1].value;
    points[obj.parentNode.parentNode.getAttribute("id")]['label'] = txt;
    map.closeInfoWindow();
    generate();
}

function setAddress(obj) {
    var txt = obj.parentNode.childNodes[1].value;
    points[obj.parentNode.parentNode.getAttribute("id")]['address'] = txt;
    map.closeInfoWindow();
    generate();
}

function getId(obj) {
    var out;
    for (p in points) {
       if (p != 'clear' && points[p] != null) {
           if (points[p]['marker'].getPoint().lat() == obj.getPoint().lat() && points[p]['marker'].getPoint().lng() == obj.getPoint().lng()) {
               out = p;
           }
       }
    }
    return out;
}

function getLabel(id) {
    return points[id]['label'];
}

function getAddress(id) {
    return points[id]['address'];
}

function makeInfoWindow(id) {
    var label = getLabel(id) ? getLabel(id) : "";
    var address = getAddress(id) ? getAddress(id) : "";
    var html = "<form id='" + id + "'>";
    html += "<p style='margin: 0;'>Label: ";
    html += "<input type='text' size='15' style='display: inline;' value='" + label  + "'/>";
    html += "<input type='button' value='Set Label' style='display: inline;' onclick='setLabel(this)' />";
    html += "</p>";
    html += "<p style='margin: 0;'>Address: ";
    html += "<input type='text' size='15' style='display: inline;' value='" + address + "' />";
    html += "<input type='button' value='Set Address' style='display: inline;' onclick='setAddress(this); return false;' />";
    html += "</p>";
    html += "<input type='button' value='Remove Point' onclick='removePoint(this); return false;'/>";
    html += "</form>";
    return html;
}

function addGeocoderPoint(point) {
    var marker = new GMarker(point);
    map.setCenter(point);
    map.addOverlay(marker);
    var poipoint = addPoint(poi_id, marker);
    poipoint['address'] = document.getElementById('location').value;
    generate();
    document.getElementById('location').value = "location";
}

function addByText() {
    var type = document.getElementById('location-type').value;
    var data = document.getElementById('location').value;
    if (type == 'address') {
        var geocoder = new GClientGeocoder();
        geocoder.getLatLng(data, addGeocoderPoint);
        return;
    }

    // strip out whitespace in coordinates
    //data = data.replace(/ /g, "");
    var coords = data.split(',');
    if (isNaN(parseFloat(coords[0])) || parseFloat(coords[0]) == 0 || isNaN(parseFloat(coords[1])) || parseFloat(coords[1] == 0)) {
        alert('Invalid coordinates');
        return;
    }
    var point = new GLatLng(coords[0], coords[1]);

    // then placement
    var marker = new GMarker(point);
    map.setCenter(point);
    map.addOverlay(marker);
    addPoint(poi_id, marker);
    generate();
    document.getElementById('location').value = "lat,lng";
}

function locationFocus(node) {
    if(node.value=='location' || node.value=='lat,lng') node.value=''
}

function locationBlur(node) {
    var select = document.getElementById('location-type');
    if (select.value == 'address' && node.value == '' ) node.value = 'location';
    if (select.value == 'coordinates' && node.value == '') node.value = 'lat,lng';
}

function locationTypeChange(node) {
    var input = document.getElementById('location');
    if (node.value == 'address') input.value = 'location';
    if (node.value == 'coordinates') input.value = 'lat,lng';
}

