﻿// ------------------------------------------------------
// Global Variables
// ------------------------------------------------------

//constants
var IMAGE_PIN_PATH = "/Resources/Images/Pins/";

//view enums
var VIEW = { Home: 0, LocationType: 1, Location: 2 };
//pins
var pins = [ new PinColour("Black","black.gif"), new PinColour("Blue","blue.gif"), new PinColour("Green","green.gif"),new PinColour("Grey","grey.gif"),new PinColour("Red","red.gif")];

var currentView = VIEW.Home;
var editingType;
var editingLocation;
var g_LocMap;
var errors = new Array();
var isOKClicked = false;

// ------------------------------------------------------
// Methods
// ------------------------------------------------------

function Initialise()
{
    // Restore if we have a json value passed.
    // Create new if no json value passed.
    g_LocMap = new LocationMap();
    
    if ((window.dialogArguments != null) && (window.dialogArguments[0] != ""))
    {
        var temp = window.dialogArguments[0].evalJSON();
        g_LocMap.MapImageUrl = temp.MapImageUrl;
        document.getElementById("imgMap").src = temp.MapImageUrl;
        $('txtImagePath').value = temp.MapImageUrl;
        g_LocMap.LocationTypes = new Array();
        temp.LocationTypes.each(function(item, index)
        {
            g_LocMap.LocationTypes[index] = new LocationType();
            g_LocMap.LocationTypes[index].Name = item.Name;
            g_LocMap.LocationTypes[index].Description = item.Description;
            g_LocMap.LocationTypes[index].PinColour = item.PinColour;
            g_LocMap.LocationTypes[index].Locations = new Array();

            if (item.Locations)
            {
                item.Locations.each(function(item, index1)
                {
                    g_LocMap.LocationTypes[index].Locations[index1] = new Location();
                    g_LocMap.LocationTypes[index].Locations[index1].Name = item.Name;
                    g_LocMap.LocationTypes[index].Locations[index1].Top = item.Top;
                    g_LocMap.LocationTypes[index].Locations[index1].Left = item.Left;
                    g_LocMap.LocationTypes[index].Locations[index1].Manager = item.Manager;
                    g_LocMap.LocationTypes[index].Locations[index1].Telephone = item.Telephone;
                    g_LocMap.LocationTypes[index].Locations[index1].Switchboard = item.Switchboard;
                    g_LocMap.LocationTypes[index].Locations[index1].AddressLine1 = item.AddressLine1;
                    g_LocMap.LocationTypes[index].Locations[index1].AddressLine2 = item.AddressLine2;
                    g_LocMap.LocationTypes[index].Locations[index1].AddressLine3 = item.AddressLine3;
                    g_LocMap.LocationTypes[index].Locations[index1].County = item.County;
                    g_LocMap.LocationTypes[index].Locations[index1].Postcode = item.Postcode;
                });
            }
        });
        g_LocMap.LocationTypes = g_LocMap.SortLocationTypesByName();
    }
    SwitchView("addtype");
}

function DoOk()
{
    isOKClicked = true;
    // Generate json string from location map
    if (g_LocMap)
    {
        arrRet = new Array();
        arrRet[0] = Object.toJSON(g_LocMap);
        returnValue = arrRet;
    }
    window.close();
}

function DoCancel()
{
    if (CheckModified() == true)
    {
        if (confirm("The location map has been modified, are you sure you want to cancel without saving?") == true)
        {
            window.close();
        }
    }
    else
    {
        window.close();
    }
}

function DoBack()
{
    SwitchView(GetPreviousView());
}

function DoUnload()
{
    if (CheckModified() == true && isOKClicked == false)
    {
        return "The location map has been modified, are you sure you want to cancel without saving?";
    }
    else
    {
        return null;
    }
}

function CheckModified()
{
    return g_LocMap.IsModified() == true || (editingType && editingType.IsModified() == true) || (editingLocation && editingLocation.IsModified() == true);
}

