var map = null;
var dragShape = null;
var baseLayer = null;
var editObject = null;
var myLayer = null;
var global_LL = null;
var global_dragShape_startLoc = null;
var j$ = jQuery.noConflict();
var editMode = false;
var agencyCollection = [];

//Ajax handler callbacks
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

//FIX FF3 wrong client click point
(function() {
    var mouseEvt;
    if (typeof document.createEvent !== 'undefined') {
        mouseEvt = document.createEvent('MouseEvents');
    }
    if (mouseEvt && mouseEvt.__proto__ && mouseEvt.__proto__.__defineGetter__) {
        mouseEvt.__proto__.__defineGetter__('pageX', function() {
            return this.clientX + window.pageXOffset;
        });
        mouseEvt.__proto__.__defineGetter__('pageY', function() {
            return this.clientY + window.pageYOffset;
        });
    }
})();

function MouseHandler(e) 
{ 
    if (e.eventName == "onmousedown" && e.elementID != null) 
    { 
        map.HideInfoBox();
        //find the right layer first!
        dragShape = map.GetShapeByID(e.elementID);
        if (dragShape != null) {
            global_dragShape_startLoc = dragShape.GetPoints();
        }
        return true;
    } 
    else if (e.eventName == "onmouseup") {
        if (dragShape != null) {
            
           // j$.facebox("<div><span>Do you really want to update this agent location?...  seriously?</span><div><a href='#' id='btnConfirmOK'>OK</a>&nbsp;|&nbsp;<a href='#' id='btnConfirmCancel'>or cancel...</a></div><div></div></div>");
           // j$("#facebox .footer").hide();


            if (confirm("Are you sure you want to update this location?"))
            {
            
                
                //j$("#btnConfirmOK").unbind().click(function() {
                //    j$.facebox.close();
                j$.ajax({
                    type: "POST",
                    url: "Maintenance.aspx/UpdateAgencyCoordinates",
                    data: "{'ID' : '" + j$("#agtID").val() + "', 'Lat' : " + global_LL.Latitude + ", 'Lon' : " + global_LL.Longitude + "}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(data, textStatus) {
                        //            j$.facebox("Agency Location updated successfully");
                        alert("The agency location was updated successfully.");
                        //global_LL = null;
                        //global_dragShape_startLoc = null;
                        //dragShape = null;
                    },
                    error: function(xhr, status, errorThrown) {
                        //            j$.facebox(xhr.responseText);
                        alert(errorThrown);
                        //global_LL = null;
                        //global_dragShape_startLoc = null;
                        //dragShape = null;
                    }
                });

		        global_LL = null;
            	global_dragShape_startLoc = null;
            	dragShape = null;	

                //});
            } else {
            //j$("#btnConfirmCancel").unbind().click(function() {
            //        j$.facebox.close();
                    dragShape.SetPoints(global_dragShape_startLoc);
                    global_LL = null;
                    global_dragShape_startLoc = null;
                    dragShape = null; 
            //    });
            }




        }
    }
    else if (e.eventName == "onmousemove" && dragShape != null) {
        map.HideInfoBox();
        var x = e.mapX; 
        var y = e.mapY; 
        pixel = new VEPixel(x, y); 
        var LL = map.PixelToLatLong(pixel);
        dragShape.SetPoints(LL);
        global_LL = LL;
        return true; // prevent the default action 
    } 
}

function EndRequestHandler(sender, args)
{
    if (typeof agencyCollection == "object" && agencyCollection != null && agencyCollection.length > 0)
    {
        for (var index = 0; index < agencyCollection.length; index++)
        {
            agencyCollection[index].OnMap = false;
        }
    }

    //set the map points
    setMapPoints(j$(".editAgt").parent().parent());
    setListFunctions(j$(".editAgt").parent().parent());

    // Loop through the agency collection and if it has not been put on the map yet, add the shape.
    if (typeof agencyCollection == "object" && agencyCollection != null && agencyCollection.length > 0)
    {
        for (var index = 0; index < agencyCollection.length; index++)
        {
            if (typeof agencyCollection[index].OnMap == "undefined" || agencyCollection[index].OnMap == false)
            {
                AddCollectionShapeToMap(agencyCollection[index]);
            }
        }
    }
    
    defaultControlConfig();
}

