// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

var map, manager, marker_list, draggable_array;



//Utility
function removeChildren(node){
    //			if (node.childNodes && node.childNodes.length > 0) {
    //				while (node.childNodes.length >= 1) {
    //					    if (node.firstChild.hasChildNodes()) {
    //						   a = node.firstChild.getElementsByTagName('a');
    //						   a.onclick=null;
    //						   removeChildren(node.firstChild);
    //						}
    //						   node.removeChild( node.firstChild) ;
    //	                       if (node.firstChild.outerHTML) {
    //								node.firstChild.outerHTML = "";
    //						   }
    //						   node.firstChild=null;	
    //				}
    //			}
    
    
    if (node) {
    
        for (var x = node.childNodes.length - 1; x >= 0; x--) {
            var childNode = node.childNodes[x];
            
            if (childNode.hasChildNodes()) {
                a_links = childNode.getElementsByTagName('a');
                for (a = 0; a < a_links.length; a++) {
                    //console.log(a_links[a].onclick);
                    a_links[a].onclick = null;
                }
                removeChildren(childNode);
            }
            
            //console.log("removing a node: " + childNode.nodeName);
            // console.dir(childNode);
            node.removeChild(childNode);
            
            if (childNode.outerHTML) {
                childNode.outerHTML = '';
            }
            
            childNode = null;
        }
        node = null;
    }
}





function update_map(request){
    //alert(manager.getMarkerCount(11));
    //delete window.center;
    //delete window.zoom;
    //grab the current center
    window.center = map.getCenter();
    //alert(window.center);
    window.zoom = map.getZoom();
    //alert(window.center);
    //kill the current map to free all of the old markers and memory
    
    //console.log(marker_list.length);
    //iterate through the draggable array and destroy them, so as not to cause a mem leak
    //console.log("array length: " + draggable_array.length );
    for (i = 0; i < draggable_array.length; i++) {
        draggable_array[i].destroy();
        draggable_array[i] = null;
    }
    //console.log("array length: " + draggable_array.length );
    
    //the marker_list array we maintain to keep track of specific markers
    for (i = 0; i < marker_list.length; i++) {
        //console.dir(manager);
        //console.log("trying to remove marker for " + marker_list[i].labelText);
        //the manager manages the diplay at various zoom levels...  need to remove from here		
        window.manager.removeMarker(marker_list[i]);
        //check now
        // window.manager.refresh();
        
        //console.log("removed markers... currrent count: " + window.manager.getMarkerCount(8));
        //we need to call 'remove()' on each marker to free up the marker's memory
        //marker_list[i].remove();
        //then we set the marker's reference to null
        marker_list[i] = null;
    }
    
    marker_list = null;
    
    GUnload();
    //delete map;
    //delete manager;
    //delete window.markers;
    //alert(manager.getMarkerCount(11));
    window.markers = request.responseJSON;
    
    //the first element returned is always the center point
    //window.center = window.markers.pop()
    
    //this call will reset the map.  
    //just clearing the markers has led to memory leaks
    //resorted to unloading and reloading through set_up_map
    set_up_map();
    //alert(window.markers.length + " 1");
    
    
    window.markers.sort(function(a, b){
        return (a.kw > b.kw) ? +1 : -1;
    });
    //	alert(window.markers[0].name);
    //alert(window.markers.length+ " 2");
    
    //clear out the side bar list by deleting the child nodes in side-bar
    removeChildren(document.getElementById('sidebar-list'));
    //alert(window.markers.length+ " 3");
    
    //local variable to temporarily hold references to created markers
    batch = [];
    for (var i = 0; i < window.markers.length; i++) {
        //alert("calling createMarker: " + window.markers[i]);
        //create a new marker
        m = createMarker(window.markers[i])
        //alert(window.markers[i]);
        
        //add it to the array we'll use to create the map overlay
        batch.push(m);
        //add a reference to the same marker to an  array so that 
        //we can access it later to remove them
        marker_list[i] = m;
        //console.log("created marker for: "+ marker_list[i].labelText);
    }
    //alert(window.markers[0].name + "3");
    window.manager.addMarkers(batch, 4);
    batch = null;
    window.manager.refresh();
    //console.log("created markers: " + window.manager.getMarkerCount(8) );

}