function DoAddLocationType(sender)
{
    CleanValidationSummaries();
    if (TriggerValidation("rfvTypeName", true) == true && TriggerValidation("cvTypeName", true) == true)
    {
        g_LocMap.AddLocationType(new LocationType(document.getElementById("txtLocationTypeName").value));
        document.getElementById("txtLocationTypeName").value = "";
    }

    RenderLocationTypes();
    return false;
}

function DoDeleteLocation(sender, name)
{
    if (confirm("Are you sure you want to remove this location?"))
    {
        var index = editingType.RemoveLocation(name);
        RenderLocations();
    }
}

function DoEditLocation(sender, name)
{
    CleanValidationSummaries();

    editingLocation = editingType.FindLocationByName(name);
    SwitchView(VIEW.Location);
}

function DoChangeLocationType(sender)
{
    CleanValidationSummaries();
    if (TriggerValidation("rfvEditType", true) == true && TriggerValidation("cvEditType", true) == true)
    {
        editingType.Name = document.getElementById("txtEditType").value;
        editingType.Description = document.getElementById("txtEditTypeDescription").value.replace(/\r\n/gi, "<br/>");
        
        var pin = GetSelectedPinColour();
        if (pin)
        {
            editingType.SetPinColour(pin.Text, pin.Value);
        }
        
        editingType.MarkModified();
        ShowMessage("The type name has been successfully changed");
    }

    return false;
}

function DoAddLocation(sender)
{
    CleanValidationSummaries();
    if (TriggerValidation("rfvAddLocation", true) == true && TriggerValidation("cvAddLocation", true) == true)
    {
        editingType.AddLocation(new Location(document.getElementById("txtLocationName").value));
        document.getElementById("txtLocationName").value = "";
    }

    RenderLocations();
    return false;
}

function DoLocationChange(sender, eventArgs)
{
    CleanValidationSummaries();

    if (TriggerValidation("rfvLocName", true) == true && TriggerValidation("cvLocName", true) == true)
    {
        if (!document.getElementById("txtLocTop").value.blank() && !document.getElementById("txtLocLeft").value.blank())
        {
            if (TriggerMultipleValidations("comLocTop",
                                            "comLocLeft",
                                            "rfvLocManager",
                                            "rfvLocTele",
                                            "rfvLocSwitch",
                                            "rfvLocAddr1",
                                            "rfvLocAddr2",
                                            "rfvLocAddr3",
                                            "rfvLocCounty",
                                            "rfvLocPost") == true)
            {
                UpdateLocation();
            }
        }
        else
        {
            UpdateLocation();
        }
    }

    return false;
}

function DoDeleteLocationType(sender, type)
{
    if (confirm("Are you sure you want to remove this location type?"))
    {
        var index = g_LocMap.RemoveLocationType(type);
        RenderLocationTypes();
    }
}

function DoEditLocationType(sender, type)
{
    CleanValidationSummaries();
    if (TriggerValidation("rfvImg", true) == true)
    {
        editingType = g_LocMap.FindLocationTypeByName(type);
        SwitchView(VIEW.LocationType);
    }
}

function GetSelectedPinColour()
{
    var pin = null;
    var select = document.getElementById("ddlColour");
    var index = select.selectedIndex;

    if (index >= 0)
    {
        pin = new PinColour(select.options[index].text, select.options[index].value);
    }

    return pin;
}

function UpdateLocation()
{
    if (editingLocation)
    {
        editingLocation.Name = document.getElementById("txtLocName").value;
        editingLocation.Top = document.getElementById("txtLocTop").value;
        editingLocation.Left = document.getElementById("txtLocLeft").value;
        editingLocation.Manager = document.getElementById("txtLocManager").value;
        editingLocation.Telephone = document.getElementById("txtLocTele").value;
        editingLocation.Switchboard = document.getElementById("txtLocSwitch").value;
        editingLocation.AddressLine1 = document.getElementById("txtLocAddr1").value;
        editingLocation.AddressLine2 = document.getElementById("txtLocAddr2").value;
        editingLocation.AddressLine3 = document.getElementById("txtLocAddr3").value;
        editingLocation.County = document.getElementById("txtLocCounty").value;
        editingLocation.Postcode = document.getElementById("txtLocPost").value;

        $("spanEditLoc").innerText = editingLocation.Name;
        $("spanEditLoc").textContent = editingLocation.Name;
        ShowMessage("Location has been saved successfully");
        editingLocation.MarkModified();
    }
}

