var secondLine;
var globalMap;
var popupTimer;
var popupInterval;
var John1010path1 = "http://www.1010Challenge.org/StartATeam"; 
var John1010path2 = "http://www.1010Challenge.org/FindATeam"; 

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }

    return 0;
}

function getSegment() {
    if (jQuery('#currentSegment').text() != "") {
        return jQuery('#currentSegment').html();
    }
    else if (jQuery("input#segID").length > 0 && jQuery("input#segID").val() != "") {
        return jQuery("input#segID").val();
    }
    else {
        return getQueryVariable("segment");
    }
}

function makeMap(filtering, refresher, newseg) {

    var seg;
    if (newseg == null) {
        seg = getSegment();
    } else {
        seg = newseg;
    }

    //clear elements of the previous map
    jQuery('#badLinks').empty();
    jQuery('div#container span').remove();
    jQuery('#loadingstatus').fadeIn();
    jQuery('#results').css("height", "549px");
    jQuery('#currentSegment').html(getSegment());
    clearTimeouts();

    //this function decides which customfield to display depending on which map is loading
    defineSecondLine();

    //load the map
    globalMap = jQuery('#map').mapBySeg({
        serverpath: "http://master.umc.org/spheremaps/",
        segment: seg,
        lastname: "",
        firstname: "",
        city: "",
        state: "",
        zip: "",
        refresh: refresher,
        runnow: true,
        usetemplate: true,
        templatedata: {
            line1: "<div id='contactDetails'><h3>[FirstName] [LastName]</h3>",
            line2: secondLine + "<br />" + "<hr />", //make sure to use xhtml <br /> rather than <br>
            line3: " <a href=" + "'" + John1010path1 + "'" + ">" + "Start a Team" + "</a>" + " | " + " <a href=" + "'" + John1010path2 + "'" + ">" + "Join a Team" + "</a>"
        },
        userightcoltemplate: true,
        rightcoltemplatedata: {
            line1: "<div class='contactlist'>",
            line2: "[FirstName] [LastName]<br />",
            //line3: secondLine + "<br />", //make sure to use xhtml <br /> rather than <br>
            line4: "[PrimaryAddressCity], [primaryStateString] </div>"
        },
        bubbleheight: 50,
        bubblewidth: 220,
        autobubblepopup: true,
        autobubblepopupinterval: 10,
        zoomlevel: 4,
        maxzoomlevel: 9,
        showrightcol: true,
        filter: filtering,
        debugMode: false,     //set to true to see "unmappable entry" controller
        waitToBubble: 25      //amount of time in seconds to wait to start bubbling again after a click
    });

}

function resetMap() {
    jQuery("input#lastname").val("");
    jQuery("input#firstname").val("");
    jQuery("input#city").val("");
    jQuery("input#state").val("");
    makeMap(false, null);

}

function newSeg(seg) {
    //clear old mappings
    jQuery('#currentSegment').html(seg);
    jQuery('#badLinks').empty();
    jQuery('div#container span').remove();
    jQuery('#loadingstatus').fadeIn();
    clearReminders();
    clearTimeouts();
    defineSecondLine();

    globalMap = makeMap(false, null, seg);

}

function showReminder(contents) {
    var cacheDiv = "<div class=\"clear\"></div>";
    cacheDiv += "<div class=\"bottomReminder\">" + contents + "<img src=\"http://master.umc.org/spheremaps/images/delete.gif\" class=\"closeReminder\" /></div>";
    jQuery("#output").after(cacheDiv);
    jQuery(".bottomReminder").slideDown("slow");
    
}

function clearReminders() {
    jQuery(".bottomReminder").slideUp("fast", function() {
        jQuery(".bottomReminder").remove();
    });

}