function getElementsByStyleClass(className){
    var all = document.all ? document.all : document.getElementsByTagName('*');
    var elements = new Array();
    for (var e = 0; e < all.length; e++) 
        if (all[e].className == className) 
            elements[elements.length] = all[e].id;
    return elements;
}

function array_params(arry){
    //concatenating array onto variable string...
    var paramvar = "";
    arry.each(function(s){
        paramvar = paramvar.concat("guid_list[]=", s, "&");
    });
    paramvar = paramvar.replace(/&$/, "");
    //alert(paramvar);
    return paramvar;
    
}

function get_image_name(kw){
    //alert ("get image name parse" + parseInt(kw));
    switch (parseInt(kw)) {
    
        case 0:
            return '../images/1.png';
        case 1:
            return '../images/1.png';
        case 2:
            return '../images/2.png';
        case 3:
            return '../images/3.png';
        case 4:
            return '../images/4.png';
        case 5:
            return '../images/5.png';
        case 6:
            return '../images/6.png';
        case 7:
            return '../images/7.png';
        case 8:
            return '../images/8.png';
        case 9:
            return '../images/9.png';
        default:
            return '../images/10.png';
    }
}

function createMarker(pointData){

    //create a GLatLng struct to hold the point's location
    var latlng = new GLatLng(pointData.latitude, pointData.longitude);
    
    //the following creates the icon
    var icon = new GIcon();
    //alert("in createMarker");
    icon.image = get_image_name(pointData.kw);
    //alert(icon.image);
    icon.iconSize = new GSize(32, 32);
    icon.iconAnchor = new GPoint(16, 16);
    icon.infoWindowAnchor = new GPoint(25, 7);
    
    //this is the associative array used within the marker
    //it associates the above icon with the marker
    opts = {
        "icon": icon,
        "clickable": true,
        "labelText": pointData.kw,
        "labelOffset": new GSize(-16, -16)
    };
    
    //creaate a marker using the point information and opts
    var marker = new LabeledMarker(latlng, opts);
    //alert("built the marker");
    //this creates a variable pointing to a handler function
    var handler = createMarkerClickHandler(marker, pointData);
    //this adds a marker listener event for 'click' - assigned to the handler
    GEvent.addListener(marker, "click", handler);
    
    var marker_mouse_over_handler = function(){
        $(pointData.id).style.backgroundColor = "#66ff33";
        $(pointData.id).style.color = "red";
    };
    var marker_mouse_out_handler = function(){
        $(pointData.id).style.color = "#445555";
        $(pointData.id).style.backgroundColor = '';
    };
    
    GEvent.addListener(marker, "mouseover", marker_mouse_over_handler);
    GEvent.addListener(marker, "mouseout", marker_mouse_out_handler);
    
    set_sidebar(pointData, handler);
    //alert("set the sidebar");
    
    return marker;
}

function set_sidebar(pointData, handler){
    //alert("trying to set the sidebar");
    //the following creates  data to be used in the sidebar list
    var listItem = document.createElement('li');
    listItem.innerHTML = '<div style="background-image:url(' + get_image_name(pointData.kw) + ')" class="label" >' + +pointData.kw + '</div><a href="' + pointData.wp + '" id="' + pointData.id + '" class="label">' + pointData.name + '</a>';
    
    //all you need to do is assign the same handler to another event
    listItem.getElementsByTagName('a')[0].onclick = handler;
    
    //the following appends the newly created list item to the sidebar
    document.getElementById('sidebar-list').appendChild(listItem);
    
    draggable_array.push(new Draggable(pointData.id, {
        revert: true,
        snap: [40, 40]
    }));
}

function fill_trash(){
    $('trash').src = "/images/trashfull.jpg";
}

function empty_trash(){
    $('trash').src = "/images/trash.jpg";
    
}

// this is called when the page loads. 
// it initializes the map, and creates each marker
function initialize(){

    //this will call a local function to set up the map and events
    set_up_map();
    //prime the map with a first call for new data
    get_remote_data();
    //paint the graph
    new_lines_graph();
    
}

function unload_map_page(){
    
	//unload the map page
    GUnload();
}


function compares_post(id){
    var coordinates = "";
    coordinates = 'zoom=' + map.getZoom() + '&center_lat=' + map.getBounds().getCenter().lat() + '&center_lng=' + map.getBounds().getCenter().lng();
    //prepend the id parameter
    parameter_list = coordinates.concat('&id=' + id);
    return parameter_list;
    
}