function TriggerValidation(validatorID, cleanOthers)
{
    if (cleanOthers == true)
    {
        CleanValidators();
    }
    
    ValidatorValidate(document.getElementById(validatorID));
    var result = $(validatorID).isvalid;
    if (result == false)
    {
        errors.push($(validatorID).errormessage);
        UpdateValidationSummary();
    }
    HideMessage();
    return result;
}

function TriggerMultipleValidations()
{
    var result = true;

    for (var i = 0; i < arguments.length; i++)
    {
        if (TriggerValidation(arguments[i], false) == false)
        {
            result = false;
        }
    }

    return result;
}

function ValidateDuplicatedLocationType(sender, args)
{
    if (args.Value && !args.Value.blank())
    {
        if ((!editingType && g_LocMap.FindLocationTypeByName(args.Value) != null) || (editingType && editingType.Name != args.Value && g_LocMap.FindLocationTypeByName(args.Value) != null))
        {
            args.IsValid = false;
        }
    }
    else
    {
        args.IsValid = true;
    }
}

function ValidateDuplicatedLocation(sender, args)
{
    if (args.Value && !args.Value.blank())
    {
        if ((!editingLocation && editingType.FindLocationByName(args.Value) != null) || (editingLocation && editingLocation.Name != args.Value && editingType.FindLocationByName(args.Value) != null))
        {
            args.IsValid = false;
        }
    }
    else
    {
        args.IsValid = true;
    }
}

function RenderLocationTypes()
{
    if (g_LocMap.LocationTypes)
    {
        if (g_LocMap.LocationTypes.length == 0)
        {
            $("divTypes").hide();
            $("divEmpty").show();
        }
        else
        {
            $("divEmpty").hide();
            $("divTypes").show();
        }
        
        var tbody = $("tblTypes").childElements()[0];
        //clean the table first

        var trs = tbody.childElements();
        for (var i = 1; i < trs.length; i++)
        {
            trs[i].remove();
        }

        g_LocMap.LocationTypes.each(function(item, index)
        {
            var tr = document.createElement("tr");
            var tdName = $(document.createElement("td"));
            tdName.addClassName("tdLocationTypeName");
            tdName.innerText = item.Name;
            tdName.textContent = item.Name;

            var tdEdit = $(document.createElement("td"));
            tdEdit.addClassName("tdLocationTypeActions");
            var lnkEdit = document.createElement("a");
            lnkEdit.innerHTML = "<img src=\"/App_Themes/Default/Images/Tools/Edit.gif\" />";
            lnkEdit.title = "Edit " + item.Name;
            lnkEdit.href = String.format("javascript:DoEditLocationType(this, '{0}');", item.Name);
            tdEdit.appendChild(lnkEdit);

            var tdDel = $(document.createElement("td"));
            tdDel.addClassName("tdLocationTypeActions");
            var lnkDelete = $(document.createElement("a"));
            lnkDelete.innerHTML = "<img src=\"/App_Themes/Default/Images/Tools/Delete.gif\" />";
            lnkDelete.title = "Delete " + item.Name;
            lnkDelete.href= String.format("javascript:DoDeleteLocationType(this,'{0}');", item.Name);
            tdDel.appendChild(lnkDelete);

            tr.appendChild(tdName);
            tr.appendChild(tdEdit);
            tr.appendChild(tdDel);

            tbody.appendChild(tr);
        });
    }
}