function setListFunctions(rows) {
    rows.each(function(i)
    {
        var AgyID = j$(this).find("td:eq(1) a").text();

        //zoom to Agency
        j$(this).find(".zoomAgt").bind("click", function()
        {
            for (var i = 0; i < map.GetShapeLayerCount(); i++)
            {
                var TargetLayer = map.GetShapeLayerByIndex(i);
                if (TargetLayer.GetTitle() == "DEFAULT")
                {
                    var id = parseInt(j$(this).parent().parent().find("span:first").html()) - 1;
                    var shape = TargetLayer.GetShapeByIndex(parseInt(id));
                    map.SetCenterAndZoom(new VELatLong(shape.Latitude, shape.Longitude), 16);
                    showBalloon(shape);
                    return false;
                }
            }
        });

        //edit Agency
        j$(this).find(".editAgt").bind("click", function()
        {

            for (var i = 0; i < map.GetShapeLayerCount(); i++)
            {
                var TargetLayer = map.GetShapeLayerByIndex(i);
                if (TargetLayer.GetTitle() == "DEFAULT")
                {
                    var id = parseInt(j$(this).parent().parent().find("span:first").html()) - 1;
                    var shape = TargetLayer.GetShapeByIndex(parseInt(id));
                    map.SetCenterAndZoom(new VELatLong(shape.Latitude, shape.Longitude), 16);
                    //showBalloon(shape);
                    //return false;
                }
            }
            j$.ajax({
                type: "POST",
                url: "Maintenance.aspx/GetAgencyProfile",
                data: "{'ID' : '" + AgyID + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data, textStatus)
                {
                    //alert(data.d);
                    editObject = data.d;
                    showAddEdit('Edit Agency Profile');
                },
                error: function(xhr, status, errorThrown)
                {
                    //j$.facebox(xhr.responseText);
                    alert(errorThrown);
                }
            });
            return true;
        });


        var agencyFromCollection = GetAgencyFromCollection(AgyID);

        if (agencyFromCollection != null)
        {
            AddCollectionShapeToMap(agencyFromCollection);

            var collectionItem = j$(this).find(".collection");
            collectionItem.parent().find(".inCollection").remove();
            collectionItem.parent().append("<span class='inCollection'>Added</span>");
            collectionItem.hide();
        }
        else
        {
            var collectionItem = j$(this).find(".collection");
            collectionItem.parent().find(".inCollection").remove();
            collectionItem.show();

            collectionItem.bind("click", function() {
                fnAddToCollection(parseInt(j$(this).parent().parent().find("span:first").html()), j$(this).parent().parent());
            });
        }
    });
}


function GetAgencyFromCollection(agencyID)
{
    agencyID = j$.trim(agencyID);
    var agency = null;
    
    if (agencyCollection != null && agencyCollection.length > 0)
    {
        for (var index = 0; index < agencyCollection.length; index++)
        {
            if (agencyCollection[index].ID == agencyID) 
            {
                agency = agencyCollection[index];
                break;
            }
        }
    }

    return agency;
}



function setMapPoints(rows) {
    ClearMap(baseLayer);
    baseLayer = new VEShapeLayer();
    baseLayer.SetTitle("DEFAULT");
    map.AddShapeLayer(baseLayer);
    rows.each(function(i) {
        var x = new VELatLong(parseFloat(j$(this).find("td:eq(7)").html()), parseFloat(j$(this).find("td:eq(8)").html()));
        var shape = new VEShape(VEShapeType.Pushpin, x);
        //shape.SetTitle(j$(this).find("td:eq(1)").html()); //trans_mrkr.png
        shape.SetCustomIcon("<div class='pinStyle NotActive'><div class='text'>" + (i + 1) + "</div></div>");
        shape.SetDescription("<div class='balloon'><div class='balloon_top'><div class='balloon_title'>Agency ID: " + j$(this).find("td:eq(1)").html() + "</div><div class='balloon_description'>Name: " + j$(this).find("td:eq(2)").html() + "<br/>Street: " + j$(this).find("td:eq(3)").html() + "<br/>City/State:  " + j$(this).find("td:eq(4)").html() + ", " + j$(this).find("td:eq(5)").html() + "<br />Precision: " + j$(this).find("td:eq(6)").html() + "</div></div><div class='balloon_bottom'>" + (GetAgencyFromCollection(j$(this).find("td:eq(1)").text()) != null ? "" : "<a href='#AddToCollection' onclick='fnAddToCollection(" + (i + 1) + ", j$(\"#tblAgency tr:eq(" + (i + 1) + ")\")); j$(this).remove();'>Add To My Collection</a>") + "</div></div>");
        shape.SetZIndex(100);
        baseLayer.AddShape(shape);
    });
    var rect = baseLayer.GetBoundingRectangle();
    map.SetMapView(rect);
}

function showBalloon(ob) {
    try {
        map.ShowInfoBox(ob);
    }
    catch (e) {
        //j$.facebox(e.description);
        alert(e.description);
    }
}


