// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
var centerLatitude = 34;
var centerLongitude = 20;
var startZoom = 2;

var map;



function init() {

    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));

        document.getElementById("map").style.backgroundColor="#99B3CC";
        map.addMapType(G_PHYSICAL_MAP);

        //map.setMapType(G_PHYSICAL_MAP);

        var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(40,40));
        map.addControl(new GSmallMapControl(), topRight);
        //map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);


        map.removeMapType(G_HYBRID_MAP);
        map.removeMapType(G_SATELLITE_MAP);
        map.addMapType(G_PHYSICAL_MAP);
        map.addMapType(G_SATELLITE_3D_MAP);
        var mapControl = new GMapTypeControl();
        map.addControl(mapControl);
        map.setMapType(G_NORMAL_MAP);
        listMarkers("all_issues");
    // map.disableDragging();

    
    }
}



function createMarker(){
    var lng = document.getElementById("longitude").value;
    var lat = document.getElementById("latitude").value;


    var getVars = "?m[issue]=" + document.getElementById("issue").value
    + "&m[title]=" + document.getElementById("title").value
    + "&m[summary]=" + document.getElementById("summary").value
    + "&m[country]=" + document.getElementById("country").value
    + "&m[infolink]=" + document.getElementById("infolink").value
    + "&m[image]=" + document.getElementById("image").value
    + "&m[video]=" + document.getElementById("video").value
    + "&m[icon]=" + document.getElementById("icon").value
    + "&m[lng]=" + lng
    + "&m[lat]=" + lat;

    var request = GXmlHttp.create();

    //call the create action back on the server
    request.open('GET', 'create' + getVars, true);
    request.onreadystatechange = function() {
        if (request.readyState == 4){
            //the request is complete

            var success=false;
            var content='Error contacting web service';
            try{
                //parse the result to JSON (simply by eval-ing it)
                res=eval( "(" + request.responseText + ")" );
                content=res.content;
                success=res.success;
            }catch (e){
                sucess=false;
            }

            //check to see if it was an error or success
            if (!success){
                alert(content);
            }else{
                //create a new marker and add its info window
                var latlng = new GLatLng(parseFloat(lat),parseFloat(lng));
                var marker = addMarkerToMap(latlng, content, res.icon);
                map.addOverlay(marker);
                map.closeInfoWindow();
            }
        }
    }
    request.send(null);

    return false;
}

function addMarkerToMap(latlng, html, iconImage, loadIssueBox, loadButtons, issueid){
    if(iconImage!='') {
        var icon = new GIcon();
        icon.image = "/images/" + iconImage;
        icon.iconSize = new GSize(16,28);
        icon.iconAnchor = new GPoint(14,25);
        icon.infoWindowAnchor = new GPoint(14,14);
        var marker = new GMarker(latlng,icon);
    }else{
        var marker = new GMarker(latlng);
    }

    GEvent.addListener(marker, 'click', function(){
        var markerHTML = html;
        var markerLoadIssueBox = loadIssueBox;

        document.getElementById('issuebox').innerHTML = markerLoadIssueBox;
        document.getElementById('buttonspanel').innerHTML = loadButtons;
        pageTracker._trackPageview('/clicked-marker/' + issueid + '/');
        //firebug.d.console.cmd.log("clickedyclick");
        //console.log('/' + country_ga + '/' + mediaval_ga + '/'); //for firebug
        externalLinks();
    });


    return marker;
}

function ClearMarkers() {
    map.clearOverlays();

}

function TrackDonationClicks(issueid) {
    pageTracker._trackPageview('/clicked-donate-button/' + issueid + '/');
    console.log('/clicked-donate-button/' + issueid + '/');
}

function TrackLearnMoreClicks(issueid) {
    pageTracker._trackPageview('/clicked-learnmore-button/' + issueid + '/');
    console.log('/clicked-learnmore-button/' + issueid + '/');
}

function listMarkers(issuetag){

    ClearMarkers();
    pageTracker._trackPageview(issuetag);

    var request = GXmlHttp.create();
    sourceElement = document.getElementById("select3");
    //tell the request where to retrieve data from

    var issuetagpath = '/map/' + issuetag;
    //    var issuetagpath = '/feedme/convert_to_json';

    request.open('GET', issuetagpath , true);


    //tell the request what to do when the state changes.
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            //parse the result to JSON, by eval-ing it.
            //The response is an array of markers
            markers=eval("(" + request.responseText + ")" );
            for (var i = 0; i < markers.length ; i++) {

                var marker=markers[i]
                var lat=marker.lat;
                var lng=marker.lng;


                //check for lat and lng so MSIE does not error
                //on parseFloat of a null value
                if (lat && lng) {
                    var latlng = new GLatLng(parseFloat(lat),parseFloat(lng));

                    if(marker.video!="") {
                        mediaval_ga = marker.video
                        mediaval = '<div id="media"><p><object width="178" height="150"><param name="movie" value="http://www.youtube.com/v/'+marker.video+'&hl=en"></param><embed src="http://www.youtube.com/v/'+marker.video+'&hl=en" type="application/x-shockwave-flash" width="178" height="150"></embed></object></p></div>'
                    }else {
                        mediaval_ga = marker.image
                        mediaval = '<div id="media"><p><img src="/images/' + marker.image + '" style="border-style: solid; border-width: 1px; border-color: #375b4d;" alt="' + marker.imgalt + '" width="178" height="130"></p></div>';
                    }


                    var html = '<div class="boundingbox">'
                    + '<span class="issue">' + marker.category + '</span> '
                    + '<span class="country">(' + marker.country + ')</span>'
                    + '</div><div class="summarybox">'
                    + '<span class="title">' + marker.summary + '</span> '
                    + '<span class="title">' + marker.moreurl + '</span> '
                    + '</div>';

                    issueid = marker.id
                    var loadIssueBox =  mediaval + '<div id="summary"><p>' + marker.summary + '</p></div><div id="maintext"><p>' + marker.maintext + '</div></p>';
                    var loadButtons = '<a href="https://donations.wspa-international.org/form.asp?id=281" target="_blank" onclick="TrackDonationClicks(' + marker.id +')""><img width="83" height="16" border="0" style="padding-right: 10px;" src="/images/but_donate.gif" id="donatebutton"/><a href="' + marker.moreurl + '" target="_blank" onclick="TrackLearnMoreClicks(' + marker.id +')"><img id="learnbutton" border="0" src="/images/but_learnmore.gif" width="83" height="16"></div>';


                    var iconImage = marker.icon;
                    var marker = addMarkerToMap(latlng, html, iconImage, loadIssueBox, loadButtons, issueid);
                    map.addOverlay(marker);
                }//end of if lat and lng
            }//end of for loop
        }//if
    }//function

    request.send(null);
}


// Decided to make all links auto target=_blank
// can use if (anchor.getAttribute("href") && anchor.getAttribute("class") == "external") if want to do it by class (need to add (external) to front of textile link though
function externalLinks() {
    if (!document.getElementsByTagName) return;
    var anchors = document.getElementsByTagName("a");
    for (var i=0; i<anchors.length; i++) {
        var anchor = anchors[i];
        if (anchor.getAttribute("href") && anchor.getAttribute("class") == "external")
            anchor.target = "_blank";
    }
}

window.onload = init;
window.onunload = GUnload;