function RenderLocations()
{
    if (editingType && editingType.Locations)
    {
        if (editingType.Locations.length == 0)
        {
            $("divLocations").hide();
            $("divEmptyLocations").show();
        }
        else
        {
            $("divEmptyLocations").hide();
            $("divLocations").show();

            var tbody = $("tblLocations").childElements()[0];
            //clean the table first

            var trs = tbody.childElements();
            for (var i = 1; i < trs.length; i++)
            {
                trs[i].remove();
            }

            editingType.Locations.each(function(item, index)
            {
                var tr = $(document.createElement("tr"));
                var tdName = $(document.createElement("td"));
                tdName.addClassName("tdLocationTypeName");
                tdName.innerText = item.Name;
                tdName.textContent = item.Name;

                var tdEdit = $(document.createElement("td"));
                tdEdit.addClassName("tdLocationTypeActions");
                var lnkEdit = document.createElement("a");
                lnkEdit.innerHTML = "<img src=\"/App_Themes/Default/Images/Tools/Edit.gif\" />";
                lnkEdit.title = "Edit " + item.Name;
                lnkEdit.href = String.format("javascript:DoEditLocation(this, '{0}');", item.Name);
                tdEdit.appendChild(lnkEdit);

                var tdDel = $(document.createElement("td"));
                tdDel.addClassName("tdLocationTypeActions");
                var lnkDelete = $(document.createElement("a"));
                lnkDelete.innerHTML = "<img src=\"/App_Themes/Default/Images/Tools/Delete.gif\" />";
                lnkDelete.title = "Delete " + item.Name;
                lnkDelete.href = String.format("javascript:DoDeleteLocation(this,'{0}');", item.Name);
                tdDel.appendChild(lnkDelete);

                tr.appendChild(tdName);
                tr.appendChild(tdEdit);
                tr.appendChild(tdDel);

                tbody.appendChild(tr);
            });
        }
    }
}

function SwitchView(view)
{
    HideMessage();
    CleanValidationSummaries();
    CleanValidators();
    switch (view)
    {
        case VIEW.Home:
        default:
            {
                CleanInputsValue("txtLocationTypeName");
                $("AddType").show();
                $("editLocation").hide();
                $("spanBack").hide();
                RenderLocationTypes();

                $("AddType").show();
                $("divLocation").hide();
                $("editLocation").hide();

                $("spanSave").show();
                $("spanCancel").show();
            }
            break;
        case VIEW.LocationType:
            {
                CleanInputsValue("txtLocationName");
                if (editingType)
                {
                    $("spanTitle").innerText = editingType.Name;
                    $("spanTitle").textContent = editingType.Name;
                    $("txtEditType").value = editingType.Name;
                    $("txtEditTypeDescription").value = editingType.Description.replace(/<br\/>/gi,"\r\n");

                    //clear all options prior to populate
                    document.getElementById("ddlColour").options.length = 0;
                    //populate colours
                    pins.each(function(item, index)
                    {
                        var optn = $(document.createElement("OPTION"));
                        optn.text = item.Text;
                        optn.value = item.Value;

                        if (index == 0)
                        {
                            optn.defaultSelected = true;
                        }

                        if (editingType.PinColour != null && editingType.PinColour.Value == optn.value)
                        {
                            optn.selected = true;
                        }

                        document.getElementById("ddlColour").options.add(optn);
                    });

                    $("spanBack").show();
                    RenderLocations();
                }
                $("editLocation").show();
                $("AddType").hide();
                $("divLocation").hide();

                $("spanSave").hide();
                $("spanCancel").hide();
            }
            break;
        case VIEW.Location:
            {
                //Set the map image
                $("imgMap").src = g_LocMap.MapImageUrl;
                
                CleanInputsValue("txtLocTop", "txtLocLeft", "txtLocManager", "txtLocTele", "txtLocSwitch", "txtLocAddr1", "txtLocAddr2", "txtLocAddr3", "txtLocCounty", "txtLocPost");
                if (editingType && editingLocation)
                {
                    $("spanLocType").innerText = editingType.Name;
                    $("spanLocType").textContent = editingType.Name;

                    $("spanEditLoc").innerText = editingLocation.Name;
                    $("spanEditLoc").textContent = editingLocation.Name;
                    $("txtLocName").value = editingLocation.Name;

                    //init pin
                    $("imgPin").writeAttribute("src", IMAGE_PIN_PATH + editingType.PinColour.Value);

                    //load pin
                    PushMapPin();

                    if (editingLocation.Top && !editingLocation.Top.toString().blank())
                    {
                        document.getElementById("txtLocTop").value = editingLocation.Top;
                    }

                    if (editingLocation.Left && !editingLocation.Left.toString().blank())
                    {
                        document.getElementById("txtLocLeft").value = editingLocation.Left;
                    }

                    if (editingLocation.Manager && !editingLocation.Manager.toString().blank())
                    {
                        document.getElementById("txtLocManager").value = editingLocation.Manager;
                    }

                    if (editingLocation.Telephone && !editingLocation.Telephone.toString().blank())
                    {
                        document.getElementById("txtLocTele").value = editingLocation.Telephone;
                    }

                    if (editingLocation.Switchboard && !editingLocation.Switchboard.toString().blank())
                    {
                        document.getElementById("txtLocSwitch").value = editingLocation.Switchboard;
                    }

                    if (editingLocation.AddressLine1 && !editingLocation.AddressLine1.toString().blank())
                    {
                        document.getElementById("txtLocAddr1").value = editingLocation.AddressLine1;
                    }

                    if (editingLocation.AddressLine2 && !editingLocation.AddressLine2.toString().blank())
                    {
                        document.getElementById("txtLocAddr2").value = editingLocation.AddressLine2;
                    }

                    if (editingLocation.AddressLine3 && !editingLocation.AddressLine3.toString().blank())
                    {
                        document.getElementById("txtLocAddr3").value = editingLocation.AddressLine3;
                    }

                    if (editingLocation.County && !editingLocation.County.toString().blank())
                    {
                        document.getElementById("txtLocCounty").value = editingLocation.County;
                    }

                    if (editingLocation.Postcode && !editingLocation.Postcode.toString().blank())
                    {
                        document.getElementById("txtLocPost").value = editingLocation.Postcode;
                    }

                    $("spanBack").show();
                }
                $("divLocation").show();
                $("editLocation").hide();
                $("AddType").hide();
                //this line will fail if you call before the page initialization completed
                ScrollPinIntoView();

                $("spanSave").hide();
                $("spanCancel").hide();
            }
            break;
    }
    currentView = view;
}

