var map;
var mgr;
var centerLatitude = 35;
var centerLongitude = -94;
var startZoom = 3;
var stateZoom = 3;
var listClickZoom = 12;
var pointZoom = 5;
var pointsLoaded;
var focusPoint;
var focusLat = 0;
var focusLng = 0;
var emailLink = '';
var auth;
var userid;
var frm;
var reset = 'false';

// state icon
var iconState = new GIcon();
iconState.image = "/wp-content/themes/expoblog/images/icons/marker-state.png";
iconState.shadow = "/wp-content/themes/expoblog/images/icons/marker-shadow.png";
iconState.iconSize = new GSize(20, 34);
iconState.shadowSize = new GSize(40, 34);
iconState.iconAnchor = new GPoint(10, 34);

// point icon
var iconPoint = new GIcon();
iconPoint.image = "/wp-content/themes/expoblog/images/icons/marker-populated.png";
iconPoint.shadow = "/wp-content/themes/expoblog/images/icons/marker-shadow.png";
iconPoint.iconSize = new GSize(20, 34);
iconPoint.shadowSize = new GSize(40, 34);
iconPoint.iconAnchor = new GPoint(10, 34);
iconPoint.infoWindowAnchor = new GPoint(10, 1);
iconPoint.infoShadowAnchor = new GPoint(20, 20);

// Exhibitor point icon
var iconExhibitor = new GIcon();
iconExhibitor.image = "/wp-content/themes/expoblog/images/icons/marker-exhibitor.png";
iconExhibitor.shadow = "/wp-content/themes/expoblog/images/icons/marker-shadow.png";
iconExhibitor.iconSize = new GSize(20, 34);
iconExhibitor.shadowSize = new GSize(40, 34);
iconExhibitor.iconAnchor = new GPoint(10, 34);
iconExhibitor.infoWindowAnchor = new GPoint(10, 1);
iconExhibitor.infoShadowAnchor = new GPoint(20, 20);

// Speaker point icon
var iconSpeaker = new GIcon();
iconSpeaker.image = "/wp-content/themes/expoblog/images/icons/marker-speaker.png";
iconSpeaker.shadow = "/wp-content/themes/expoblog/images/icons/marker-shadow.png";
iconSpeaker.iconSize = new GSize(20, 34);
iconSpeaker.shadowSize = new GSize(40, 34);
iconSpeaker.iconAnchor = new GPoint(10, 34);
iconSpeaker.infoWindowAnchor = new GPoint(10, 1);
iconSpeaker.infoShadowAnchor = new GPoint(20, 20);

function setCenter()
{
    map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
}

function clearAttendeeList(attendeeTable)
{
    while (attendeeTable.hasChildNodes()) attendeeTable.removeChild(attendeeTable.firstChild)
}

function clearList(list)
{
    var selected;

    if(reset == 'true') selected = 0
    else selected = list.selectedIndex;

    list.options.length = 0;

    return selected;
}

// this function was placed in because IE does not follow standards go figure.
function addOptionHack(select, option)
{
    try
    {
        // stendards compliant
        select.add(option, null);
    }
    catch(ex)
    {
        // work around for IE
        select.add(option);
    }
}
function populateIndustries(industries)
{

    iselect = document.getElementById("industry");
    selected = clearList(iselect);

    var total = 0;
    for(i in industries)
    {
        total = total + industries[i].count;
    }

    var o = document.createElement('option');
    o.text = "All Industries (" + total + ")";
    o.value = 'all';
    addOptionHack(iselect, o);

    for(i in industries)
    {
        var o = document.createElement('option');
        o.text = industries[i].text + ' (' + industries[i].count + ')';
        o.value = industries[i].id;
        if(o.value == selected) o.selected = true;
        addOptionHack(iselect, o);
    }
}
function populateCosizes(cosizes)
{
    var total = 0;
    for(i in cosizes)
    {
        total = total + cosizes[i].count;
    }

    cselect = document.getElementById("cosize");
    selected = clearList(cselect);

    var o = document.createElement('option');
    o.text = "All Company Sizes (" + total + ")";
    o.value = 'all';
    addOptionHack(cselect, o);

    for(i in cosizes)
    {
        var o = document.createElement('option');
        o.text = cosizes[i].text + ' (' + cosizes[i].count + ')';
        o.value = cosizes[i].id;
        if(o.value == selected) o.selected = true;
        addOptionHack(cselect, o);
    }
}

function populateDropDowns(industries, cosizes)
{
    populateIndustries(industries);
    populateCosizes(cosizes);
}