function AddCollectionShapeToMap(agencyObj)
{
    if (typeof baseLayer == "undefined" || baseLayer == null)
    {
        for (var i = 0; i < map.GetShapeLayerCount(); i++)
        {
            var TargetLayer = map.GetShapeLayerByIndex(i);
            if (TargetLayer.GetTitle() == "DEFAULT")
            {
                baseLayer = TargetLayer;
            }
        }
    }


    var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(agencyObj.Latitude, agencyObj.Longitude));    
    shape.SetCustomIcon("<div class='pinStyle Active'><div class='text'></div></div>");
    shape.SetDescription('<div class=\"balloon\"><div class=\"balloon_top\"><div class=\"balloon_title\">Agency ID: ' + agencyObj.ID + '</div><div class=\"balloon_description\">Name: ' + agencyObj.Name + '<br/>Street: ' + agencyObj.Street + '<br/>City/State:  ' + agencyObj.City + ', ' + agencyObj.StateCode + '<br />Precision: ' + agencyObj.Precision + '</div></div><div class=\"balloon_bottom\"></div></div>');
    shape.SetZIndex(101);
    baseLayer.AddShape(shape);

    agencyObj.OnMap = true;
}


function fnAddToCollection(idx, row)
{
    var agencyID = row.find("td:eq(1)").text();
    
    // Add the clicked agency to both the server-side (session) and client-side collections.
    j$.ajax({
        type: "POST",
        url: "Maintenance.aspx/AddAgencyToCollection",
        data: "{'ID' : '" + agencyID + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data, textStatus)
        {
            agencyCollection = data.d;

            var agencyFromCollection = GetAgencyFromCollection(agencyID);
            if (agencyFromCollection != null)
            {
                AddCollectionShapeToMap(agencyFromCollection);

                var collectionItem = row.find(".collection");
                collectionItem.parent().find(".inCollection").remove();
                collectionItem.parent().append("<span class='inCollection'>Added</span>");
                collectionItem.hide();
            }
        },
        error: function(xhr, status, errorThrown)
        {
            alert(errorThrown);
        }
    });
}

function ClearMap(layer) {
    if (layer != null) {
        map.DeleteShapeLayer(layer);
        layer = null;
    }
}

function search() {
    var objID = document.getElementById('searchbox');
    query = objID.value;
    document.location.href = "http://www.auto-owners.com/search_results.aspx?Search=" + query;
}


j$(document).ready(function()
{
    map = new VEMap('AOImap');
    map.LoadMap();

    // Load the agency collection array from Session.
    j$.ajax({
        type: "POST",
        url: "Maintenance.aspx/GetAgencyCollection",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data, textStatus)
        {
            agencyCollection = data.d;

            // Set the map points
            setMapPoints(j$(".editAgt").parent().parent());

            // Set the added status of the items in the agency table.
            setListFunctions(j$(".editAgt").parent().parent());

            // Loop through the agency collection and if it has not been put on the map yet, add the shape.
            for (var index = 0; index < agencyCollection.length; index++)
            {
                if (typeof agencyCollection[index].OnMap == "undefined" || agencyCollection[index].OnMap == false)
                {
                    AddCollectionShapeToMap(agencyCollection[index]);
                }
            }
        },
        error: function(xhr, status, errorThrown)
        {
            alert(errorThrown);
            setListFunctions(j$(".editAgt").parent().parent());
        }
    });

    j$("#setMapEdit").hide();
    defaultControlConfig();
    //set my default collection layer
    myLayer = new VEShapeLayer();
    map.AddShapeLayer(myLayer);
});






function defaultControlConfig() {
    j$("#addNew").unbind("click").click(function() {
        showAddEdit('Add New Agency');
        return false;
    });

    j$("#btnSave").unbind("click").click(function() {
        saveAgencyData();
        return false;
    });

    j$("#btnCancel").unbind("click").click(function() {
        hideAddEdit();
        editMode = false;
        j$("#editstatus").html("Inactive");
        j$("#setMapEdit").hide();
        return false;
    });

    j$("#btnDelete").unbind("click").click(function() {

        //j$.facebox("<div><span>Do you really want to delete this agency?...  seriously?</span><div><a href='#' id='btnConfirmOK'>OK</a>&nbsp;|&nbsp;<a href='#' id='btnConfirmCancel'>or cancel...</a></div><div></div></div>");
        //j$("#facebox .footer").hide();

    if (confirm("Are you sure you want to delete this agency?")) {
            //j$("#btnConfirmOK").unbind().click(function() {
            //    j$.facebox.close();
            j$.ajax({
                type: "POST",
                url: "Maintenance.aspx/DeleteAgencyProfile",
                data: "{'ID' : '" + j$("#agtID").val() + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data, textStatus) {
                    //j$.facebox("Agency Removed");
                    alert("The agency was successfully deleted.");
                    hideAddEdit();
                },
                error: function(xhr, status, errorThrown) {
                    alert(errorThrown);
                    //j$.facebox(xhr.responseText);
                }
            });
            // });
        }
        else {
            //j$("#btnConfirmCancel").unbind().click(function() {
                //j$.facebox.close();
                hideAddEdit();
            //});
        }
    });


    j$("#clearCollection").unbind("click").click(function()
    {
        // Clear the agency collection array from Session.
        j$.ajax({
            type: "POST",
            url: "Maintenance.aspx/ClearAgencyCollection",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data, textStatus)
            {
                agencyCollection = [];
                ClearMap(myLayer);
                setMapPoints(j$(".editAgt").parent().parent());
                setListFunctions(j$(".editAgt").parent().parent());
            },
            error: function(xhr, status, errorThrown)
            {
                alert(errorThrown);
            }
        });
    });


    j$("#setMapEdit").unbind("click").click(function(event) {
        event.preventDefault();

        if (editMode == true) {
            map.DetachEvent("onmousedown", MouseHandler);
            map.DetachEvent("onmouseup", MouseHandler);
            map.DetachEvent("onmousemove", MouseHandler);
            editMode = false;
            j$("#editstatus").html("Inactive");
        }
        else {
            map.AttachEvent("onmousedown", MouseHandler);
            map.AttachEvent("onmouseup", MouseHandler);
            map.AttachEvent("onmousemove", MouseHandler);
            editMode = true;
            j$("#editstatus").html("Active");
        }
    });

}