function CleanInputsValue()
{
    for (var i = 0; i < arguments.length; i++)
    {
        var input = document.getElementById(arguments[i]);

        if (input)
        {
            input.value = "";
        }
    }
}

function GetNextView()
{
    switch (currentView)
    {
        default:
            {
                return VIEW.Home;
            } break;
        case VIEW.Home:
            {
                return VIEW.LocationType;
            } break;
        case VIEW.LocationType:
            {
                return VIEW.Location;
            }
            break;
    }
}

function GetPreviousView()
{
    switch (currentView)
    {
        default:
        case VIEW.Home:
        case VIEW.LocationType:
            {
                return VIEW.Home;
            } break;
        case VIEW.Location:
            {
                return VIEW.LocationType;
            } break;
    }
}

function UpdateValidationSummary()
{
    var sum = $("summary");
    ResetValidationSummary();
    sum.innerHTML = errors.join("<br/>");
    sum.show();
}

function CleanValidationSummaries()
{
    errors = new Array();
    ResetValidationSummary();
}

function ResetValidationSummary()
{
    var sum = $("summary");
    sum.innerHTML = "";
    sum.hide();
}

function CleanValidators()
{
    for (var i = 0; i < Page_Validators.length; i++)
    {
        Page_Validators[i].isvalid = true;
        ValidatorUpdateDisplay(Page_Validators[i]);
    }
}

function ShowMessage(message)
{
    var divMessage = $("divMessage");

    if (divMessage)
    {
        divMessage.innerHTML = message;
        divMessage.show();
    }
}

function HideMessage()
{
    var divMessage = $("divMessage");

    if (divMessage)
    {
        divMessage.innerHTML = "";
        divMessage.hide();
    }
}

function OnMapClicked(event)
{
    var imgPosition = GetCoordinates(event);

    document.getElementById("txtLocTop").value = imgPosition.top;
    document.getElementById("txtLocLeft").value = imgPosition.left;
    PushMapPin(event);
}