function init() {
    showLoaderGraphic();

    auth = document.getElementById("auth");
    userid = document.getElementById("userid");
    if(userid.value == "") userid.value = 0;
    var t = window.setTimeout('hideLoaderGraphic()', 2500);
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
        map.enableDoubleClickZoom();
        map.addControl(new GLargeMapControl());
        setCenter();

        pointsLoaded = 'false';
        focusPoint = 'false';

        populateDropDowns(industries, cosizes);
        updateAttendeeList(attendees);
        updateMarkers();

        GEvent.addListener(map,'moveend',function() {
            updateMarkers();
        });

        reset = 'false';
    }
}

function resetMap()
{
    reset = 'true';
    init();
}

function updateMarkers() {
    var t = window.setTimeout('hideLoaderGraphic()', 2500);
    var currentZoom = map.getZoom();
    if(currentZoom < pointZoom) pointsLoaded = 'false';
    if(currentZoom <= pointZoom  && pointsLoaded == 'false')
    {
        showLoaderGraphic();
        if(currentZoom == (pointZoom + 1)) pointsLoaded = 'true';
        map.clearOverlays();
        var cssClass = 'vcard';

        var bounds = map.getBounds();
        var southWest = bounds.getSouthWest();
        var northEast = bounds.getNorthEast();
        var getVars = 'ne=' + northEast.toUrlValue() + '&sw=' + southWest.toUrlValue() + '&currentZoom=' + map.getZoom() + '&fromuserid=' + userid.value;

        if(reset == 'true')
        {
            getVars = getVars + '&industry=all&cosize=all';
        }
        else
        {
            frm = document.getElementById("filters");
            for (var i = 0; i < frm.length; i++) {
                getVars = getVars + '&' + frm[i].name + '=' + frm[i].value;
            }
        }

        var stateList = [];
        var pointList = [];


        mgr = new GMarkerManager(map);

        //retrieve the points
        var request = GXmlHttp.create();

        request.open('GET', '/map-server.php?'+getVars, true);
        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                var jscript = request.responseText;
                eval(jscript);

                if(currentZoom < pointZoom)
                {
                    //create each point from the list
                    for (i in states) {
                        var point = new GLatLng(states[i].lat,states[i].lng);
                        var name = states[i].name;
                        var marker = createMarker(point, 'state', '', name);
                        map.addOverlay(marker);
                    }
                }
                else
                {
                    for (z in points) {
                        var point = new GLatLng(points[z].lat,points[z].lng);
                        var name = points[z].name;
                        var marker = createMarker(point, 'point', points[z].attendeetype, name);

                        map.addOverlay(marker);
                        if(focusPoint == 'true' && focusLat == points[z].lat && focusLng == points[z].lng) marker.openInfoWindowHtml(name);
                    }
                }
            }
        }
        request.send(null);
    }
}

function createMarker(point, type, attendeeType, name)
{
    if(type == 'state')
    {
        var marker = new GMarker(point, iconState, false);
        GEvent.addListener(marker, "click", function() {
            map.setCenter(point, pointZoom);
        });
    }
    else
    {
        if(attendeeType == '10' || attendeeType == "11" || attendeeType == "12" || attendeeType == "13") icon = iconSpeaker;
        else if(attendeeType == '8' || attendeeType == "9") icon = iconExhibitor;
        else icon = iconPoint;

        var marker = new GMarker(point, icon, false);
        GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml(name);
        });

    }
    return marker;
}

function onChange(frm)
{
    map.clearOverlays();

    var bounds = map.getBounds();

    var currentZoom = map.getZoom();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var getVars = 'ne=' + northEast.toUrlValue() + '&sw=' + southWest.toUrlValue() + '&currentZoom=' + map.getZoom() + '&fromuserid=' + userid.value;

    var request = GXmlHttp.create();

    for (var i = 0; i < frm.length; i++) {
        getVars = getVars + '&' + frm[i].name + '=' + frm[i].value;
        if(frm[i].value == "all") setCenter();
    }

    request.open('GET', '/map-server.php?'+getVars, true);
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            var jscript = request.responseText;
            eval(jscript);

            updateAttendeeList(attendees);
            populateDropDowns(industries, cosizes);

            if(currentZoom < pointZoom)
            {
                //create each point from the list
                for (i in states) {
                    var point = new GLatLng(states[i].lat,states[i].lng);
                    var name = states[i].name;
                    var marker = createMarker(point, 'state', '', name);
                    map.addOverlay(marker);
                }
            }
            else
            {
                for (z in points) {
                    var point = new GLatLng(points[z].lat,points[z].lng);
                    var name = points[z].name;
                    var marker = createMarker(point, 'point', points[z].attendeetype, name);
                    map.addOverlay(marker);
                }
            }
        }
    }
    request.send(null);
}

function focusOnPoint(lat, lng)
{
    pointsLoaded = 'false';
    focusPoint = 'true';
    focusLat = lat;
    focusLng = lng;

    map.setCenter(new GLatLng(lat, lng), pointZoom);
    map.setCenter(new GLatLng(lat, lng), listClickZoom);
}

