var req;
var map;

//var SERVER_URL = 'http://localhost:8080/RWVacancyGeoView';
var SERVER_URL = "http://www.ungiwg.org/RWVacancyGeoView";

var KML_URL = "/output_data/RW_vacancy_KML_output.kml";
var HTML_URL = "/output_data/RW_vacancy_HTML_output.html";
var GM_XML_URL = "/output_data/GMXML_output.xml";

//var FLAG_IMG_URL = "http://www.ungiwg.org/RWVacancyGeoView/img/flag_png/"; 
var FLAG_IMG_URL = "/img/flag_png/";
var FILTER_WAIT_ICON = "/img/filter_wait.gif";

//var ICONS_ROOT_PATH = "http://localhost:8080/RWVacancyGeoView/img/icons/";
var ICONS_ROOT_PATH = "http://www.ungiwg.org/RWVacancyGeoView/img/icons/";

//consts for icons
var PLACEMARK_W_H = 16 //32;

var FLAG_W = 16;
var FLAG_H = 11;

var gmarkers = [];
var markers;
var i=0;

var timeOut = 1;
var lMessage;

var AllLayers = [];
var countriesfound = [];
var vacanciesfound = [];
var mgr;
var marker_id=0;

var Filter_Active;
var TimeStampNote;
var NoVacancyInfo;

//consts for class breaks in symbols
var OVERFLOW_THRESHOLD = 1; //amount of overlap vacancies that determine when they should be aggregated
var class_limits = [9,20,50,200]; //class  limits for circles,

var array_found;

//filter values - keeps track for updates
var CURRENT_SECTOR_FILTER;
var CURRENT_ORG_FILTER;
var CURRENT_EXPIRE_FILTER;

var cat_name;
var cat_value;

function load() {
    if (GBrowserIsCompatible()) {
         
        toggleHelpMessage(0);
        
        lMessage = document.getElementById('lMessage');
        hideOverFlowTextDiv();
        
        
        
        map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl ());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(46.2266, 6.14041), 2);
        map.enableDoubleClickZoom();
        
        //set the min/max zoom levels Zoom level indices in GMap2 start with 0 at the coarsest level,
        var min_zoom = 2;
        var max_zoom = 10;
        
        G_PHYSICAL_MAP.getMinimumResolution = function () { return min_zoom };
        G_NORMAL_MAP.getMinimumResolution = function () { return min_zoom };
        G_SATELLITE_MAP.getMinimumResolution = function () { return min_zoom };
        G_HYBRID_MAP.getMinimumResolution = function () { return min_zoom };
        
        G_PHYSICAL_MAP.getMaximumResolution = function () { return max_zoom };
        G_NORMAL_MAP.getMaximumResolution = function () { return max_zoom };
        G_SATELLITE_MAP.getMaximumResolution = function () { return max_zoom };
        G_HYBRID_MAP.getMaximumResolution = function () { return max_zoom };
        
        //add moveend for checking that filters still apply
        Filter_Active = 0;
        CURRENT_EXPIRE_FILTER = '0';
        CURRENT_SECTOR_FILTER = '';
        CURRENT_ORG_FILTER = '';
        
        GEvent.addListener(map, "moveend", function () {
            
            //makes sure map filters stay applied when panning and zooming
            //might want to revisit this if more than 2 filter options are developed
            if (Filter_Active == 1) {
                show('','');
            }
            
        });
        
        GEvent.addListener(map, "zoomend", function (oldZ, newZ) {
            
            //makes sure map filters stay applied when panning and zooming
            //might want to revisit this if more than 2 filter options are developed
            //update this if the zoom level between the flags and the points change
            if (newZ > 3) {
                if (Filter_Active == 1) {
                    map.panBy(new GSize(1, 1));
                }
            }
        });
        
        
        mgr = new MarkerManager(map, {trackMarkers:true});
        
        //add HTML for pages not found
        var static_HTML_URL = SERVER_URL + HTML_URL;
        document.getElementById('output_page').src = static_HTML_URL;
        
        //get the marker XML
        var request = GXmlHttp.create();
        request.open("GET", SERVER_URL + GM_XML_URL, true);
        request.onreadystatechange = function() {
            
            if (request.readyState == 4) {
                var xmlDoc = request.responseXML;

                markers = xmlDoc.documentElement.getElementsByTagName("marker");

                //time stamp_info
                times =  xmlDoc.documentElement.getElementsByTagName("timestamp");
                TimeStampNote = times[0].getAttribute("time");

                no_vacancies =  xmlDoc.documentElement.getElementsByTagName("no_vacancy_count");
                NoVacancyInfo = no_vacancies[0].getAttribute("value");
                var NoVacanciesMessage = document.getElementById('NoVacanciesMessage');
                NoVacanciesMessage.innerHTML="";
                NoVacanciesMessage.innerHTML="<span class=\"Title\">Vacancies without location information</span><br><span class=\"vacancy_info\">(" + NoVacancyInfo + " vacancies out of " + markers.length + " total)</span>";

                window.setTimeout(GenerateMarkers,timeOut);
            }
        }
        
        request.send(null);
        
    }
    
    //call refresh again, in IE all flags weren't showing after load
    mgr.refresh();
    
}


