var markerOptions = new Object();
markerOptions.icon = new GIcon();
markerOptions.icon.image = "images/marker.png";
markerOptions.icon.iconSize = new GSize(20, 20);
markerOptions.icon.iconAnchor = new GPoint(10, 10);
markerOptions.icon.infoWindowAnchor = new GPoint(10, 10);
markerOptions.icon.infoShadowAnchor = new GPoint(11, 11);

var zoomMarkerOptions = new Object();
zoomMarkerOptions.icon = new GIcon();
zoomMarkerOptions.icon.iconSize = new GSize(30, 30);
zoomMarkerOptions.icon.iconAnchor = new GPoint(15, 15);
zoomMarkerOptions.icon.infoWindowAnchor = new GPoint(15, 15);
zoomMarkerOptions.icon.infoShadowAnchor = new GPoint(16, 16);
zoomMarkerOptions.title = "Default title, edit below";

var dragStartPoint = new GLatLng();
var popupWindow = "";

var filter = "";

var DEFAULT_CLICK_ZOOM = 11;
var textSearch = "";
var openingInfoWindow = false;

function mytrim(str){
    if(!str)
        return "";
    return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

//var ZOOM_ACCURACY = [ 4, 5, 9, 13, 15, 16, 16, 17 ];
// TODO: test out what values we like
var ZOOM_ACCURACY =   [ 4, 5, 7, 10, 13, 14, 15, 15, 15, 15 ];
function show_address(map, address, state, country, table) {

    var geocoder = new GClientGeocoder();
    var locStr = "";
    if (address && address.length > 0 && address != "Enter your location here")
        locStr = address;
    
    if (state && state.length > 0 && state != "Select State, Province, County, Territory") { 
        if (locStr.length > 0)
            locStr += ", ";
        locStr += state; 
    }
    if (country && country.length > 0 && country != "Select Country") { 
        if (locStr.length > 0)
            locStr += ", ";
        locStr += country; 
    }

    filter = document.getElementById("filter").value;
    
    if(locStr){
        geocoder.getLocations(locStr, 
                 function(result){
                     if (result.Status.code == G_GEO_SUCCESS) {
                             var lat = result.Placemark[0].Point.coordinates[1];
                             var lng = result.Placemark[0].Point.coordinates[0];
                             
                             var point;
                             var zoom;
                             
                             if(!(point = getSpecialCaseCenter(locStr)))
                                 point = new GLatLng(lat,lng);
                             if(!(zoom = getSpecialCaseZoom(locStr)))
                                 zoom = ZOOM_ACCURACY[result.Placemark[0].AddressDetails.Accuracy];
                             
                             map.setCenter(point, zoom);
                         if(result.Placemark.length != 1){
                             var pickerText = "Multiple results were found, please pick one:<br/>";
                             for(i=0; i<result.Placemark.length; i++){
                                 pickerText += "<a href='?address="+
                                     encodeURIComponent(result.Placemark[i].address)+"'>"+
                                     result.Placemark[i].address+"</a><br/>";
                             }
                             qc.showStatusMsg(pickerText);
                         }
                         
                         
                     } else {
                         alert(locStr + " not found");
                     }
                 });
    }
    else if(filter){
        move_it(map, table);
    }
}

function createElem(opt_className, opt_html, opt_tagName) {
    var tag = opt_tagName||"div";
    var elem = document.createElement(tag);
    if (opt_html) elem.innerHTML = opt_html;
    if (opt_className) elem.className = opt_className;
    return elem;
}


function addToSideBar(marker, title, expanded){
    var label = createElem("sidebar-entry-title", title + (expanded ? '<span class=\'asterisk\'>*</span>' : ''), "a");
    label.href = "#";
    label.onclick = function(){GEvent.trigger(marker,'click'); return false};//x-browser
    my_results.appendChild(label);
    GEvent.addListener(marker,'click',function(){label.focus(); return false});

}
function clearSideBar(){
    while (my_results.firstChild) {
        my_results.removeChild(my_results.firstChild);
    }
}


function createMarker(map, lat, lng, html, title, table) {
    markerOptions.title = title;
    if(document.getElementById("admininfo")){
        markerOptions.draggable = true;
    }
    var marker = new GMarker(new GLatLng(lat, lng), markerOptions);
    GEvent.addListener(marker, "click", function() {
        openingInfoWindow = true;
        var options = new Object();
        options.maxWidth = "450";
        marker.openInfoWindowHtml(html, options);
    });
    map.addOverlay(marker);

    if(document.getElementById("admininfo")){
        GEvent.addListener(marker, "dragstart",
                           function(){ 
                               dragStartPoint = marker.getLatLng();
                               if(popupWindow)
                                   popupWindow.close();
                           });
        
        GEvent.addListener(marker, "dragend",  function(){
            // if same point, exit out
            if(dragStartPoint.equals(marker.getLatLng()))
                return;
            
            popupWindow = window.open("markeredit.php?op=edit&map="+table+"&"+
                                      "lat="+dragStartPoint.lat()+"&lng="+dragStartPoint.lng()+"&"+
                                      "newlat="+marker.getLatLng().lat()+"&newlng="+marker.getLatLng().lng(),
                                      'markeredit','height=300,width=600');
        });
    }

    return marker;
}

function createZoomMarker(map, numResults, table) {
    var msg = "";

    if(numResults){
        zoomMarkerOptions.title = "Click on the + to zoom in";
        zoomMarkerOptions.icon.image = "images/zoom.png";
        zoomMarker = new GMarker(map.getCenter(), zoomMarkerOptions);
        GEvent.addListener(zoomMarker, "click", function() { map.zoomIn(); });
        
        msg = "Please zoom in, or choose some search criteria;"+
            "<br />there are too many results ";
        if(map.getZoom() > 5)
            msg += "(" + numResults + ") ";
        msg += "to display";
    }
    else{
        zoomMarkerOptions.title = "Click on the - to zoom out";
        zoomMarkerOptions.icon.image = "images/zoomout.png";
        zoomMarker = new GMarker(map.getCenter(), zoomMarkerOptions);
        GEvent.addListener(zoomMarker, "click", function(){ map.zoomOut(); });
        
        msg = "No results found.<br/>Please zoom out or change your search criteria.<br/>";
        if(table == "seekfind"){
            msg += "<a href='http://www.sdiworld.org/become_a_member.html'>Add your own listing</a>";
        }
        else if(table == "regevents"){
            msg += "<br/>If you are a current member and would like to add a retreat or event, please fill out <a href='http://www.sdiworld.org/levynal4gfu7gnjw1rtwiq'>this form</a>.";
        }
        else if(table == "programs"){
            msg += "<br/>If you are a current member and would like to add a program, please fill out <a href='http://www.sdiworld.org/enrichment_formation_and_training_programs.html'>this form</a>.";
        }
        else if(table == "retreats"){
            msg += "<br/>If you are a current member and would like to add a retreat center, please fill out <a href='http://sdiworld.org/retreat_centers.html'>this form</a>.";
        }
    }

    qc.showStatusMsg(msg);

    map.addOverlay(zoomMarker);
}

function showTextResult(marker, title, info, expanded){
    addToSideBar(marker, title, info, expanded);
}


function after_move(dyn_js, http_status) {
    if(http_status == 200){
        eval(dyn_js);
    }
    else{
        // if http_status == 0, probably the person is exiting the page
        if(http_status){
            alert("Error: bad response from server (" + http_status + ")");
        }
    }
}

function move_it(map, table) {
    filter = document.getElementById("filter").value;
    if(openingInfoWindow == false){
        map.clearOverlays();
        var bounds = map.getBounds();
        var params = 
            'lon1=' + bounds.getSouthWest().lng() + 
            '&lat1=' + bounds.getSouthWest().lat() +
            '&lon2=' + bounds.getNorthEast().lng() +
            '&lat2=' + bounds.getNorthEast().lat() +
            '&zoom=' + map.getZoom() +
            '&t=' + table +
            '&filter=' + filter;
        new GDownloadUrl("js_gen.php?" + params, after_move);
    }
    openingInfoWindow = false;
}

function selectZoomCenter(zoom){
    if(zoom){
        document.getElementById('zoom').disabled = false; 
        document.getElementById('lat').disabled = true;
        document.getElementById('lng').disabled = true;
    }
    else{
        document.getElementById('zoom').disabled = true; 
        document.getElementById('lat').disabled = false;
        document.getElementById('lng').disabled = false;
    }
}

function admin_click(map, table, click_latlng, marker_latlng) {
    if(!click_latlng && !marker_latlng)
        return;
    if(!click_latlng)
        click_latlng = "";
    if(!marker_latlng)
        marker_latlng = "";

    var admininfo = document.getElementById("admininfo");
    if(admininfo){
        formdata = "Use full names (e.g. Pennsylvania, not PA; capitalization is not important)";
        formdata += "<form method='POST' action='admin.php'>" + 
            "City: <input type='text' name='city' /><br/>" + 
            "State: <input type='text' name='state' /><br/>" + 
            "Country: <input type='text' name='country' /><br/>";

        formdata += "<input type='radio' name='zoomcenter' value='1' checked='checked' onclick='selectZoomCenter(true);' /> ";

        formdata += "Zoom: <input type='text' id='zoom' name='zoom' value='" + map.getZoom() + "' /><br/>";

        formdata += "<input type='radio' name='zoomcenter' value='0' onclick='selectZoomCenter(false);' />";
        if(click_latlng){
            formdata += "Click: <input type='text' id='lat' name='lat' size='7' value='" + 
                click_latlng.lat() + "' />" + 
                " <input type='text' id='lng' name='lng' size='7' value='" + click_latlng.lng() + "' /><br/>";
        }
        else if(marker_latlng){
            formdata += "Marker: <input type='text' id='lat' name='lat' size='7' value='" + 
                marker_latlng.lat() + "' />" + 
                " <input type='text' id='lng' name='lng' size='7' value='" + marker_latlng.lng() + "' /><br/>";
        }
        formdata += "<input type='hidden' name='map' value='"+table+"' />" +
            "Check the above values and then: <input type='submit' value='Update' /1>" + 
            "</form>";

        admininfo.innerHTML = formdata;
        selectZoomCenter(true);
    }
}


function do_search(map, table){
    qc.showStatusMsg('');
    map.clearOverlays();
    show_address(map,
                 document.getElementById("address").value,
                 getBoxSelectedText(document.getElementById("state")),
                 getBoxSelectedText(document.getElementById("country")),
                 table);
}


function dump(arr,level) {
    var dumped_text = "";
    if(!level) level = 0;
    
    if(level == 5)
        return "too much depth...";

    //The padding given at the beginning of the line.
    var level_padding = "";
    for(var j=0;j<level+1;j++) level_padding += "    ";
    
    if(typeof(arr) == 'object') { //Array/Hashes/Objects 
        for(var item in arr) {
            var value = arr[item];
            
            if(typeof(value) == 'object') { //If it is an array,
                dumped_text += level_padding + "'" + item + "' ...\n";
                dumped_text += dump(value,level+1);
            } else {
                dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
            }
        }
    } else { //Stings/Chars/Numbers etc.
        dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
    }
    return dumped_text;
}