function PushMapPin(event)
{
    if (event || ((editingLocation.Top && editingLocation.Left) && (editingLocation.Top >= 0 && editingLocation.Left >= 0)))
    {
        var pin;
        if (event)
        {
            pin = GetCoordinates(event);
        }
        else
        {
            pin = { top: editingLocation.Top, left: editingLocation.Left };
        }
        
        var imgPin = document.getElementById("imgPin");
        var imgMap = document.getElementById("imgMap");
        var pinXAdjusted = pin.left - 4;
        var pinYAdjusted = pin.top - imgPin.height;
        var pinX = pinXAdjusted;

//        if (pin.left < imgPin.width)
//        {
//            pinX = 0;
//        }
//        else if ((imgMap.width - pin.left) < imgPin.width)
//        {
//            pinX = imgMap.width - imgPin.width;
//        }

        var pinY = pinYAdjusted;

//        if (pin.top < imgPin.height)
//        {
//            pinY = 0;
//        }
//        else if ((imgMap.height - pin.top) < imgPin.height)
//        {
//            pinY = imgMap.height - imgPin.height;
        //        }

        var divPin = $("divPin");
        divPin.style.left = pinX + "px";
        divPin.style.top = pinY + "px";
        divPin.show();
    }
    else 
    {
        $("divPin").hide();
    }
}

// ------------------------------------------------------
// if scrollbar appears scroll and a pin was set, scroll the pin into view
// ------------------------------------------------------
function ScrollPinIntoView()
{
    var divPin = $("divPin");
    var divMapImg = $("divMapImg");
    //reset scrollbar
    divMapImg.scrollTop = 0;
    divMapImg.scrollLeft = 0;
    
    //if the pin has set, we scroll it into view so user will not need to scroll it
    if (divPin.visible())
    {
        divPin.scrollIntoView(true);
    }
}

// ------------------------------------------------------
// event: the mouse click event
// returns the relative position(x and y) within the map image
// ------------------------------------------------------
function GetCoordinates(event)
{
    var imgPosition = { top: -1, left: -1 };
    
    //if scrollbar shows, get the scrolling amount for x and y 
    var scrollX = document.getElementById("divMapImg").scrollLeft;
    var scrollY = document.getElementById("divMapImg").scrollTop;
    
    //gets the relative position of clicked point respect to the image container in x and y regardless scrolling x and y
    var offsetX = event.offsetX ? (event.offsetX) : event.pageX - document.getElementById("divMapImg").offsetLeft;
    var offsetY = event.offsetY ? (event.offsetY) : event.pageY - document.getElementById("divMapImg").offsetTop;

    //calculate the actual x and y of clicked point, taken scrolling amount into account
    
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");
    if (msie > 0)
    {
        imgPosition.left = offsetX;  //- scrollX;
        imgPosition.top = offsetY;  //- scrollY;
    }
    else
    {
        imgPosition.left = offsetX + scrollX;
        imgPosition.top = offsetY + scrollY;
    }
    
    return imgPosition;
}

// ------------------------------------------------------
// text: formated string
// an equivalence to string.format in C#
// ------------------------------------------------------
String.format = function( text )
{
    //check if there are two arguments in the arguments list
    if ( arguments.length <= 1 )
    {
        //if there are not 2 or more arguments there’s nothing to replace
        //just return the original text
        return text;
    }

    //decrement to move to the second argument in the array
    var tokenCount = arguments.length - 2;

    for( var token = 0; token <= tokenCount; token++ )
    {
        //iterate through the tokens and replace their placeholders from the original text in order
        text = text.replace( new RegExp( "\\{" + token + "\\}", "gi" ),arguments[ token + 1 ] );
    }
    return text;
};

//-------------------------------------------------------
//These methods are used to provide the front-end
//location map functionlaity for the user
//-------------------------------------------------------
function InitializeLocationMap(clientIdArray)
{
    ConfigureLocationMap(true, clientIdArray);
}