function GenerateMarkers() {
    if ( i < markers.length ) {
        
        var max=Math.min(i+20, markers.length);
        
        while (i<max) {
            
            // ** determine zoom levels - countries
            //get the CCode of the item
            var current_country = markers[i].getAttribute("country");
            
            var acheck =  CheckArray(countriesfound, current_country);
            
            //see if the country has already been found
            if (acheck == 0) {
                
                var CCLat  = parseFloat(markers[i].getAttribute("ccentlat"));
                var CCLong = parseFloat(markers[i].getAttribute("ccentlong"));
                var cname = markers[i].getAttribute("cname");
                
                var space_index = cname.indexOf(" ",24);
                
                var fixed_cname;
                
                if (space_index != -1) {
                    var left = cname.substring(0,space_index);
                    var right = cname.substring(space_index,cname.length);
                    fixed_cname =  left + "<br>" + right;
                } else {
                    fixed_cname = cname;
            }
            
            //lcase the country name so it works with the flag icon as of 2/6/08
            var flag_icon = current_country.toLowerCase();
            
            var tempArray = [{'name': current_country, 'type': 'country', 'MarkerDescription': " vacancies in " + fixed_cname, 'count': 1 , 'icon': SERVER_URL + FLAG_IMG_URL + flag_icon + '.png', 'LatLong': [CCLat,CCLong]}];
            
            countriesfound.push  (tempArray);
            
        }
        
        
        //** create arrays for the actual vacancies
        var MarkerDescription = markers[i].childNodes[0].nodeValue;
        var expire_soon = markers[i].getAttribute("expire_soon");
        var IconToUse = markers[i].getAttribute("icon");
        var Lat  = parseFloat(markers[i].getAttribute("lat"));
        var Long = parseFloat(markers[i].getAttribute("long"));
        
        //April 2008 - org and sector types - comma strings
        var orgs = markers[i].getAttribute("orgs");
        var sectors = markers[i].getAttribute("sectors");
        
        //determine if the point overlaps with any other exisiting points, if so, gets is postion withing the overlap set (i.e 1 of 30)
        overlap_position =  CheckLatLongOverlap (vacanciesfound, Lat, Long, "get_position", 0);
        
        if (overlap_position == 0) { //first time for a coord, create new vacancy object
            
            //markers[i].childNodes[0].nodeValue - general description, markers[i].childNodes[1].nodeValue - followup URLs
            var data_temp = [{'MarkerDescription': markers[i].childNodes[0].nodeValue, 'expire_soon': expire_soon, 'overlap_position':  1, 'orgs': orgs, 'sectors': sectors} ]
            
            //add the followup URLs at the top of the array so they are easy to get at for overlaps - + markers[i].childNodes[1].nodeValue (URLs), they represent a generalization of the vacancy
            var tempVacancyArray = [{'id': marker_id, 'type': 'vacancy', 'overlap_count': 1,   'icon': IconToUse, 'LatLong': [Lat,Long], 'Data': [data_temp], 'FollowupURLs': markers[i].childNodes[1].nodeValue }];
            marker_id++;
            
            vacanciesfound.push  (tempVacancyArray);
        } else {
        
            //update sub-array
            //array found was indentied in the overlap
            var pos = array_found["Data"].length + 1;
        
            var data_temp = [{'MarkerDescription': markers[i].childNodes[0].nodeValue, 'expire_soon': expire_soon, 'overlap_position':  pos, 'orgs': orgs, 'sectors': sectors} ]
        
            array_found["Data"].push(data_temp);
        
            //sort the expire soons
            var exisiting_data = array_found["Data"];
        
            for ( var x=0; x<array_found["Data"].length; x++) {
            
                specific_data = array_found["Data"][x];
            
                for ( var y=0; y<specific_data.length; y++) {
                
                    var ex = specific_data[y];
                
                    if ( ex["expire_soon"] == "1") {
                        newArray =  array_found["Data"].splice(x,1); //cut it out
                    
                        var data_temp;
                    
                        for (var z = 0; z <newArray.length; z++) {
                        
                            var newA = newArray[z];
                            //console.log (newA[z]["expire_soon"]);
                        
                            //** remember to update if more attributes get added
                            data_temp = [{'MarkerDescription': newA[z]["MarkerDescription"], 'expire_soon': newA[z]["expire_soon"], 'overlap_position':  newA[z]["overlap_position"], 'orgs': newA[z]["orgs"], 'sectors': newA[z]["sectors"]} ]
                        
                        }
                    
                        array_found["Data"].splice(0,0, data_temp); //put it in the front
                    
                        // console.log (exisiting_data);
                    } //if ( ex["expire_soon"] == "1")
                }//for ( var y=0; y<specific_data.length; y++)
             } //for ( var x=0; x<array_found["Data"].length; x++)
        
            overlap_position = pos;
        
        }
    
    //update the array to reflect the total count of overlaps on the point
    CheckLatLongOverlap (vacanciesfound, Lat, Long,"update_array",overlap_position);
    
    i++;
    
    
    }//while (i<max)

    //user feedback
    if (lMessage) {
        lMessage.innerHTML="<span class=\"CloseDate\">Loading " + i + " of " + markers.length + "</span>";
        window.setTimeout(GenerateMarkers,timeOut);
    }

    if ( i >= markers.length ) {
        document.getElementById('loading').style.visibility='hidden';
        
        var lMessage_permanent = document.getElementById('lMessage_permanent');
        lMessage_permanent.innerHTML="";
        lMessage_permanent.innerHTML="<span class=\"CloseDate\">Information auto-processed on " + TimeStampNote + "</span>";

        //return to this at some point, animated GIFs don't work durng intense javascript runs'
        // lMessage.innerHTML="<img id=\"load\" src=\"" + SERVER_URL + FILTER_WAIT_ICON  + "\"/>" ;
        lMessage.innerHTML='';

        
        //put the full array together - modify values to alter zoom levels, was 0,4 and 5,17
        AllLayers.push ({"zoom": [0, 3],"places": countriesfound});
        AllLayers.push ({"zoom": [4, 17],"places": vacanciesfound});
        //console.log(AllLayers);

        //prcocess the markers through the marker manager
        setupManagedMarkers()

    }

}
}


