// ==================================================
// DonorToDeed v2.13  �2008 Donor2Deed
// ==================================================

var _numSpiderArms = 0;
var _spiderArmNames = [];
var _spiderDeltaX = [];
var _spiderDeltaY = [];
var _spiderArmIds = [];
var _hackDone = false;

if (GBrowserIsCompatible()) {
    // ==================================================
    // global variables
    // ==================================================
	
    var _baseUrl;
    var _facebookMode;
    var _InDetailMode;
    var _reDisplayProjectMarkers;
  
    var _mapZoom;
    var _mapLat;
    var _mapLng;
    var _mapWidth;
    var _mapHeight;
    var _popOutWidth;
    var _popOutHeight;

    var _ngoId;

    var _map;
    var _mapCenter;
    var _mapType; // set by the PHP

    var _backContent = [];
    var _backFile = [];
    var _backPoint = [];
    var _backTab = [];
    var _backTag = [];

    var _back = false; // used to suppress current update after back button used
    var _defaultMarker; // infoWindow for this marker is shown after fadeIn

    var _asyncWait = false; // set true during asynchronous downloadContent

    function initNgoFacebook(
                            ngoid,
                            baseUrl,
                            width,
                            height,
                            popOutWidth,
                            popOutHeight
                            )
    {
        init(
            baseUrl,
            ngoid,
            true, // facebookMode
            width,
            height,
            popOutWidth,
            popOutHeight
        )
    }

    /*
    * ==================================================
    * initialize home page
    * ==================================================
    */
    function init(baseUrl,ngoid,facebookMode,width,height,popOutWidth,popOutHeight) {
        //Initialise global variables.
        _ngoId = ngoid;
        _baseUrl = baseUrl;
        _InDetailMode = false;
        _reDisplayProjectMarkers = false;
        _facebookMode = facebookMode;
	  
        _mapWidth = width;
        _mapHeight = height;
        _popOutWidth = popOutWidth;
        _popOutHeight = popOutHeight;

        var url = baseUrl + "/map/getngodetails?ngoid=" + ngoid;
        GDownloadUrl(url, function(data, responseCode) {
            if(responseCode == 200 || responseCode === 0)
            {
                try
                {
                    var xml = GXml.parse(data);
                    var ngoinfo = xml.getElementsByTagName("ngoinfo");
                }
                catch (e)
                {
                    alert("Google Maps Request Error (XML Parse)");
                    return;
                }
                mapZoom = ngoinfo[0].getAttribute("zoom");
                mapLat = ngoinfo[0].getAttribute("lat");
                mapLng = ngoinfo[0].getAttribute("lng");
                mapType = ngoinfo[0].getAttribute("maptype");
                
                _mapZoom = parseInt(mapZoom);
                if(isNaN(_mapZoom))
                {
                    _mapZoom = 2;
                }
                _mapLat = parseFloat(mapLat);
                if(isNaN(_mapLat))
                {
                    _mapLat = 25;
                }
                _mapLng = parseFloat(mapLng);
                if(isNaN(_mapLng))
                {
                    _mapLng = -40;
                }

                _mapType = convertStringToMapType(mapType);
            }
            else
            {
                alert("Google Maps Request Error (NGO Details)");
            }
            
            createNewMap();

            _asyncWait = true; // initialize wait for asynchronous function to complete
            projectid = getUrlParameter("projectid");
            windowName = getUrlParameter("windowName");
            if(windowName != "")
            {
                var url = _baseUrl + "/map/getproject?projectid=" + projectid + "&windowName=" + windowName
                GDownloadUrl(url, function(data, responseCode) {
                    if(responseCode == 200 || responseCode === 0)
                    {
                        try
                        {
                            var xml = GXml.parse(data);
                            var marker = xml.getElementsByTagName("marker");
                        }
                        catch (e)
                        {
                            alert("Parse XML Error: " + e.message);
                            return;
                        }
                        // get the javascript function
                        fn = marker[0].getAttribute("function");
                        eval(fn)
                    }
                    else
                    {
                        retContent = url+" Data request error (code="+responseCode+") ";
                        alert("Request Error");
                    }
                });
            }
            else
            {
                displayProjectMarkers();
            }
            _asyncWait = false; // terminate wait
        });
    }

    // ==================================================
    // back button to detail map (Note: point is set) ... called from back button click
    // ==================================================
    function detailMapBack() {
        var e = document.getElementById('globe');
        e.style.display = 'block';
        createNewMap();
    
        displayProjectMarkers();
    
        fadeIn();
    }

    // ==================================================
    // home button
    // ==================================================
    function home() {
        var e = document.getElementById('globe');
        e.style.display = 'block';
        createNewMap();
    
        displayProjectMarkers();

        fadeOut();
    }

    // ==================================================
    // back button
    // ==================================================
    function back() {
        if (_backFile.length > 0){
            var content = _backContent.pop();
            var file = _backFile.pop();
            var point = _backPoint.pop();
            var tab = _backTab.pop();
            var tag = _backTag.pop();
            _back = true;
            if (content == "detailMap"){
                detailMapBack(file); // show previous map in link stack
            }
            else if (content == "showContent"){
                showContent(file,tag);
            }
            else if (content == "showData"){
                showData(file,null,null,null);
            }
        }
        else {
            home();
        }
    }
  

    // ==================================================
    // Display the markers on the initial map
    // ==================================================
    function displayProjectMarkers() {
        var url;
        url = _baseUrl + "/map/get";

        var urlNew = window.location.href;
        var charPos = urlNew.indexOf("?");
        if (charPos > 0) {
            var params = urlNew.substr(charPos);
            url = url + params;
        }
        
        _asyncWait = true; // initialize wait for asynchronous function to complete
    
        GDownloadUrl(url, function(data, responseCode) {
            if(responseCode == 200 || responseCode === 0) { // responseCode is 0 from localhost
        	
                try {
                    var xml = GXml.parse(data);
                } catch (e)
                {
                    alert("Parse XMl Error: " + e.message);
                    return;
                }

                try {
                    var markers = xml.getElementsByTagName("marker");
                } catch (e) {
                    alert("Get Markers Error : " + e.message);
                    return;
                }
        	
                for (var ix = 0; ix < markers.length; ix++) { // remove non-element tab nodes
                    projid = markers[ix].getAttribute("projectid");
                    projlat = markers[ix].getAttribute("lat");
                    projlng = markers[ix].getAttribute("lng");
                    projtitle = markers[ix].getAttribute("title");
                    url = _baseUrl + "/map/getsimpletab?projectid=" + projid;
                    createMarkerAddListener(projid,projlat,projlng,url,false,projtitle,false);
                }

                if(markers.length > 0)
                {
                    if(_hackDone == false)
                    {
                        // this is a hack ... display an info window and immediately close it ... this needs to be
                        // done to update the DOM tree!
                        createMarkerAddListener(projid,1,1,url,true,projtitle,true);
                        GEvent.trigger(_defaultMarker, "click");
                        _map.removeOverlay(_defaultMarker);
                    }
                }

                // Now try to get the spider diagram if one exists
                try {
                    var arm = xml.getElementsByTagName("arm");
                    id = -1;
                    for (i = 0; i < arm.length; i++) { // remove non-element tab nodes
                        dx = parseFloat(arm[i].getAttribute("dx"));
                        dy = parseFloat(arm[i].getAttribute("dy"));
                        name = arm[i].getAttribute("name");
                        lat = parseFloat(arm[i].getAttribute("lat"));
                        lng = parseFloat(arm[i].getAttribute("lng"));
                        url = _baseUrl + "/map/getarmbubble?armid=" + arm[i].getAttribute("id");
                        tmpPoint = new GLatLng(lat,lng);
                        _map.addOverlay(new OffsetableMarker(tmpPoint,dx,dy,name,id,url));
                    }
                    if(arm.length > 0)
                    {
                        if(_hackDone == false)
                        {
                            // this is a hack ... display an info window and immediately close it ... this needs to be
                            // done to update the DOM tree!
                            projid = 1;
                            createMarkerAddListener(projid,1,1,url,true,"projtitle",true);
                            GEvent.trigger(_defaultMarker, "click");
                            _map.removeOverlay(_defaultMarker);
                        }
                    }
                } catch (e) {
                    alert("Spider Diagram load problem");
                    alert(e.message);
                    return;
                }

            } else if(responseCode == -1) {
                retContent = "  Data request timed out ";
                alert("Timeout");
            } else {
                retContent = url+" Data request error (code="+responseCode+") ";
                alert("Not Found ");
            }
            _asyncWait = false; // terminate wait
        });
        GEvent.addListener(_map, "maptypechanged", function() {
            _mapType = _map.getCurrentMapType();
        })

    }

    // ==================================================
    // Create markers and add listeners to the markers
    //
    // if updateDefault is TRUE, then we also update the
    // defaultMarker
    // ==================================================
    function createMarkerAddListener(projId, lat, lng, url, updateDefault, projtitle, hack) {

        // create the marker
        var point = new GLatLng(lat,lng);
        if(projtitle != "none")
        {
            options = {title: projtitle};
        }
        else
        {
            options = {title: "Project " + projId + " Lat: " + lat + " Lng: " + lng};
        }
        var projMarker = new GMarker(point, options);

        // add listener
        GEvent.addListener(projMarker, "click", function() {
            displayBubble(projMarker, url, projId, hack);
            if((updateDefault == true) && (hack == false))
            {
                var e = document.getElementById('globe');
                e.style.display = 'none';
            }
        });

        if(updateDefault == true)
        {
            _defaultMarker = projMarker;
        }
    
        _map.addOverlay(projMarker);
    }

    // ==================================================
    // Open Project Detail Window
    //
    // Opens a new window with the project detail bubble displayed OR
    // if in facebook then it stays in the original map and displays the
    // project detail bubble.
    //
    // This function is called directly on click event in the page
    // ==================================================
    function openDetailProjectMap(projectId, Lat, Lng, Zoom, mapType)
    {
        pageTracker._trackPageview("/mapDetail?projid=" + projectId);

        var width = _popOutWidth;
        var height = _popOutHeight;
        var contentUrl = _baseUrl + "/map/getdetailtab?projectid=" + projectId;
	  
        _InDetailMode = true;

        _map = new GMap2(document.getElementById("detailBox"),
        {
            mapTypes:[],
            size: new GSize(width,height)
        });

        _map.setMapType(convertStringToMapType(mapType));

        _mapCenter = new GLatLng(Lat, Lng);
        _map.setCenter(_mapCenter, parseInt(Zoom));
        _map.addControl(new GMapTypeControl());
        _map.disableDoubleClickZoom();
        //_map.disableDragging();

        createMarkerAddListener(projectId, Lat, Lng, contentUrl, true, "none", false);
        GEvent.trigger(_defaultMarker, "click"); // trigger a click on default marker to open InfoWindow

        fadeIn();
    }

    // ==================================================
    // Generic function to display the contents of a bubble
    //
    // If checkForFacebook is TRUE, then we need to check
    // if we're being called from a Facebook App as the
    // maps are displayed differently
    // ==================================================
    function displayBubble(projMarker, url, projId, hack)
    {
        // google analytics
        pageTracker._trackPageview("/maps?projid=" + projId);
        
        _asyncWait = true; // initialize wait for asynchronous function to complete

        GDownloadUrl(url, function(data, responseCode)
        {
            if(responseCode == 200 || responseCode === 0) // responseCode is 0 from localhost
            {
                options = {
                    noCloseOnClick: true,
                    onCloseFn: function(){
                        _map.panTo(_mapCenter)
                    }
                };
                _map.openInfoWindowHtml(projMarker.getLatLng(), data, {
                    noCloseOnClick: true,
                    onCloseFn: function(){
                        _map.panTo(_mapCenter)
                    }
                });
                _map.getInfoWindow().show();
                if(hack == true)
                {
                    GEvent.trigger(_map.getInfoWindow(), "closeclick");
                    if(_hackDone == false)
                    {
                        _hackDone = true;
                        init(_baseUrl,_ngoId,_facebookMode,_mapWidth,_mapHeight,_popOutWidth,_popOutHeight);
                    }
                }
            }
            else if(responseCode == -1)
            {
                alert("Timeout");
            }
            else
            {
                alert("Not Found ");
            }
            // If there's a Tab to load, then call loadTabs
            tabberAutomaticOnLoad();

            _asyncWait = false; // terminate wait
        });
    }

    // ==================================================
    // Open Donate Bubble
    //
    // Opens a new window right donation info
    // ==================================================
    function openDonateBubble(projectId, Lat, Lng, Zoom, mapType, projectOrNgo)
    {
        pageTracker._trackPageview("/donate?projid=" + projectId);

        var width = _popOutWidth;
        var height = _popOutHeight;
        var contentUrl = "";
        if(projectOrNgo == true)
        {
            contentUrl = _baseUrl + "/map/getdonateprojecttab?projectid=" + projectId;
        }
        else
        {
            contentUrl = _baseUrl + "/map/getdonatengotab?projectid=" + projectId;
        }
        

        _InDetailMode = true;

        _map = new GMap2(document.getElementById("detailBox"),
        {
            mapTypes:[],
            size: new GSize(width,height)
        });

        _map.setMapType(convertStringToMapType(mapType));

        _mapCenter = new GLatLng(Lat, Lng);
        _map.setCenter(_mapCenter, parseInt(Zoom));
        _map.addControl(new GMapTypeControl());
        _map.disableDoubleClickZoom();
        //_map.disableDragging();

        createMarkerAddListener(projectId, Lat, Lng, contentUrl, true, "none", false);

        GEvent.trigger(_defaultMarker, "click"); // trigger a click on default marker to open InfoWindow

        fadeIn();
    }

    function createNewMap()
    {
        _map = new GMap2(document.getElementById("homeBox"),
        {
            mapTypes:[G_NORMAL_MAP,G_PHYSICAL_MAP,G_SATELLITE_MAP,G_SATELLITE_3D_MAP]
            //mapTypes:[G_NORMAL_MAP,G_PHYSICAL_MAP,G_SATELLITE_MAP]
        });

        _map.setMapType(_mapType);

        _mapCenter = new GLatLng(_mapLat,_mapLng)
        _map.setCenter(_mapCenter, _mapZoom);

        //_map.addControl(new GLargeMapControl());
        _map.addControl(new GLargeMapControl3D());
        _map.addControl(new GMapTypeControl());
        _map.disableDoubleClickZoom();

    }

    function reDisplayProjectMarkers() {

        if (_reDisplayProjectMarkers == true) {
		  
            _InDetailMode = false;
            _reDisplayProjectMarkers = true;
		  
            _map.setMapType(_mapType);
		      
            _mapCenter = new GLatLng( 25,-40)
            _map.setCenter(_mapCenter, 2);
            _map.disableDoubleClickZoom();

            displayProjectMarkers();
        }
    }

  
    function updateLineTotal(index)
    {
        var donateTotal = 0;
        var donateLineVal = 0;
        var numOfLines = 0;
        var strFieldName = "";
	  	  	  
        try {
            numOfLines = document.getElementById("numberoflines").value;
        } catch (e) {
            alert("Error getting line values: " + e.message);
        }

        if (numOfLines == 0) {
            return false;
        }

        donateTotal = 0;
        for (i=0; i<numOfLines; i++) {
            strFieldName = "donatelinevalue" + i;
            donateLineVal = parseFloat(document.getElementById(strFieldName).value);
    
            if (donateLineVal >= 0) {
                donateLineVal = Math.round(100*donateLineVal)/100;
                donateTotal = donateTotal + donateLineVal;
            }
        }
        donateTotal = Math.round(donateTotal*100)/100;
        document.getElementById("donatevalue").value =  donateTotal;
    }
    
    function updateUnitLineTotal(index)
    {
        var donateTotal = 0;
        var donateLineVal = 0;
        var donatePricePerLineVal = 0;
        var donateSubTotal = 0;
        var numOfLines = 0;
        var strFieldName = "";
  
        //numOfLines = document.getElementById("numberoflines").value;
        numOfLines = get_object("numberoflines").value;
	  
        donateTotal = 0;
	  
        for (i=0; i<numOfLines; i++) {
		  
            strFieldName = "donatelinevalue" + i;
            //donateLineVal = parseFloat(document.getElementById(strFieldName).value);
            donateLineVal = parseFloat(get_object(strFieldName).value);

            strFieldName = "priceperline" + i;
            //donatePricePerLineVal = parseFloat(document.getElementById(strFieldName).value);
            donatePricePerLineVal = parseFloat(get_object(strFieldName).value);
            //alert(strFieldName + "  " + donateLineVal + " by " + donatePricePerLineVal);
			  
            if (donateLineVal >= 0) {
                if (donatePricePerLineVal >= 0) {
                    donateLineVal = Math.round(donateLineVal*100)/100;
                    donateSubTotal = donateLineVal * donatePricePerLineVal;
                    donateSubTotal = Math.round(donateSubTotal*100)/100;
                    donateSubTotal.toFixed(2);
                    
                    strFieldName = "donatelinesubtotal" + i;
                    document.getElementById(strFieldName).value = donateSubTotal.toFixed(2);
                    get_object(strFieldName).value = donateSubTotal.toFixed(2);
				  
                    donateTotal = donateTotal + donateSubTotal;
                }
            }
        }
        
        donateTotal = Math.round(donateTotal*100)/100;
        //donateTotal.toFixed(2);
        document.getElementById("donatevalue").value =  donateTotal.toFixed(2);
        get_object("donatevalue").value =  donateTotal.toFixed(2);
    }
    
    function submitAjaxRequest(requestURL, reqParameters) {
        new Ajax.Request(requestURL,{
            method:'post',
            parameters: reqParameters,
            onSuccess: function(oRequest, oJSN)
            {
                try {
                    var resp = eval('(' + oRequest.responseText + ')');
                } catch (e) {
                    alert(e.message)
                }
                if (resp.status == "success") {
                    //Redirect to the donate page
                    self.parent.location = resp.url;
                } else {
                    //Display the error message
                    if (resp.message != ""){
                        document.getElementById("tabErrorDiv").innerHTML = resp.message;
                    } else {
                        document.getElementById("tabErrorDiv").innerHTML = "An error occured processing the form. Please check the entered values.";
                    }
                    document.getElementById("proceed_button").disabled = false;
                }
            },
            onFailure: function()
            {
                alert('Error processing donate request...')
            }
        });
    }
    
    function submitDonateNgoForm() {
        var contentUrl = _baseUrl + "/map/processdonatengo";
	  
        try {
            var poststr = "donatevalue=" + document.getElementById("donatevalue").value;
            poststr = poststr + "&ngoid=" + document.getElementById("ngoid").value;
            poststr = poststr + "&projectid=" + document.getElementById("projectid").value;
            poststr = poststr + "&infacebookmode=" + _facebookMode;
        } catch (e)
        {
            alert("Error submitting form values: " + e.message);
            return;
        }
	  
        submitAjaxRequest(contentUrl, poststr);
    }
  
    function submitDonateProjectForm() {
        var contentUrl = _baseUrl + "/map/processdonateproject";
	  
        try {
            var poststr = "donatevalue=" + document.getElementById("donatevalue").value;
            poststr = poststr + "&projectid=" + document.getElementById("projectid").value;
            poststr = poststr + "&infacebookmode=" + _facebookMode;
		  	
        } catch (e)
        {
            alert("Error submitting form values: " + e.message);
            return;
        }

        submitAjaxRequest(contentUrl, poststr);
    }

    function submitDonateProjectLineQtyForm() {
        var contentUrl = _baseUrl + "/map/processdonateprojectlineqty";

        var donateLineVal = 0;
        var numOfLines = 0;
        var strFieldName = "";
	  
        try {
            var poststr = "donatevalue=" + document.getElementById("donatevalue").value;

            numOfLines = document.getElementById("numberoflines").value;
			  
            for (i=0; i<numOfLines; i++) {
                strFieldName = "donatelinevalue" + i;
                donateLineVal = document.getElementById(strFieldName).value;
				
                poststr = poststr + "&donatelinevalue" + i + "=" + donateLineVal;
            }

            poststr = poststr + "&projectid=" + document.getElementById("projectid").value;
            poststr = poststr + "&infacebookmode=" + _facebookMode;

        } catch (e)
        {
            alert("Error submitting form values: " + e.message);
            return;
        }
	  
        submitAjaxRequest(contentUrl, poststr);
    }
 
    function get_object(id)
    {
        var object = null;
        if( document.layers ) {
            object = document.layers[id];
        } else if( document.all ) {
            object = document.all[id];
        } else if( document.getElementById ) {
            object = document.getElementById(id);
        }
        return object;
    }

    function getUrlParameter( name )
    {
        name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]"+name+"=([^&#]*)";
        var regex = new RegExp( regexS );
        var results = regex.exec( window.location.href );
        if( results == null )
            return "";
        else
            return results[1];
    }

    function convertStringToMapType(mapType)
    {
        // mapType may be one of the following
        //      - G_PHYSICAL_MAP
        //      - G_HYBRID_MAP
        //      - G_SATELLITE_MAP
        //      - G_SATELLITE_3D_MAP
        switch(mapType)
        {
            case "G_HYBRID_MAP":
                m = G_HYBRID_MAP;
                break;
            case "G_SATELLITE_MAP":
                m = G_SATELLITE_MAP;
                break;
            case "G_SATELLITE_3D_MAP":
                m = G_SATELLITE_3D_MAP;
                break;
            case "G_NORMAL_MAP":
                m = G_NORMAL_MAP;
                break;
            default: //case "G_PHYSICAL_MAP":
                m = G_PHYSICAL_MAP;
                break;
        }
        return m;
    }

function urlencode (str) {
    var hexStr = function (dec) {
        return '%' + dec.toString(16).toUpperCase();
    };

    var ret = '',
            unreserved = /[\w.-]/; // A-Za-z0-9_.- // Tilde is not here for historical reasons; to preserve it, use rawurlencode instead
    str = (str+'').toString();

    for (var i = 0, dl = str.length; i < dl; i++) {
        var ch = str.charAt(i);
        if (unreserved.test(ch)) {
            ret += ch;
        }
        else {
            var code = str.charCodeAt(i);
            // Reserved assumed to be in UTF-8, as in PHP
            if (code === 32) {
                ret += '+'; // %20 in rawurlencode
            }
            else if (code < 128) { // 1 byte
                ret += hexStr(code);
            }
            else if (code >= 128 && code < 2048) { // 2 bytes
                ret += hexStr((code >> 6) | 0xC0);
                ret += hexStr((code & 0x3F) | 0x80);
            }
            else if (code >= 2048 && code < 65536) { // 3 bytes
                ret += hexStr((code >> 12) | 0xE0);
                ret += hexStr(((code >> 6) & 0x3F) | 0x80);
                ret += hexStr((code & 0x3F) | 0x80);
            }
            else if (code >= 65536) { // 4 bytes
                ret += hexStr((code >> 18) | 0xF0);
                ret += hexStr(((code >> 12) & 0x3F) | 0x80);
                ret += hexStr(((code >> 6) & 0x3F) | 0x80);
                ret += hexStr((code & 0x3F) | 0x80);
            }
        }
    }
    return ret;
}

// ==================================================
// end of main "if"
// ==================================================
}
else {
    alert("Sorry ... Google Maps is not compatible with your browser!");
}


function donate() {
  // window.open("donate.htm", "","toolbar=no,location=no,directories=no,menubar=no,scrollbars=no,resizable=yes,status=no,top=0,left=0")

  openWindow("donate1.htm", "Donate", 600, 320);
}

function openWindow(windowUri, windowTitle, windowWidth, windowHeight) {
    var centerWidth = (window.screen.width - windowWidth) / 2;
    var centerHeight = (window.screen.height - windowHeight) / 2;

    newWindow = window.open(windowUri, windowTitle, 'resizable=0,width=' + windowWidth +
        ',height=' + windowHeight +
        ',left=' + centerWidth +
        ',top=' + centerHeight);

    newWindow.focus();
    return newWindow.name;
}