function saveAgencyData() {
    if (j$("h3.action-title").html() == "Add New Agency") {
        j$.ajax({
            type: "POST",
            url: "Maintenance.aspx/AddAgencyProfile",
            data: "{'ID' : '" + j$("#agtID").val() + "', 'Name' : '" + j$("#org").val() + "', 'Phone' : '" + j$("#phone").val() + "', 'email' : '" + j$("#email").val() + "', 'website' : '" + j$("#website").val() + "', 'Address' : '" + j$("#Address").val() + "', 'City' : '" + j$("#city").val() + "', 'State' : '" + j$("#state").val() + "', 'Zip' : '" + j$("#zip").val() + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data, textStatus) {
                //j$.facebox(data.d);
                alert(data.d);
                hideAddEdit();
            },
            error: function(xhr, status, errorThrown) {
                //j$.facebox(xhr.responseText);
                alert(errorThrown);
            }
        });
    } else {
        j$.ajax({
            type: "POST",
            url: "Maintenance.aspx/EditAgencyProfile",
            data: "{'ID' : '" + j$("#agtID").val() + "', 'Name' : '"+j$("#org").val()+"', 'Phone' : '"+j$("#phone").val()+"', 'email' : '"+j$("#email").val()+"', 'website' : '"+j$("#website").val()+"', 'Address' : '"+j$("#Address").val()+"', 'City' : '"+j$("#city").val()+"', 'State' : '"+j$("#state").val()+"', 'Zip' : '"+j$("#zip").val()+"'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data, textStatus) {
                //j$.facebox(data.d);
                alert(data.d);
                //showAddEdit('Edit Agency Profile');
                hideAddEdit();
                editMode = false;
                map.DetachEvent("onmousedown", MouseHandler);
                map.DetachEvent("onmouseup", MouseHandler);
                map.DetachEvent("onmousemove", MouseHandler);
                j$("#editstatus").html("Inactive");
                j$("#setMapEdit").hide();
            },
            error: function(xhr, status, errorThrown) {
            //j$.facebox(xhr.responseText);
            alert(errorThrown);
            }
        });
    }
}


function showAddEdit(txt) {
    j$("h3.action-title").html(txt);
    j$("#agent-list").fadeOut('fast', function() {
        j$("#addNewAgent").slideDown('slow', function() {
            if (editObject != null) {
                j$("#agtID").val(editObject.ID);
                j$("#org").val(editObject.Name);
                j$("#phone").val(editObject.Phone);
                j$("#email").val(editObject.Email);
                j$("#website").val(editObject.Website);
                j$("#Address").val(editObject.Street);
                j$("#city").val(editObject.City);
                j$("#state").val(editObject.StateCode);
                j$("#zip").val(editObject.Zip);
                j$("#btnDelete").show();
                j$("#setMapEdit").show();

            }
            else {
                j$("#btnDelete").hide();
                j$("#setMapEdit").hide();
                j$("#agtID").val("");
                j$("#org").val("");
                j$("#phone").val("");
                j$("#email").val("");
                j$("#website").val("");
                j$("#Address").val("");
                j$("#city").val("");
                j$("#state").val("");
                j$("#zip").val("");
            }
        });
    });
}

function hideAddEdit() {
    j$("#addNewAgent > input").val("");
    j$("#addNewAgent").slideUp('slow', function() {
        j$("#agent-list").fadeIn('slow');
        editObject = null;
    });
}