function setupManagedMarkers() {
    
    for (var i in AllLayers) {
        var layer = AllLayers[i];
        var markers = [];
        for (var j in layer["places"]) {
            
            var place = layer["places"][j];
            
            //seem to have to enter another loop?
            for ( var x=0; x<place.length; x++) {
                
                specific_place = place[x];
                
                var MarkerType = specific_place["type"];
                var Array_ID = specific_place["id"];
                
                //these values adjust the symbol to the center of symbol relative to the upper left
                //modify if the symbol for single vacancy changes
                var adjusted_x = 8; //15;
                var adjusted_y = 8; //15;
                var info_window_anchor = 6;
                
                var icon_w;
                var icon_h;
                
                var overflow_icon = '';
                
                if (MarkerType == 'country') {
                    
                    icon_w = FLAG_W;
                    icon_h = FLAG_H;
                    
                } else if (MarkerType == 'vacancy') {
                    //set H and W to defaults
                    icon_w = PLACEMARK_W_H;
                    icon_h = PLACEMARK_W_H;
                }
            
            
                var symbols_per_circle_base = 9; //number of points in a circle, used to determine if multiple rings are needed, increase size
                var radial_base_value = 20;
                var radial_adjust_value = 15;
                var radial_value;  //adjust as need be
                var overlap_count;
            
                if (MarkerType == 'vacancy') {
                
                    overlap_count = parseInt(specific_place["overlap_count"]);
                
                    if (overlap_count > 1) { //for counts > 1, determine the division of the circle
                    
                        var circle_position = parseInt(specific_place["overlap_position"]);
                        var circle_increments;
                    
                        //see how many circles will be needed
                        if (overlap_count > OVERFLOW_THRESHOLD) {
                        
                            var circle_class_position; //which circle class the point falls into
                        
                            //determine what class the current point falls into
                            for (var z = 0; z<class_limits.length; z++) {
                                if (overlap_count <= class_limits[z] ) {
                                    circle_class_position = z;
                                    break;
                                }
                            
                            }
                        
                            //override the default symbol with the symbol that represents the class
                            overflow_icon = circle_class_position + ".png";
                        
                        } //(overlap_count > OVERFLOW_THRESHOLD) 
                    
                    }
                
                } //(MarkerType == 'vacancy')
            
                //get the details of the marker to be constructed
                var posn = new GLatLng(specific_place["LatLong"][0], specific_place["LatLong"][1]);
            
                //set description based on the type
                var MarkerDescription  = '';
            
                //get the followup URLs to possibly place on top
                var FollowupURLs = specific_place["FollowupURLs"];
            
                if (MarkerType == 'country') {
                    MarkerDescription  = "<span class=\"BubbleText\"><br>" + specific_place["count"] + specific_place["MarkerDescription"] + "</span>";
                } else if (MarkerType == 'vacancy') {
            
                    var hasOverflow = 0;
                    var expire_soon;

                    if (overlap_count > OVERFLOW_THRESHOLD) {
                        hasOverflow = 1;
                    }

                    //go into data sub-array and get values
                    var exisiting_data = specific_place["Data"];
            
                    for ( var x=0; x<specific_place["Data"].length; x++) {
                
                        specific_data = specific_place["Data"][x];
                
                        //1 increment loop on a specific overflow vacancy
                        for ( var y=0; y<specific_data.length; y++) {
                    
                            var specific_item = specific_data[y];
                    
                            if (hasOverflow == 1) { //create aggregated string for overflow box
                        
                                //first time
                                if (x ==0) {
                            
                                    MarkerDescription = FollowupURLs + "<hr>" + specific_item["MarkerDescription"];
                            
                                } else {
                        
                                    MarkerDescription += "<hr>" + specific_item["MarkerDescription"];
                                    expire_soon = 1; //set to automatically keep overflows present when a filter happens
                        
                                }
                            } else { //create marker for non-overflow or single
                
                                if (overlap_count > 1) { //for counts > 1, determine the division of the circle
                    
                                    var circle_position = parseInt(specific_item["overlap_position"]);
                                    var circle_increments;
                    
                                    //only one circle of points, use default
                                    radial_value = radial_base_value;
                                    circle_increments = Math.round (360/overlap_count);
                    
                                    //determine how many angle increments the point is
                                    var angle = circle_increments  * circle_position;
                                    var angle_radians = angle*Math.PI/180;
                    
                                    //calculate X,Y coords from polar coords
                                    adjusted_x = radial_value * Math.cos(angle_radians);
                                    adjusted_y = radial_value * Math.sin(angle_radians);
                    
                                    //this adjusts the points so they cluser around the lat/long coord correctly since the anchor point is relative to the upper left of the symbol icon
                                    //modify this value based on the the x,y difference between the center of the symbol and its upper left
                                    var x_img_move = 10; //15;
                                    var y_img_move = 10; //15;
                    
                                    adjusted_x = adjusted_x + x_img_move;
                                    adjusted_y =  adjusted_y  + y_img_move;
                    
                                 }
                
                                //redundant, but necessary
                                var icon = new GIcon();
                                icon.image = ICONS_ROOT_PATH + specific_place["icon"];
                                icon.shadow = null;
                
                                //IE needs an icon size - see http://groups.google.com/group/Google-Maps-API/browse_thread/thread/4d2776363c2ab52c for details
                                icon.iconSize = new GSize(icon_w, icon_h);
                                icon.iconAnchor = new GPoint(adjusted_x, adjusted_y);
                                icon.infoWindowAnchor = new GPoint(info_window_anchor, info_window_anchor);
                                icon.infoShadowAnchor = new GPoint(info_window_anchor + 2, info_window_anchor + 4);
                
                                MarkerDescription = specific_item["MarkerDescription"] + FollowupURLs;
                
                                expire_soon = specific_item["expire_soon"];
                
                                //get the org and sector info
                                var org_info = specific_item["orgs"];
                                var sector_info = specific_item["sectors"];
                
                                //create the marker right away while looping on the instance data
                                var marker = createMarker(posn,MarkerDescription,icon,expire_soon, MarkerType,org_info,sector_info,Array_ID, x);
                
                                markers.push(marker);
                
                        }//create marker for non-overflow or single
            
                    }//for ( var y=0; y<specific_data.length; y++)
                    
                }//for ( var x=0; x<specific_place["Data"].length; x++)
    
            }//else if (MarkerType == 'vacancy')

            //create markers for aggregated
            if (hasOverflow == 1 || MarkerType == 'country') {
    
                var icon_img;
    
                //see if it is an overflow text to structure the marker correctlty
                if (hasOverflow == 1) {
        
                    MarkerDescription = "<p>" + overlap_count + " vacancies at location</p>"  + MarkerDescription;
        
                    MarkerType = 'overflow';
        
                    icon_img = ICONS_ROOT_PATH + overflow_icon;
        
                    //set img size based on the data class, should match what the underlying img files are
        
                    var override_val;
                    var override_adjust;
        
                    if (circle_class_position == 0) {
                        override_val = 23;
                        override_adjust = 12;
                    } else if (circle_class_position == 1) {
                        override_val = 31;
                        override_adjust = 15;
                    } else if (circle_class_position == 2) {
                        override_val = 40;
                        override_adjust = 20;
                    } else if (circle_class_position == 3) {
                        override_val = 53;
                        override_adjust = 26;
                    }

                    icon_w = override_val;
                    icon_h = override_val;

                    adjusted_x = override_adjust;
                    adjusted_y = override_adjust;

                } else {
                    icon_img = specific_place["icon"]; //ICONS_ROOT_PATH + specific_place["icon"];
                }

            //redundant, but necessary
            var icon = new GIcon();
            icon.image = icon_img
            icon.shadow = null;

            //IE needs an icon size - see http://groups.google.com/group/Google-Maps-API/browse_thread/thread/4d2776363c2ab52c for details
            icon.iconSize = new GSize(icon_w, icon_h);

            icon.iconAnchor = new GPoint(adjusted_x, adjusted_y);

            icon.infoWindowAnchor = new GPoint(15, 15);
            icon.infoShadowAnchor = new GPoint(18, 25);

            var marker = createMarker(posn,MarkerDescription,icon,expire_soon,MarkerType,'','',Array_ID)

            markers.push(marker);

            } //if (hasOverflow == 1 || MarkerType == 'country')

        } //if (MarkerType == 'vacancy')

    } //for ( var x=0; x<place.length; x++)

    mgr.addMarkers(markers, layer["zoom"][0], layer["zoom"][1]);

    } //for (var j in layer["places"])
    
    mgr.refresh();

} 