function openMailWindow(fromuserid, touserid)
{
    window.open('http://www.ereexpoblog.com/email-attendee-form.php?fromuserid=' + fromuserid + '&touserid=' + touserid,'test','scrollbars=yes,menubar=no,height=600,width=550,resizable=yes,toolbar=no,location=no,status=no');
}

function loginMessage()
{
    alert('You must be logged in as a conference participant in order to email an attendee. You can login via the link at the bottom of this page');
}
function updateAttendeeList(list)
{
    var attendeeTable = document.getElementById("listTable");
    clearAttendeeList(attendeeTable);
    var count = 0;
    for(y in list)
    {
        count++;
        var style;

        if((Number(y.substr(1)) % 2) != 0) style = 'vcard';
        else style = 'vcard alternate';

        row = document.createElement('tr');
        row.className = style;

        // marker cell
        var markerCell = document.createElement('td');

        attendeeType = list[y].attendeetype;

        if(attendeeType == '10' || attendeeType == "11" || attendeeType == "12" || attendeeType == "13") marker = 'marker-speaker.png';
        else if(attendeeType == '8' || attendeeType == "9") marker = 'marker-exhibitor.png';
        else marker = 'marker-populated.png';

        markerCell.innerHTML = '<a href="#column-main" onclick="focusOnPoint(' + list[y].lat + ',' + list[y].lng + ');"><img src="/wp-content/themes/expoblog/images/icons/' + marker + '" alt="map it" /></a>';

        row.appendChild(markerCell);

        // attendee cell
        var attendeeCell = document.createElement('td');
        if(auth.value == "1") link = ' <a href="javascript:openMailWindow(' + userid.value + ',' + list[y].id + ');">';
        else link = ' <a href="javascript:loginMessage();">';
        emailLink = link + '<img src="/wp-content/themes/expoblog/images/icons/email.png" alt="email" /></a>';
        attendeeCell.innerHTML = '<p class="fn">' + list[y].fname + ' ' + list[y].lname + emailLink + '</p><p class="title">' + list[y].title + '</p><p class="org">' + list[y].company + '</p>';
        row.appendChild(attendeeCell);

        // location cell
        var locationCell = document.createElement('td');
        if(list[y].country != 'USA' && list[y].country != "")
        {
            if(list[y].city == "") locationCell.innerHTML = '<p class="adr"><span class="locality">' + list[y].country + '</span></p>';
            else if(list[y].city != "" && list[y].state == "") locationCell.innerHTML = '<p class="adr"><span class="locality">' + list[y].city + '<br />' + list[y].country + '</span></p>';
            else if(list[y].city != "" && list[y].state != "") locationCell.innerHTML = '<p class="adr"><span class="locality">' + list[y].city + '<br />' + list[y].state + ', ' + list[y].country + '</span></p>';
        }
        else
        {
            if(list[y].city != "" && list[y].state != "") locationCell.innerHTML = '<p class="adr"><span class="locality">'   + list[y].city + '</span>, <span class="region">' + list[y].state + '</span></p>';
            else if(list[y].city == "" && list[y].state != "") locationCell.innerHTML = '<p class="adr"><span class="region">' + list[y].state + '</span></p>';
            else if(list[y].city != "" && list[y].state == "") locationCell.innerHTML = '<p class="adr"><span class="locality">' + list[y].city + '</span></p>';
        }
        row.appendChild(locationCell);

        // details cell
        var detailsCell = document.createElement('td');
        var details = '<ul>';

        // add spaces around forward slashes in industry data
        list[y].industry = list[y].industry.replace('/'," / ");

        if(list[y].industry != "") details = details + '<li>' + list[y].industry + '</li>';
        if(list[y].cosize != "") details = details + '<li>' + list[y].cosize + '</li>';
        details = details + '</ul>';
        if( list[y].industry != "" || list[y].cosize != "" ) detailsCell.innerHTML = details;
        row.appendChild(detailsCell);

        attendeeTable.appendChild(row);
    }
    if(Number(count) == 0)
    {
        // show the no results row.
        row = document.createElement('tr');
        var errorCell = document.createElement('td');
        errorCell.colSpan = 4;
        errorCell.innerHTML = '<div class="noresults">Sorry there are no results for your filters.  Please refine the filters or <a href="#column-main" onclick="resetMap();">reset</a> the map.</div>';
        row.appendChild(errorCell);
        attendeeTable.appendChild(row);
    }
}

//Jim D. code - should be checked and cleaned

function showLoaderGraphic()
{
    var loaderGraphic = document.getElementById("busy");
    loaderGraphic.style.display = "block";
}

function hideLoaderGraphic()
{
    var loaderGraphic = document.getElementById("busy");
    loaderGraphic.style.display = "none";
}

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