function ConfigureLocationMap(firstLoad, clientIdArray)
{
    hdnLocationMapJSON = document.getElementById(clientIdArray[0]);
    divLocationMapCon = document.getElementById(clientIdArray[1]);
    ddlLocationTypes = document.getElementById(clientIdArray[2]);

    locationMap = hdnLocationMapJSON.value.evalJSON();

    //Remove all location map pins
    if (divLocationMapCon.hasChildNodes())
    {
        for (i = 0; i < divLocationMapCon.childNodes.length; i++)
        {
            if (divLocationMapCon.childNodes[i].tagName == "IMG")
            {
                divLocationMapCon.removeChild(divLocationMapCon.childNodes[i]);
                i--;
            }
        }
    }

    imgLocationMap = document.createElement("img");
    imgLocationMap.src = locationMap.MapImageUrl;
    divLocationMapCon.appendChild(imgLocationMap);

    //Determine whether this is the first page load - need to show the initial state
    if (firstLoad)
    {
        //Populate drop down list
        locationMap.LocationTypes.each(function(item, index)
        {
            ddlLocationTypes.options[index + 1] = new Option(item.Name, item.Name);
            colour = item.PinColour.Value;
            item.Locations.each(function(item, index)
            {
                DrawMapPin(clientIdArray, item, colour);
            });
        });
    }
    else
    {
        //Filter the pins display based on the drop down value
        locationMap.LocationTypes.each(function(item, index)
        {
            if (item.Name == ddlLocationTypes.options[ddlLocationTypes.selectedIndex].value || ddlLocationTypes.options[ddlLocationTypes.selectedIndex].value == "All")
            {
                colour = item.PinColour.Value;
                item.Locations.each(function(item, index)
                {
                    DrawMapPin(clientIdArray, item, colour);
                });

                //Also, display the description text in the locationTypeDescription div
                if (ddlLocationTypes.options[ddlLocationTypes.selectedIndex].value == "All")
                {
                    document.getElementById(clientIdArray[13]).style.display = "none";
                }
                else
                {
                    document.getElementById(clientIdArray[13]).style.display = "block";
                    document.getElementById(clientIdArray[13]).innerHTML = "<p>" + item.Description + "</p>";
                }
            }
        });
    }
}

function DrawMapPin(clientIdArray, location, colour)
{
    imgPin = document.createElement("img");
    imgPin.id = "imgPin" + location.Name;
    imgPin.src = "/Resources/images/Pins/" + colour;
    imgPin.style.position = "absolute";
    imgPin.style.top = new String(location.Top - 12) + "px";
    imgPin.style.left = new String(location.Left - 4) + "px";
    imgPin.style.cursor = "pointer";
    
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");
    if (msie > 0)
    {
        imgPin.attachEvent('onmouseover', function() { ShowLocationFloatingPopup(clientIdArray, location); });
        imgPin.attachEvent('onmouseout', function() { HideLocationFloatingPopup(clientIdArray[3]); });
    }
    else
    {
        imgPin.addEventListener('mouseover', function() { ShowLocationFloatingPopup(clientIdArray, location); }, false);
        imgPin.addEventListener('mouseout', function() { HideLocationFloatingPopup(clientIdArray[3]); }, false);
    }

    divLocationMapCon.appendChild(imgPin);
}

function ShowLocationFloatingPopup(clientIdArray, locationData)
{
    df = document.getElementById(clientIdArray[3]);

    df.style.display = 'block';
    df.style.top = parseInt(locationData.Top) + 10 + "px";
    df.style.left = parseInt(locationData.Left) + 10 + "px";
    df.style.zIndex = 10000;

    document.getElementById(clientIdArray[4]).innerHTML = locationData.Name;

    document.getElementById(clientIdArray[5]).innerHTML = locationData.AddressLine1;
    document.getElementById(clientIdArray[6]).innerHTML = locationData.AddressLine2;
    document.getElementById(clientIdArray[7]).innerHTML = locationData.AddressLine3;
    document.getElementById(clientIdArray[8]).innerHTML = locationData.County;
    document.getElementById(clientIdArray[9]).innerHTML = locationData.Postcode;

    document.getElementById(clientIdArray[10]).innerHTML = locationData.Manager;
    document.getElementById(clientIdArray[11]).innerHTML = locationData.Telephone;
    document.getElementById(clientIdArray[12]).innerHTML = locationData.Switchboard;
}

function HideLocationFloatingPopup(divFloatClientId)
{
    document.getElementById(divFloatClientId).style.display = 'none';
}