function createMarker(point,html,icon, attribute_expire_soon, marker_type,attribute_org_info,attribute_sector_info, attribute_array_id, data_id) {
    
    var isOverflowMarker;
    
    if (marker_type != 'overflow') { //flags and standard vacancy points
        
        
        isOverflowMarker = 0;
        
        if (marker_type != 'country') { //standard single vacancy
            var marker = new GMarker(point,icon);
            GEvent.addListener(marker, "click", function() {
                marker.openInfoWindowHtml(html);
            });
            
            
        } else { //flag - mouse over
        
        var marker = new GMarker(point,icon);
        GEvent.addListener(marker,"mouseover", function() {
            marker.openInfoWindowHtml(html);
        });
    }
    
} else { //overflow marker, different kind of output

//map.addOverlay(new GMarker(new GLatLng(43.92,-79.3),{zIndexProcess:inverseOrder}));

    var marker = new GMarker(point,icon);
    GEvent.addListener(marker, "click", function() {
        openOverflowTextDiv(html);
    });

    isOverflowMarker = 1;

}

    //add attributes to individual markers
    marker.expire_soon = attribute_expire_soon;
    marker.orgs = attribute_org_info;
    marker.sectors = attribute_sector_info;
    marker.array_id = attribute_array_id;
    marker.data_id = data_id;
    marker.isOverflowMarker = isOverflowMarker;
    marker.type = marker_type;

    gmarkers.push(marker);

return marker;
}