function loadSegments() {
    jQuery('#loadingstatus').show();
    jQuery('#loadingstatus')[0].innerHTML = "<div>Loading Segments ...</div><div><img src='http://master.umc.org/spheremaps/images/ajax-loader.gif' /></div>";
    jQuery("#appContainer").prepend("<div class=\"overlay\"></div><div class=\"dialog\"><div class=\"closeDialog\"><img src=\"http://master.umc.org/spheremaps/images/delete.gif\" /></div><div id=\"loader\">Querying database for segments...<br />Note: This can take up to a few minutes<img src=\"http://master.umc.org/spheremaps/images/ajax-loader.gif\" class=\"imgLoader\" /></div><div id=\"holder\"></div></div>");

    jQuery.getJSON("http://master.umc.org/spheremaps/segFinder.aspx?callback=?", function(data) {

        jQuery("#holder").before("<div id=\"controller\"><div id=\"segHeader\">Segment Finder</div><input type=\"text\" size=\"30\" id=\"segName\" readonly=\"readonly\" /><input type=\"text\" size=\"6\" id=\"segID\" readonly=\"readonly\" /><br /><div id=\"segNote\">Caution: Larger segments make take some time to import</div></div>");
        jQuery.each(data.cat.segment, function(index, item) {
            //alert(item.@Name + " & " + item.@id + " & " + item.@Level);
            jQuery("#holder").append("<div class='segment level"+item.Level+"' id='" + item.id + "'>" + item.Name + "</div>");
        });
        jQuery("#holder").after("<center><button id=\"choose\">Submit</button></center>");



        //styles for the segment finder should be loaded HERE
        var welcome = "<b>Segments loaded</b>. Please choose a map from the menu in the bottom right corner.";
        
        showReminder(welcome);
        jQuery('#loadingstatus').fadeOut();
        jQuery("#loader").remove();
        jQuery(".closeDialog").live("click", function() {
            jQuery(".overlay").hide();
            jQuery(".dialog").hide();
        });
        jQuery("div.segment").css("cursor", "pointer");
        jQuery("div.segment").live("click", function() {
            var isSelected = jQuery(this).hasClass("selected");
            jQuery(".selected").removeClass("selected");
            jQuery(this).toggleClass("selected", !isSelected);

            jQuery("input#segName").val(jQuery(this).text());
            jQuery("input#segID").val(jQuery(this).attr("id"));
            jQuery("button#choose").css("background-color", "#EAFF8B");

        });

        toggleDialog();
    });
       
    

}


function clearTimeouts() {
    //alert(popupTimer);
    window.clearInterval(popupTimer);

}

function toggleDialog() {
    jQuery(".overlay").toggle();
    jQuery(".dialog").toggle();
}

function defineSecondLine() {
    //define custom fields for particular maps
    if (getSegment() == "265368" || getSegment() == "265369") {
        //board members & pwj coords
        secondLine = "[1124157]";
    } else if (getSegment() == "275135") {
        //health care
        secondLine = " [4908948] <br/>Date: [4908945] <br/>Location: [4908946] <br/>Promotional Info: [4908947] "; 
    } else if (getSegment() == "275967") {
        //health care All John 1010 Participants
        secondLine = " [PrimaryAddressCity], [primaryStateString]"; 
    } else if (getSegment() == "265367") {
        //death penalty
        secondLine = "How I plan to use this resource: <br/>[4813377]";
    } else {
        secondLine = "PrimaryAddressLine1";
    }
}


jQuery.noConflict()(function() {

    // Loaded on document ready
    jQuery.getScript("http://master.umc.org/spheremaps/jquery.jsonp-1.0.4.min.js");
    
    defineSecondLine();

    //handle first time loads
    if (getQueryVariable("segment") != 0) {
        makeMap(false, null);
    }
    else {
        loadSegments();
    }

    //enter behavior on filter menu
    jQuery("input#lastname, input#firstname, input#state, input#city").keyup(function(e) {
        if (e.keyCode == 13) {
            makeMap(true, null);
        }
    });

    //link behaviors
    jQuery(".closeNotif").live("click", function() {
        jQuery("#badLinks").animate({ height: "0px" }, function() { jQuery("#badLinks").hide(); });
        jQuery("#results").css("height", "402px");
    });

    jQuery(".toggle").live("click", function() {
        jQuery(".bad").toggle(500);
    });

    jQuery(".closeReminder").live("click", function() {
        var image = jQuery(this);
        image.parent().slideUp("1000", function() {
            image.parent().remove();
        });
    });

    jQuery(".overlay").live("click", function() {
        toggleDialog();
    });

    jQuery("button#choose").live("click", function() {
        var id = jQuery("input#segID").val();
        toggleDialog();
        setTimeout("newSeg(" + id + ")", 600);

    });

    jQuery(".finderlink").click(function() {
        if (jQuery(".overlay").length > 0 && jQuery(".dialog").length > 0) {
            toggleDialog();
        } else {
            loadSegments();
        }
    });

    //hover actions for the filter menu
    //jQuery("#filter").hover(function() {
    //    //hidden, prepare to show
    //    jQuery("#filter").animate({
    //        "top": "405px"
    //    }, "normal");
    //}, function() {
    //    //hover out
    //    jQuery("#filter").animate({
    //        top: "575px"
    //    }, "normal", function() {
    //        jQuery("#filter").stop(true);
    //    });
    //});
    
});