function inverseOrder(marker,b) {
    return -GOverlay.getZIndex(marker.getPoint().lat());
}

function openOverflowTextDiv(html) {
    
    document.getElementById("overflow_text_area").innerHTML = '';
    document.getElementById("overflow_text_area").innerHTML = html;
    document.getElementById("overflow_text_area").scrollTop = 0;
    document.getElementById("OverFlowTextDiv").style.visibility='visible';
    
}
function CheckArray (ArrayToCheck, valueToCheck) {
    
    var name;
    
    if (ArrayToCheck.length != 0) {
        
        for (var i=0; i<ArrayToCheck.length; i++) {
            
            
            //get the array object from the incoming array
            var CurrentSubArray = ArrayToCheck[i];
            
            //loop through that array
            for ( var x=0; x<CurrentSubArray.length; x++) {
                
                n = CurrentSubArray[x];
                arrayname = n["name"];
                count = n["count"];
                //console.log (n["name"]);
            }
            
            if (arrayname == valueToCheck) {
                //console.log("car 1");
                n["count"] = count + 1;
                return 1;
                
            }
            
        }
        
    }
    
    //nothing found
    
    return 0;
    
    
}



//this may need to be moved the java side if it creates too much of a performance hit
function CheckLatLongOverlap (ArrayToCheck, LatValueToCheck, LongValueToCheck, type, update_value) {
    
    var name;
    var timesFound = 0;
    var expires_found = 0;
    
    var temp_array = new Array();
    var temp_array_indexes = new Array();
    
    var overflow_found = 0;
    var tempOverflowVacancyArray;
    
    
    if (ArrayToCheck.length != 0) {
        
        for (var i=0; i<ArrayToCheck.length; i++) {
            
            //console.log (ArrayToCheck);
            
            //get the array object from the incoming array
            var CurrentSubArray = ArrayToCheck[i];
            
            //loop through that array
            for ( var x=0; x<CurrentSubArray.length; x++) {
                
                n = CurrentSubArray[x];
                
                arrayLat =  n["LatLong"][0];
                arrayLong = n["LatLong"][1];
                
                
                if (LatValueToCheck == arrayLat && LongValueToCheck == arrayLong) {
                    // console.log("vals equal " + " overlap_count:" + overlap_count + " times_found:" + timesFound + " " + LatValueToCheck);
                    
                    if (type == "get_position") {
                        timesFound++;
                        array_found = n;
                    } else if (type == "update_array") {
                    
                    n["overlap_count"] = update_value;
                    
                    timesFound++;
                    
                }//} else if (type == "update_array")
                
                
            } //for ( var x=0; x<CurrentSubArray.length; x++)
            
        } //for (var i=0; i<ArrayToCheck.length; i++)
        
    }
    
}


return timesFound;


}

//http://www.codingforums.com/showthread.php?t=43962
function pause () {
    show(cat_name,cat_value);
}


// == a checkbox has been clicked ==
function filterclick(option,category_name,category_value ) {
    if (option.checked) {
        
        showFeedBack(1);
        Filter_Active = 1;
        cat_name = category_name;
        cat_value = category_value;
        
        // pause flow of code for a short period so the feedback div has a chance to draw
        setTimeout("pause();",20);
        
    }
    
}

function showFeedBack (status) {
    
    if (status == 1) {
        //alert('stop1');
        hideOverFlowTextDiv();
        document.getElementById('loading').style.visibility='visible';
        var load = document.getElementById('load')
        load.innerHTML='';
        load.innerHTML= "<span class=\"FilterHeader\">Applying filter, please wait...</span>";
        
        
    } else {
    document.getElementById('loading').style.visibility='hidden';
}

}

// == shows all markers of a particular category
function show(category_name,category_value) {
    
    var filter_values; //array for keeping exisitng filter and new filters to ensure old ones are kept

    //check if it is just a map movement test, a blank category name will come in if so
    if (category_name != '') {
        //set globals
        if (category_name == 'expire_soon') {
            CURRENT_EXPIRE_FILTER = category_value;
        } else if (category_name == 'sectors') {
            CURRENT_SECTOR_FILTER = category_value;
        } else if (category_name == 'orgs') {
            CURRENT_ORG_FILTER = category_value;
        }

        map.closeInfoWindow(); //close map window automatically when a new filter comes in
    }

    //set so new values and old values are all checked
    filter_values = [];

    //filter_values = [{'sectors': CURRENT_SECTOR_FILTER, 'orgs': CURRENT_ORG_FILTER, 'expire_soon':  CURRENT_EXPIRE_FILTER} ];
    filter_values ["sectors"] =  CURRENT_SECTOR_FILTER;
    filter_values ["orgs"] = CURRENT_ORG_FILTER;
    filter_values ["expire_soon"] =   CURRENT_EXPIRE_FILTER;

    // check and see if in fact all the filter have been removed, simplfys the process
    var AllFiltersRemoved = 1;
    Filter_Active = 0;
    var v;

    for (v in filter_values) {

        if (filter_values[v] != '' || filter_values[v] != "0") {
            AllFiltersRemoved = 0;
            Filter_Active = 1;
            break;
        }
    }

    v=null;

    for (var i=0; i<gmarkers.length; i++) {
    
        var hasOverFlow = 0;
    
        //see if the marker is an overlap marker
    
        if ( gmarkers[i].type != 'country') {
        
            if (gmarkers[i].isOverflowMarker == 1 ) {
                hasOverFlow = 1;
            }

            //get the markers sub-array elements from AllLayers
            var ArrayID = gmarkers[i].array_id;
        
            var HTMLToKeep = ''; //HTML that will be kept as a result of the filter
        
            var layer = AllLayers[1]; //start at 1, where the vacancies are (as opposed to country flags)
        
            var place = layer["places"][ArrayID]; //go right to element with the overflow (or not)
        
            var specific_place = place[0]; //element 0 gets to the places
        
            //go into data sub-array and get values
            var exisiting_data = specific_place["Data"];
            var FollowupURLs = specific_place["FollowupURLs"];
            var overlap_count  = specific_place["overlap_count"];

            var filter_match_number = 0; //the number of vacancies that match the filter, used for overlap text
        
            if (hasOverFlow == 1) {
            
                var buffer='';
            
            //this is done so one marker can be removed
            for ( var x=0; x<specific_place["Data"].length; x++) {
                
                var specific_data = specific_place["Data"][x];
                
                var specific_filter_items_found = []; //keeps track of which items were found to prevent duplicate addtions to overflow text
                var backup_HTML = ''; //a backup
                var current_HTML = '';
                var match_score = 0;
                
                //loop through the elements of a single specific vacancies
                for ( var y=0; y<specific_data.length; y++) {
                    
                    var specific_item = specific_data[y]; //1 element?
                    
                    //get the org and sector info
                    var org_info = specific_item["orgs"];
                    var sector_info = specific_item["sectors"];
                    var expire_soon = specific_item["expire_soon"];
                    current_HTML = specific_item["MarkerDescription"];
                    
                    if (AllFiltersRemoved == 0) { //there is a filter
                        // match_score = checkFilters_func(filter_values, sector_info, org_info, expire_soon);
                        //check which filters are on
                        match_score = checkFilters (filter_values, sector_info, org_info, expire_soon);
                        
                    } else { //if (AllFiltersRemoved == 0)
                    
                        //if all the filters have been removed, simply rebuild the full HTML string
                        //first time
                        if (buffer == '') {

                            buffer = FollowupURLs + "<hr>" + specific_item["MarkerDescription"];

                        } else {
                            buffer += "<hr>" + specific_item["MarkerDescription"];

                        }
                    }
            
                } // for ( var y=0; y<specific_data.length; y++)
        
                var match_buffer;
        
                //once all the values have been checked ,if three matches meeting filter criteria were found, keep the HTML
                if (match_score == 3) {

                    filter_match_number++;

                   // match_buffer = (x == 0)?FollowupURLs + "<hr>" + current_HTML:"<hr>" + current_HTML;
                    match_buffer = ( buffer == '')?FollowupURLs + "<hr>" + current_HTML:"<hr>" + current_HTML;

                    buffer +=  match_buffer;
                    
                } //if (match_score == 3)
        
            } // for ( var x=0; x<specific_place["Data"].length; x++)
    
            HTMLToKeep = buffer;
    
        } else  { //if overflow

            //if not an overflow, go directly to the data element,
            var specific_data = specific_place["Data"][gmarkers[i].data_id];
            // console.log(specific_data);
            var specific_item = specific_data[0];

            //get the org and sector info
            var org_info = specific_item["orgs"];
            var sector_info = specific_item["sectors"];
            var expire_soon = specific_item["expire_soon"];
            current_HTML = specific_item["MarkerDescription"];

            match_score = checkFilters (filter_values, sector_info, org_info, expire_soon);

            if (match_score == 3) {

                HTMLToKeep = FollowupURLs + "<hr>" + current_HTML;

            } //if (match_score == 3)

        }

        //if HTMLToKeep is still '', then no filters were found, symbol should be removed

        if (HTMLToKeep == '') {
            gmarkers[i].hide();
        } else {

            gmarkers[i].show();

            if (hasOverFlow == 1) {

                //add x of y info filter_match_number
                var number_info;

                if (overlap_count == filter_match_number ) {
                    number_info = "<p>" + overlap_count + " vacancies at location</p>";
                } else {
                    number_info = "<p>" + filter_match_number + " of " + overlap_count + " vacancies shown at location (filter active)</p>";

                    /* return to this part for changing the symbols based on a filter
                     var class_position; //which circle class the point falls into

                    //determine what class the current point falls into
                    for (var z = 0; z<class_limits.length; z++) {
                        if (filter_match_number <= class_limits[z] ) {
                            class_position = z;
                            break;
                        }
                    }
                    overflow_icon = ICONS_ROOT_PATH + class_position + ".png";
                    //in the next line, the crash happens..
                    gmarkers[i].setImage( overflow_icon);
                    */
                }

                HTMLToKeep = number_info + HTMLToKeep;

                //modify the overflow text value, single markers don't matter - need to send to outside process to prevent pitfall with creating markers and local variables - http://econym.googlepages.com/basic1.htm
                reBuildMarkerHTML (gmarkers[i],HTMLToKeep);

            } //if (hasOverFlow == 1)
          
          } //if (HTMLToKeep == '')

        }//if ( gmarkers[i].type != 'country')

    } //for (var i=0; i<gmarkers.length; i++)

    //turn off feedback if a filter came in
    if (category_name != '') {
        showFeedBack(0);
    }


    //make sure the filter active switch is off if relevant
    var v;
    var filters_clear = 0;
    for (v in filter_values) {
       // console.log("what " + filter_values[v]);
        if (filter_values[v] == '' || filter_values[v] == "0") {
            filters_clear++;
            Filter_Active = 0;
        }
    }

    Filter_Active = filters_clear == 3?0:1;

    //clean up
    filter_values = null;
    exisiting_data = null;
    specific_place = null;
    place = null;
    layer = null;

}

function reBuildMarkerHTML (pInputMarker, pNewHTML) {
    
    GEvent.addListener(pInputMarker, "click", function() {
        openOverflowTextDiv(pNewHTML);
    });
}

function setNewImage (point,icon,html) {
    var marker = new GMarker(point,icon);
    GEvent.addListener(marker, "click", function() {
        openOverflowTextDiv(html);
    });

    isOverflowMarker = 1;

    gmarkers.push(marker);

}


function showAll(option) {
    if (option.checked) {
        Filter_Active = 0;
        for (var i=0; i<gmarkers.length; i++) {
            gmarkers[i].show();
        }
    }
    
}

// == hides all markers of a particular category, and ensures the checkbox is cleared ==
function hide(category) {
    for (var i=0; i<gmarkers.length; i++) {
        if (gmarkers[i].mycategory == category) {
            gmarkers[i].hide();
        }
    }
    // == clear the checkbox ==
    //document.getElementById(category+"box").checked = false;
    // == close the info window, in case its open on a marker that we just hid
    //  map.closeInfoWindow();
}

//return 'true' for even, 'false' for odd
function checkOddEven (inputNum) {
    
    return !(inputNum % 2);
    
}

function hideOverFlowTextDiv() {
    document.getElementById("OverFlowTextDiv").style.visibility='hidden';
}
/*
* args - 1 to show, zero not
*/
function toggleHelpMessage(status) {
    
    
    var visbility;
    var html;
    var height_val;
    
    if (status == 0) {
        visbility = 'hidden';
        html = "<a href=\"javascript:toggleHelpMessage(1);\">Show Quick Help</a>";
        height_val = 5;
    } else {
        visbility = 'visible';
        html = "<a href=\"javascript:toggleHelpMessage(0);\">Hide Quick Help</a>";
        height_val = 168;
    }
    
    
    //apply settings
    document.getElementById("help_message").style.visibility=visbility;
    document.getElementById("help").style.height=height_val + 'px';
    
    
    
    document.getElementById("help_show").innerHTML = '';
    document.getElementById("help_show").innerHTML = html;
    
    
   
    
}


/*
* checks the filters values of the current vacancy against the filters selected for the map
*@param - filter_values - the map filters selected
*@param(s) - sector_info, org_info, expire_soon - the filter values of the current vacancy
*/
function checkFilters (filter_values, sector_info, org_info, expire_soon) {
    
    var match_score = 0;
    var split_val;
    
    for (f  in filter_values) {
        
        //console.log (f + ' ' + filter_values[f])
        
        
        //don't check filter values if = ''
        if (filter_values[f] != '') {
            
            // console.log([f]);
            
            //go through each of the filter types and make the checks
            //the category is the new filter coming in as per the user request
            if (f == 'sectors') {
                split_val = sector_info;
                
            } else if (f == 'orgs') {
            split_val = org_info;
            
        } else if (f == 'expire_soon') {
        split_val = expire_soon;
        
        //special case for expires - any 1 expire should automatically be included with 0
        if (filter_values[f] == "0") {
            split_val = "0,1";
        }
        
    }
    
    var splitResults = split_val.split(",");
    
    //go through the split and see if it matches the filter
    for (var z = 0; z<splitResults.length; z++) {
        
        if (splitResults[z].toLowerCase().indexOf(filter_values[f].toLowerCase()) != -1) {
            //if a match was found, increment the match score
            match_score++;
            
        }//if (splitResults[z].toLowerCase().indexOf(filter_values[f].toLowerCase()) != -1)
        
    } //for (var z = 0; z<splitResults.length; z++)
    
} else { //if (filter_values[f] != '')
//increment the match score on blank filters

match_score++;

}

}// for (f in filter_values)


return match_score;

}

