﻿/*
FILE SUMMARY
------------------------------------------------------------------------------------------------
Filename				: personalisation.js
Created	Date			: 01/03/2010
Creating Author			: Stephen Farrell
------------------------------------------------------------------------------------------------
Last Modified Date		: 
Last Modified Author	: 
------------------------------------------------------------------------------------------------
Name					: personalisation.js 
Stereotype				: JavaScript class
Namespace				: 
------------------------------------------------------------------------------------------------
Purpose					: Common methods for the personalisation features.
: Makes use of the jQuery 1.3.2 library for animation effects.
: JS methods call a webservice via the Microsoft AJAX.net framework and 
: use the callback / onfail pattern
------------------------------------------------------------------------------------------------
*/

// Global Variables
var passwordRetrievalAttempts = 5;
var ddlValue;
var path = window.location.pathname;
var host = window.location.host;
var protocol = window.location.protocol;
var viewType = 0;


/*
------------------------------------------------------------------------------------------------
Anchor go to script using jQuery - we keep it smooth instead of nasty jump
------------------------------------------------------------------------------------------------
*/
$(document).ready(function() {
    $("a.anchorLink").anchorAnimate()
});

jQuery.fn.anchorAnimate = function(settings) {

    settings = jQuery.extend({
        speed: 1100
    }, settings);

    return this.each(function() {
        var caller = this
        $(caller).click(function(event) {
            event.preventDefault()
            var locationHref = window.location.href
            var elementClick = $(caller).attr("href")

            var destination = $(elementClick).offset().top;
            $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination }, settings.speed, function() {
                window.location.hash = elementClick
            });
            return false;
        })
    })
}

/*
------------------------------------------------------------------------------------------------
If the personalisation database is found to be offline, this function is used to load the 
DatabaseOffline.ascx bar control to inform the user the database is currently offline.
------------------------------------------------------------------------------------------------
*/
function DatabaseNotOnline() {
    $(document).ready(function() {
        LoadBarControl("~/Uil/Controls/Personalisation/Bar/DatabaseOffline.ascx");
    });
}

/*
------------------------------------------------------------------------------------------------
If personalisation has been turned off in the CMS redirect to the specified page
------------------------------------------------------------------------------------------------
*/
function NotOnline() {
    $(document).ready(function() {
        window.location = protocol + '//' + host + '/personalisation-offline.aspx';
    });
}

/*
------------------------------------------------------------------------------------------------
Find out what error we actually have returned and process accordingly
------------------------------------------------------------------------------------------------
*/
function ErrorProcessor(error) {
    $(document).ready(function() {
        var errorLength = error.toString().substr(0, error.toString().length);
        var errorMessage = error.toString().substr(6, errorLength.length);

        switch (errorMessage) {
            case "DATABASE_OFFLINE":
                DatabaseNotOnline();
                break;
            case "PERSONALISATION_OFFLINE":
                NotOnline();
                break;
            case "MAX_ATTEMPTS":
                // The container div and the inner div both need to be enlarge to accomodate the new text.
                $("#ctl00_PersonalisationBar1_apc").removeClass().addClass('actionForgotPasswordBig');
                $("div.newAjaxPanelSuccess").removeClass().addClass('newAjaxPanelPasswordError');
                $("#forgottenPasswordText").html('You have requested a password reminder email more times than is permitted in a session. If you have not received this email to date please check your spam filter and junk mail settings.<br />');
                break;
            case "CREDENTIALS":
                $("#forgottenPasswordText").html('Email address not recognised. Please try again.<br />');
                break;
            case "EMAIL_SEND":
                $("#forgottenPasswordText").html('There was a problem sending the email, please try again later.<br />');
                break;
            case "CREATE_EMAIL":
                $("#forgottenPasswordText").html('There was a problem sending the email, please try again later.<br />');
                break;
        }
        $("#forgottenPasswordText").css('color', 'red');
    });
}


/*
------------------------------------------------------------------------------------------------
Dynamically loads a user control by calling the web service and passing the control
location as a parameter.
------------------------------------------------------------------------------------------------
*/
function LoadControl(controlLocation) {
    $(document).ready(function() {
        ScriptService.GetControlHtml(controlLocation, CallbackLoadPanelHTML);
    });
}

/*
------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------
*/
function CallbackLoadPanelHTML(result) {
    $(document).ready(function() {
        if (result == "DATABASE_OFFLINE") {
            DatabaseNotOnline();
            return;
        }
        else if (result == "OFFLINE") {
            NotOnline();
            return;
        }
        else if (result == "TIMEOUT") {
            LogOff();
            return;
        }
        // Disable the bar panel and clear out content :TODO chain this event up properly
        DisableMe();

        $("#ctl00_PersonalisationBar1_apc").html(result);

        // Show the action panel with animation
        $("#ctl00_PersonalisationBar1_apc").slideToggle("slow", function() {
            // Animation complete.
        });
    });
}

/*
------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------
*/
function CallbackLoadBarControl(result) {
    $(document).ready(function() {
        if (result == "DATABASE_OFFLINE") {
            DatabaseNotOnline();
            return;
        }
        else if (result == "OFFLINE") {
            NotOnline();
            return;
        }
        else if (result == "TIMEOUT") {
            LogOff();
            return;
        }

        $("#ctl00_PersonalisationBar1_barContents").slideToggle("slow", function() {
            $("#ctl00_PersonalisationBar1_barContents").html(result);
            DisableMe();
        });

        var controlType = result.substring(9, 17);

        // If user is signing in get Default page
        if (controlType == "signedIn") {
            // Let the animation finish before re-directing
            setTimeout("ScriptService.GetDefaultPage(CallbackDefaultPage)", 0);
        }
    });
}

/*
------------------------------------------------------------------------------------------------
Section - Forgotten Password
------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------
Button Click to show FP panel
------------------------------------------------------------------------------------------------
*/
function ForgottenPassword(replacePanel) {
    $(document).ready(function() {
        if (replacePanel == undefined) {
            ScriptService.GetControlHtml('~/Uil/Controls/Personalisation/UpdatePanel/ForgottenPassword.ascx', CallbackForgottenPassword);
        }
        else {
            ScriptService.GetControlHtml('~/Uil/Controls/Personalisation/UpdatePanel/ForgottenPassword.ascx', CallbackForgottenPasswordReplacePanel);
        }
    });
}

/*
------------------------------------------------------------------------------------------------
Callback function to show the FP panel
------------------------------------------------------------------------------------------------
*/
function CallbackForgottenPassword(result) {
    $(document).ready(function() {
        if (result != "OFFLINE") {
            DisableMe();
            $("#ctl00_PersonalisationBar1_apc").removeClass().addClass('actionForgotPassword');
            $("#ctl00_PersonalisationBar1_apc").html(result);
            $("#ctl00_PersonalisationBar1_apc").slideToggle("slow", function() {
            });
        }
        else {
            NotOnline();
        }
    });
}

/*
------------------------------------------------------------------------------------------------
Callback function to show the FP panel but only once we've removed the existing panel.
------------------------------------------------------------------------------------------------
*/
function CallbackForgottenPasswordReplacePanel(result) {
    $(document).ready(function() {
        if (result != "OFFLINE") {
            $("#ctl00_PersonalisationBar1_apc").removeClass().addClass('actionPanelSmall');
            $("#ctl00_PersonalisationBar1_apc").slideToggle("slow", function() {
                $("#ctl00_PersonalisationBar1_apc").html(result);
                $("#ctl00_PersonalisationBar1_apc").slideToggle("slow", function() {
                });
            });
        }
        else {
            NotOnline();
        }
    });
}

/*
-------------------------------------------------------------------
Button Click attempting to retrive the password
-------------------------------------------------------------------
*/
function SendForgottenPassword() {
    $(document).ready(function() {

        var robot = $("#txtCovertCaptchaPanel").val();

        if (robot != "") {
            alert('robot attack!');
            return;
        }

        var email = $("#txtEmailPassword").val();

        if (email != "") {
            ScriptService.SendForgottenPassword(email, CallbackSendForgottenPassword);
        }
        else {
            alert('You must supply an email address.');
            $("#txtEmailPassword").removeClass().addClass('inputBoxError');
            return;
        }
    });
}

/*
------------------------------------------------------------------------------------------------
Show the success panel if the password was sent Ok or show an error message
------------------------------------------------------------------------------------------------
*/
function CallbackSendForgottenPassword(result) {
    $(document).ready(function() {
        if (result.indexOf("ERROR", 0) == -1) {
            $("#ctl00_PersonalisationBar1_apc").removeClass().addClass('actionPanelSmall');
            $("#ctl00_PersonalisationBar1_apc").slideToggle("slow", function() {
                $("#ctl00_PersonalisationBar1_apc").html(result);
                $("#ctl00_PersonalisationBar1_apc").slideToggle("slow", function() {
                });
            });
        }
        else {
            ErrorProcessor(result);
        }
    });
}

/*
------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------
*/
function LoadBarControl(controlLocation) {
    $(document).ready(function() {
        ScriptService.GetControlHtml(controlLocation, CallbackLoadBarControl);
    });
}

/*
------------------------------------------------------------------------------------------------
Logs a user into the system
------------------------------------------------------------------------------------------------
*/
function LogIn(controlLocation, isBarSignIn) {
    $(document).ready(function() {
        var email;
        var password;
        var rememberme;
        var robot;

        if (isBarSignIn) {

            robot = $("#txtCovertCaptchaBar").val();

            if (robot != "") {
                alert('robot attack!');
                return;
            }

            email = $("#email").val();
            password = $("#Password").val();
            rememberme = $("#RememberMe").attr('checked');

            if (email != "" && password != "") {
                ScriptService.LogIn(controlLocation, email, password, rememberme, CallbackLoadBarControl, OnFailLogIn);
            }
            else {
                alert('Please enter both email and password');
                if (email == "") {
                    $("#email").removeClass().addClass('inputBoxError');
                }
                else {
                    $("#email").removeClass().addClass('inputBorder');
                }
                if (password == "") {
                    $("#Password").removeClass().addClass('inputBoxError');
                }
                else {
                    $("#Password").removeClass().addClass('inputBorder');
                }
                return false;
            }
        }
        else {

            robot = $("#txtCovertCaptchaPanel").val();

            if (robot != "") {
                alert('robot attack!');
                return;
            }

            email = $("#LogInUserName").val();
            password = $("#LogInPassword").val();
            rememberme = $("#LogInRememberMe").attr('checked');

            if (email != "" && password != "") {
                ScriptService.LogIn(controlLocation, email, password, rememberme, CallbackLoadPanelHTMLSaveView, OnFailLogInReplacePanel);
            }
            else {
                alert('Please enter both email and password');
                if (email == "") {
                    $("#LogInUserName").removeClass().addClass('inputBorderFormsError');
                }
                else {
                    $("#LogInUserName").removeClass().addClass('inputBorderForms');
                }
                if (password == "") {
                    $("#LogInPassword").removeClass().addClass('inputBorderFormsError');
                }
                else {
                    $("#LogInPassword").removeClass().addClass('inputBorderForms');
                }
                return false;
            }
        }
    });
}

/*
------------------------------------------------------------------------------------------------
login function called by the sign in panel within SignUpAjax.ascx
------------------------------------------------------------------------------------------------
*/
function LogInFromPanel(controlLocation, viewtype) {
    $(document).ready(function() {
        var email;
        var password;
        var rememberme;
        var robot;

        viewType = viewtype;

        robot = $("#txtCovertCaptchaPanel").val();

        if (robot != "") {
            alert('robot attack!');
            return;
        }

        email = $("#LogInUserName").val();
        password = $("#LogInPassword").val();
        rememberme = $("#LogInRememberMe").attr('checked');

        if (email != "" && password != "") {
            ScriptService.LogIn(controlLocation, email, password, rememberme, CallbackLoadPanelHTMLSaveViewAfterLogin, OnFailLogInReplacePanel);
        }
        else {
            alert('Please enter both email and password');
            if (email == "") {
                $("#LogInUserName").removeClass().addClass('inputBorderFormsError');
            }
            else {
                $("#LogInUserName").removeClass().addClass('inputBorderForms');
            }
            if (password == "") {
                $("#LogInPassword").removeClass().addClass('inputBorderFormsError');
            }
            else {
                $("#LogInPassword").removeClass().addClass('inputBorderForms');
            }
            return false;
        }
    });
}

/*
------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------
*/
function LogInAfterError(controlLocation) {
    $(document).ready(function() {
        var email = $("#ErrorUserName").val();
        var password = $("#ErrorPassword").val();
        var rememberme = $("#ErrorRememberMe").attr('checked');
        var robot = $("#txtCovertCaptchaPanel").val();

        if (robot != "") {
            alert('robot attack!');
            return;
        }

        if ($("#ErrorUserName").val() != "" && $("#ErrorPassword").val() != "") {
            ScriptService.LogIn(controlLocation, email, password, rememberme, CallbackLoadPanelHTMLSaveView, OnFailContinualLoginError);
        }
        else {
            alert('Please enter both email and password');
            if (email == "") {
                $("#ErrorUserName").removeClass().addClass('inputBoxError');
            }
            else {
                $("#ErrorUserName").removeClass().addClass('inputBorder');
            }
            if (password == "") {
                $("#ErrorPassword").removeClass().addClass('inputBoxError');
            }
            else {
                $("#ErrorPassword").removeClass().addClass('inputBorder');
            }
            return false;
        }
    });
}

/*
------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------
*/
function CallbackSignInError(result) {
    $(document).ready(function() {
        DisableMe();
        $("#ctl00_PersonalisationBar1_apc").html(result);
        $("#loginErrorText").html('The supplied credentials were not recognised. Please try again. <br />');

        // Show the action panel with animation
        $("#ctl00_PersonalisationBar1_apc").slideToggle("slow", function() {
            $("#ctl00_PersonalisationBar1_apc").removeClass().addClass('actionPanelSignUpError');
        });
    });
}

/*
------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------
*/
function CallbackSignInErrorReplacePanel(result) {
    $(document).ready(function() {
        $("#ctl00_PersonalisationBar1_apc").slideToggle("slow", function() {
            $("#ctl00_PersonalisationBar1_apc").html(result);
            $("#loginErrorText").html('The supplied credentials were not recognised. Please try again. <br />');

            // Show the action panel with animation
            $("#ctl00_PersonalisationBar1_apc").removeClass().addClass('actionPanelSignUpError');
            $("#ctl00_PersonalisationBar1_apc").slideToggle("slow", function() {
            });
        });
    });
}

/*
------------------------------------------------------------------------------------------------
Allows a user to log off abandoning the session
------------------------------------------------------------------------------------------------
*/
function LogOff() {
    $(document).ready(function() {
        ScriptService.LogOff(CallbackLogOff);
    });
}

/*
------------------------------------------------------------------------------------------------
Redireect to the home page after sucessfull log off
------------------------------------------------------------------------------------------------
*/
function CallbackLogOff(result) {
    $(document).ready(function() {
        window.location = protocol + '//' + host + '/index.aspx';
    });
}


/*
------------------------------------------------------------------------------------------------
Loads the Error panel if the user enters incorrect details
------------------------------------------------------------------------------------------------
*/
function OnFailLogIn() {
    $(document).ready(function() {
        $("#email").val("");
        $("#Password").val("");
        ScriptService.GetControlHtml('~/Uil/Controls/Personalisation/UpdatePanel/Error.ascx', CallbackSignInError, OnFailContinualLoginError);
    });
}

/*
------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------
*/
function OnFailLogInReplacePanel() {
    $(document).ready(function() {
        ScriptService.GetControlHtml('~/Uil/Controls/Personalisation/UpdatePanel/Error.ascx', CallbackSignInErrorReplacePanel, OnFailContinualLoginError);
    });
}

/*
------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------
*/
function OnFailContinualLoginError() {
    $(document).ready(function() {
        var errorText = $("#loginErrorText").val();
        $("#loginErrorText").html('The supplied credentials are still not recognised. Please try again. <br />');
        $("#ErrorUserName").removeClass().addClass('inputBorder');
        $("#ErrorPassword").removeClass().addClass('inputBorder');

        return false;
    });
}

/*
------------------------------------------------------------------------------------------------
Section - Sign user up for membership
------------------------------------------------------------------------------------------------
*/
function SignUpUser() {
    $(document).ready(function () {
	$("#SignUpUserName").removeClass().addClass('inputBorderForms');
	$("#SignUpPassword").removeClass().addClass('inputBorderForms');
        var username = $("#SignUpUserName").val();
        var email = $("#SignUpEmail").val();
        var password = $("#SignUpPassword").val();
        var confirmPassword = $("#SignUpConfirmPassword").val();
        var rememberme = $("#SignUpRememberMe").attr('checked');

        // variables for the overt captcha
        var captchaOne = password.charAt($("#ctl01_lblCaptchaOne").text() - 1);
        var captchaTwo = password.charAt($("#ctl01_lblCaptchaTwo").text() - 1);
        var inputOne = $("#CaptchaOne").val();
        var inputTwo = $("#CaptchaTwo").val();

        var emailRegularExpression = "";

        if (username != "" && email != "" && password != "" && confirmPassword != "") {
            // check passwords match
            if (confirmPassword != password) {
                alert('Passwords do not match');
                $("#SignUpPassword").removeClass().addClass('inputBorderFormsError');
                $("#SignUpConfirmPassword").removeClass().addClass('inputBorderFormsError');
                return;
            }
            // check password is 8 characters minimum
            if (password.length < 8) {
                alert('Password must be at least 8 characters in length');
                $("#SignUpPassword").removeClass().addClass('inputBorderFormsError');
                return;
            }
            /* Do the overt captcha */
            if ((captchaOne != inputOne) || (captchaTwo != inputTwo)) {
                alert('One or more password characters are incorrect');
                $("#CaptchaOne").removeClass().addClass('inputBorderFormsErrorSm');
                $("#CaptchaOne").focus();
                return;
            }

            if (username.substring(0, 1) == ' ' || username.substring(username.length - 1, username.length) == ' '){
		
                $("#SignUpUserName").removeClass().addClass('inputBorderFormsError');
                alert('Username must not contain any leading or trailing spaces');
                return;
            }
		
            if (password.substring(0, 1) == ' ' || password.substring(password.length - 1, password.length) == ' '){
                alert('Password must not contain any leading or trailing spaces');
                $("#SignUpPassword").removeClass().addClass('inputBorderFormsError');
                return;
            }

            ScriptService.SignUpUser(username, password, email, rememberme, CallbackSignUp);
        }
        else {
            alert('Please enter username, password and email');
            if (username == "") {
                $("#SignUpUserName").removeClass().addClass('inputBorderFormsError');
            }
            else {
                $("#SignUpUserName").removeClass().addClass('inputBorderForms');
            }
            if (email == "") {
                $("#SignUpEmail").removeClass().addClass('inputBorderFormsError');
            }
            else {
                $("#SignUpEmail").removeClass().addClass('inputBorderForms');
            }
            if (password == "") {
                $("#SignUpPassword").removeClass().addClass('inputBorderFormsError');
            }
            else {
                $("#SignUpPassword").removeClass().addClass('inputBorderForms');
            }
            if (confirmPassword == "") {
                $("#SignUpConfirmPassword").removeClass().addClass('inputBorderFormsError');
            }
            else {
                $("#SignUpConfirmPassword").removeClass().addClass('inputBorderForms');
            }
            return;
        }
    });
}

/*
------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------
*/
function SaveViewAfterSignUp(controlLocation, viewtype) {
    $(document).ready(function() {
        viewType = viewtype;
        ScriptService.GetControlHtml(controlLocation, CallbackSaveViewAfterSignUp);
    });
}

/*
------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------
*/
function CallbackSaveViewAfterSignUp(result) {
    $(document).ready(function() {
        // Load the bar control with the Signed In HTML
        $("#ctl00_PersonalisationBar1_barContents").html(result);

        // Now load the save view panel
        ScriptService.GetControlHtmlSaveMyView("~/Uil/Controls/Personalisation/UpdatePanel/SaveView.ascx", viewType, CallBackLoadSaveViewPanel);
    });
}

/*
------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------
*/
function CallBackLoadSaveViewPanel(result) {
    $(document).ready(function() {
        if (result == "DATABASE_OFFLINE") {
            DatabaseNotOnline();
            return;
        }
        else if (result == "OFFLINE") {
            NotOnline();
            return;
        }
        else if (result == "TIMEOUT") {
            LogOff();
            return;
        }
        $("#ctl00_PersonalisationBar1_apc").slideToggle("slow", function() {
            $("#ctl00_PersonalisationBar1_apc").html(result);
            $("#ctl00_PersonalisationBar1_apc").removeClass().addClass('actionPanelContainerLarge');
            $("#ctl00_PersonalisationBar1_apc").slideToggle("slow", function() {
            });
        });
    });
}

/*
------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------
*/
function LoadBarControlAfterSignUp(controlLocation) {
    $(document).ready(function() {
        ScriptService.GetControlHtml(controlLocation, CallbackLoadPanelHTMLAfterSignUp);
    });
}

/*
------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------
*/
function CallbackLoadPanelHTMLAfterSignUp(result) {
    $(document).ready(function() {
        $("#ctl00_PersonalisationBar1_barContents").html(result);
        EnableMe();
    });
}

/*
------------------------------------------------------------------------------------------------
Callback method to process the result of a user trying to sign up
------------------------------------------------------------------------------------------------
*/
function CallbackSignUp(result) {
    $(document).ready(function() {
        if (result == "DATABASE_OFFLINE") {
            DatabaseNotOnline();
            return;
        }
        else if (result == "OFFLINE") {
            NotOnline();
            return;
        }
        else if (result == "TIMEOUT") {
            LogOff();
            return;
        }
        else if (result.toString().substr(0, 5) == 'ERROR') {
            alert(result.toString().substr(6, result.toString().length));


            /* unpleasant hack to highlight the error fields */

            if (result.toString().indexOf('The E-mail address is already in use') != -1) {
                $("#SignUpEmail").removeClass().addClass('inputBorderFormsError');
            } else if (result.toString().indexOf('The username is already in use') != -1) {
                $("#SignUpUserName").removeClass().addClass('inputBorderFormsError');
            }
            return;
        }
        $("#ctl00_PersonalisationBar1_apc").slideToggle("slow", function() {
            $("#ctl00_PersonalisationBar1_apc").html(result);
            $("#ctl00_PersonalisationBar1_apc").removeClass().addClass('actionPanelSmall');
            $("#ctl00_PersonalisationBar1_apc").slideToggle("slow", function() {
            });
        });
    });
}

/*
------------------------------------------------------------------------------------------------
Redirects a user to their default page if they have one
------------------------------------------------------------------------------------------------
*/
function CallbackDefaultPage(result) {
    $(document).ready(function() {
        if (result == "DATABASE_OFFLINE") {
            DatabaseNotOnline();
        }
        else if (result == "OFFLINE") {
            NotOnline();
            return;
        }
        if (result != "" && result != "default" && result != path) {
            window.location = protocol + '//' + host + result + '?navbar=true'; // append the navbar tag so we can get the default view
        }
    });
}

/*
------------------------------------------------------------------------------------------------
Disables the bar panel when the action panel is in use
------------------------------------------------------------------------------------------------
*/
function DisableMe() {
    $(document).ready(function() {
        $('#ctl00_PersonalisationBar1_barContents').slideToggle("slow", function() {
        });
    });
}

/*
------------------------------------------------------------------------------------------------
The opposite of disable me. Clears out the action panel HTML enabels the bar again and closes the action panel via animation
------------------------------------------------------------------------------------------------
*/
function ClosePanel() {
    $(document).ready(function() {
        $("#ctl00_PersonalisationBar1_apc").slideToggle("slow", function() {

        });
    });
}

/*
------------------------------------------------------------------------------------------------
The opposite of disable me. Clears out the action panel HTML enabels the bar again and closes the action panel via animation
------------------------------------------------------------------------------------------------
*/
function EnableMe() {
    $(document).ready(function() {
        $("#ctl00_PersonalisationBar1_apc").slideToggle("slow", function() {
            $('#ctl00_PersonalisationBar1_barContents').slideToggle("slow", function() {
                $("#ctl00_PersonalisationBar1_apc").removeClass().addClass('actionPanelContainer');
                $("#ctl00_PersonalisationBar1_apc").html("");
            });
        });
    });
}

/*
-------------------------------------------------------------------
Section - Save my views
-------------------------------------------------------------------
-------------------------------------------------------------------
Saves a users view to their profile
-------------------------------------------------------------------
*/
function SaveView(url, viewtype) {
    $(document).ready(function() {
        //  Has the user filled in the view name?
        if ($("#tbxViewName").val() == "") {
            $("#tbxViewName").removeClass().addClass('inputBoxError');
            alert('You must name the view.');
            return;
        }

        // Are they setting a default view?
        var isDefaultView = false;

        // Get the save type from which radio button is checked.
        if ($("#radDefaultPage").attr('checked')) {
            ScriptService.SaveDefaultPage(url, CallbackSaveDefaultPage);
        }
        else if ($("#radDefaultView").attr('checked')) {
            isDefaultView = true;
        }

        switch (viewtype) {
            case "1": // Traffic Map
                SaveMapView(isDefaultView);
                break;
            case "2": // MTF
                SaveMTFSearchView(isDefaultView);
                break;
            case "3": // Disruption Search
                SaveDisruptionSearchView(isDefaultView);
                break;
            case "4": // Empty DS view
                SaveDisruptionEmptySearchView(isDefaultView);
                break;
        }
    });
}

/* 
-------------------------------------------------------------------

-------------------------------------------------------------------
*/
function SaveMTFSearchView(defaultView) {
    $(document).ready(function () {

        var viewName = $("#tbxViewName").val();
        var roadClosures = $("#ctl00_ContentPlaceHolder1_ctl00_chkRoadClosures").attr('checked');
        var highProfileEvents = $("#ctl00_ContentPlaceHolder1_ctl00_chkHighProfileEvents").attr('checked');
        var incidentsCongestion = $("#ctl00_ContentPlaceHolder1_ctl00_chkIncidentsAndCongestion").attr('checked');
        var speed = $("#ctl00_ContentPlaceHolder1_ctl00_chkSpeed").attr('checked');
        var roadsideMessageSigns = $("#ctl00_ContentPlaceHolder1_ctl00_chkRoadsideSigns").attr('checked');
        var roadworks = $("#ctl00_ContentPlaceHolder1_ctl00_chkRoadworks").attr('checked');
        var trafficCameras = $("#ctl00_ContentPlaceHolder1_ctl00_chkTrafficCameras").attr('checked');
        var adverseWeather = $("#ctl00_ContentPlaceHolder1_ctl00_chkWeatherReports").attr('checked');

        ScriptService.SaveMotorwayFlowView(viewName, incidentsCongestion, roadClosures, highProfileEvents, speed, roadsideMessageSigns, roadworks, trafficCameras, adverseWeather, defaultView, CallbackSaveView);
    });
}

/* 
-------------------------------------------------------------------

-------------------------------------------------------------------
*/
function SaveDisruptionSearchView(defaultView) {
    $(document).ready(function () {
        var delaysFor = $("#ctl00_ContentPlaceHolder1_ctl00_ctlDateRangeSelector_pickForwardDateRange").val();
        var delayTime = $("#ctl00_ContentPlaceHolder1_ctl00_pickDelayTime").val();
        var incidentsCongestion = $("#ctl00_ContentPlaceHolder1_ctl00_chkIncidentsAndCongestion").attr('checked');
        var roadworks = $("#ctl00_ContentPlaceHolder1_ctl00_chkRoadworks").attr('checked');
        //var plannedEvents = $("#ctl00_ContentPlaceHolder1_ctl00_chkPlannedEvents").attr('checked');
        var plannedEvents = false;
        var adverseWeather = $("#ctl00_ContentPlaceHolder1_ctl00_chkWeatherReports").attr('checked');
        var roadClosures = $("#ctl00_ContentPlaceHolder1_ctl00_chkRoadClosures").attr('checked');
        var highProfileEvents = $("#ctl00_ContentPlaceHolder1_ctl00_chkHighProfileEvents").attr('checked');

        var viewName = $("#tbxViewName").val();
        var sortBy = "";
        var showResults = "";
 
        // public string SaveDisruptionSearchView(string viewname, short delaysFor, short delayTime, bool roadClosures, bool highProfileEvents, bool incidentsCongestion, bool roadworks, bool plannedEvents, bool adverseWeather, bool isDefaultView)
        ScriptService.SaveDisruptionSearchView(viewName, delaysFor, delayTime, roadClosures, highProfileEvents, incidentsCongestion, roadworks, plannedEvents, adverseWeather, defaultView, CallbackSaveView);
    });
}

/* 
-------------------------------------------------------------------

-------------------------------------------------------------------
*/
function SaveDisruptionEmptySearchView(defaultView) {
    $(document).ready(function () {
        var delaysFor = $("#ctl00_ContentPlaceHolder1_ctl00_ctlDateRangeSelector_pickForwardDateRange").val();
        var delayTime = $("#ctl00_ContentPlaceHolder1_ctl00_pickDelayTime").val();
        var incidentsCongestion = $("#ctl00_ContentPlaceHolder1_ctl00_chkIncidentsAndCongestion").attr('checked');
        var roadworks = $("#ctl00_ContentPlaceHolder1_ctl00_chkRoadworks").attr('checked');
        //   var plannedEvents = $("#ctl00_ContentPlaceHolder1_ctl00_chkPlannedEvents").attr('checked');
        var plannedEvents = false;
        var adverseWeather = $("#ctl00_ContentPlaceHolder1_ctl00_chkWeatherReports").attr('checked');
        var roadClosures = $("#ctl00_ContentPlaceHolder1_ctl00_chkRoadClosures").attr('checked');
        var highProfileEvents = $("#ctl00_ContentPlaceHolder1_ctl00_chkHighProfileEvents").attr('checked');

        var viewName = $("#tbxViewName").val();
        var sortBy = "";
        var showResults = "";
        
        ScriptService.SaveDisruptionSearchView(viewName, delaysFor, delayTime, roadClosures, highProfileEvents, incidentsCongestion, roadworks, plannedEvents, adverseWeather, defaultView, CallbackSaveView);
    });
}

/* 
-------------------------------------------------------------------
Save the Map view to the database against the current user profile.
-------------------------------------------------------------------
*/
function SaveMapView(defaultView) {
    $(document).ready(function () {
        // Get the Navteq map object if loaded
        var mapView = M24.getCurrentView();

        // Grab the coordinates from the mapview object
        var topLeftLong = mapView.TopLeft.Longitude;
        var topLeftLat = mapView.TopLeft.Latitude;
        var lowerRightLong = mapView.LowerRight.Longitude;
        var lowerRightLat = mapView.LowerRight.Latitude;

        //Get the map filter states (radio buttons to the side of the map)
        //Current Information
        var speedDelays = $("#chkDelay").attr('checked');
        var roadClosures = $("#chkRoadClosures").attr('checked');
        var highProfile = $("#chkHighProfileEvents").attr('checked');
        var incidentsCongestion = $("#chkIncidentsAndCongestion").attr('checked');
        var roadworks = $("#chkRoadworks").attr('checked');
        var adverseWeather = $("#chkAdverseWeather").attr('checked');
        var messageSigns = $("#chkSignsOn").attr('checked');
        var trafficCameras = $("#chkTrafficCamerasOn").attr('checked');
        //Future Information
        var futureRoadClosures = $("#chkFutureRoadClosures").attr('checked');
    //    var futureHighProfileEvents = $("#chkFutureHighProfileEvents").attr('checked');
        var futureEvents = $("#chkFutureEventsOn").attr('checked');
        var futureRoadworks = $("#chkFutureRoadworksOn").attr('checked');


        // Saved View Name
        var viewName = $("#tbxViewName").val();
        /*
            public string SaveMapView(string lon0, string lat0, string lon1, string lat1, string viewName,
                            bool speedDelays, bool roadClosures, bool highProfileEvents, bool incidentsCongestion, bool roadworks, bool adverseWeather,
                            bool messageSigns, bool trafficCameras, bool futureRoadClosures, bool futureHighProfileEvents, bool futureEvents, bool futureRoadworks, bool isDefaultView)
        */
        // Call the service script method to save the map view to the database
        ScriptService.SaveMapView(topLeftLong,
                                    topLeftLat,
                                    lowerRightLong,
                                    lowerRightLat,
                                    viewName,
                                    speedDelays,
                                    roadClosures,
                                    highProfile,
                                    incidentsCongestion,
                                    roadworks,
                                    adverseWeather,
                                    messageSigns,
                                    trafficCameras,
                                    futureRoadClosures,
                       //             futureHighProfileEvents,
                                    futureEvents,
                                    futureRoadworks,
                                    defaultView,
                                    CallbackSaveView);
    });
}

/*
------------------------------------------------------------------------------------------------
Processes the returned string from the Web Service checking for any errors.
------------------------------------------------------------------------------------------------
*/
function SaveViewErrorProcessor(error) {
    // DB Has crashed and is offline
    if (error == "DATABASE_OFFLINE") {
        DatabaseNotOnline();
        return;
    }
    // Personalisation has been turned off
    else if (error == "OFFLINE") {
        NotOnline();
        return;
    }
    // Session has timed out
    else if (error == "TIMEOUT") {
        LogOff();
        return;
    }
    // Save limit reached
    else if (error == "MAX") {
        // Too many saves for this section
        ScriptService.GetControlHtml('~/Uil/Controls/Personalisation/UpdatePanel/ErrorSV.ascx', CallbackOnFailSaveUserView);
    }
    // User name exists
    else if (error == "EXISTS") {
        ScriptService.GetControlHtml('~/Uil/Controls/Personalisation/UpdatePanel/ErrorSUN.ascx', CallbackOnFailSaveUserView);
    }
    else if (error == "BLACKLIST_ERROR") {
        alert("Could not save map view at this time (Blacklist error). Please try again later.");
        return;
    }
    else if (error.substr(0, 13) == "GENERAL_ERROR") {
        alert("Could not save map view at this time (General error). " + error);
        return;
    }
    // No error so return result
    else {
        return error;
    }
}

/*
------------------------------------------------------------------------------------------------
Loads the error panel when the user has tried to save more than 10 views per section or same name
------------------------------------------------------------------------------------------------
*/
function CallbackOnFailSaveUserView(result) {
    $(document).ready(function() {
        $("#ctl00_PersonalisationBar1_apc").slideToggle("slow", function() {
            $("#ctl00_PersonalisationBar1_apc").removeClass().addClass('actionPanelSmall');
            $("#ctl00_PersonalisationBar1_apc").html(result);
            $("#ctl00_PersonalisationBar1_apc").slideToggle("slow", function() {
            });
        });
    });
}


/* 
-------------------------------------------------------------------
Save the Map view to the database against the current user profile.
-------------------------------------------------------------------
*/
function SaveBlacklistedMapView() {
    $(document).ready(function() {
        // Get the Navteq map object if loaded
        var mapView = M24.getCurrentView();

        // Grab the coordinates from the mapview object
        var topLeftLong = mapView.TopLeft.Longitude;
        var topLeftLat = mapView.TopLeft.Latitude;
        var lowerRightLong = mapView.LowerRight.Longitude;
        var lowerRightLat = mapView.LowerRight.Latitude;

        //Get the map filter states (radio buttons to the side of the map)
        var speedDelays = $("#chkDelay").attr('checked');
        var incidentsCongestion = $("#chkIncidentsAndCongestion").attr('checked');
        var roadworks = $("#chkRoadworks").attr('checked');
        var adverseWeather = $("#chkAdverseWeather").attr('checked');
        var messageSigns = $("#chkSignsOn").attr('checked');
        var trafficCameras = $("#chkTrafficCamerasOn").attr('checked');
        var futureEvents = $("#chkFutureEventsOn").attr('checked');
        var futureRoadworks = $("#chkFutureRoadworksOn").attr('checked');

        // Saved View Name
        var viewName = $("#tbxViewName").val();

        // Re-direct to black listed save page
        window.location = protocol + '//' + host + '/save-my-view.aspx?type=map&long0=' + topLeftLong + '&lat0=' + topLeftLat + '&long1=' + lowerRightLong + '&lat1=' + lowerRightLat + '&sd=' + speedDelays + '&ic=' + incidentsCongestion + '&rw=' + roadworks + '&aw=' + adverseWeather + '&ms=' + messageSigns + '&tc=' + trafficCameras + '&fe=' + futureEvents + '&fr=' + futureRoadworks;

        return false;
    });
}

/*
------------------------------------------------------------------------------------------------
Loads the save view control or Sign up control if not logged in on call back
------------------------------------------------------------------------------------------------
*/
function SaveMyView(controlLocation, viewtype) {
    $(document).ready(function() {
        ScriptService.GetControlHtmlSaveMyView(controlLocation, viewtype, CallbackSaveMyView, OnFailSaveMyView);
    });
}

/*
------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------
*/
function CallbackSaveMyView(result) {
    $(document).ready(function() {
        if (result == "DATABASE_OFFLINE") {
            DatabaseNotOnline();
            return;
        }
        else if (result == "OFFLINE") {
            NotOnline();
            return;
        }
        else if (result == "TIMEOUT") {
            LogOff();
            return;
        }

        DisableMe();

        $("#ctl00_PersonalisationBar1_apc").html(result);

        // Check to see what dynamic user control was loaded by querying for an item
        if ($("#SignUpUserName").val() == null) {
            $("#ctl00_PersonalisationBar1_apc").removeClass().addClass('actionPanelContainerLarge');
        }
        else {
            $("#ctl00_PersonalisationBar1_apc").removeClass().addClass('actionPanelContainerLargest');
        }

        // Show the action panel with animation
        $("#ctl00_PersonalisationBar1_apc").slideToggle("slow", function() {
            // Animation complete.
        });
    });
}

/*
------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------
*/
function CallbackSaveView(result) {
    $(document).ready(function() {
        var newResult = SaveViewErrorProcessor(result);

        if (newResult != undefined) {
            $("#ctl00_PersonalisationBar1_apc").slideToggle("slow", function() {
                $("#ctl00_PersonalisationBar1_apc").removeClass().addClass('actionPanelSmall');
                $("#ctl00_PersonalisationBar1_apc").html(result);
                $("#ctl00_PersonalisationBar1_apc").slideToggle("slow", function() {
                });
            });
        }
    });
}

/*
------------------------------------------------------------------------------------------------
This is just a placeholder function and doesnt need to have any functionality as the calling
method falls through to do more processing
------------------------------------------------------------------------------------------------
*/
function CallbackSaveDefaultPage(result) {
    $(document).ready(function() {
        if (result == "DATABASE_OFFLINE") {
            DatabaseNotOnline();
            EnableMe();
            return;
        }
        else if (result == "OFFLINE") {
            NotOnline();
            return;
        }
        // Do nothing
    });
}

/*
------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------
*/
function CallbackLoadPanelHTMLSaveView(result) {
    $(document).ready(function() {
        if (result == "DATABASE_OFFLINE") {
            DatabaseNotOnline();
            EnableMe();
            return;
        }
        $("#ctl00_PersonalisationBar1_apc").html("");
        $("#ctl00_PersonalisationBar1_barContents").html(result);
        EnableMe();

        // Let the animation finish before re-directing
        setTimeout("ScriptService.GetDefaultPage(CallbackDefaultPage)", 0);
    });
}

/*
------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------
*/
function CallbackLoadPanelHTMLSaveViewAfterLogin(result) {
    $(document).ready(function() {
        if (result == "DATABASE_OFFLINE") {
            DatabaseNotOnline();
            EnableMe();
            return;
        }

        $("#ctl00_PersonalisationBar1_barContents").html(result);

        ScriptService.GetControlHtmlSaveMyView("~/Uil/Controls/Personalisation/UpdatePanel/SaveView.ascx", viewType, CallBackLoadSaveViewPanel);
    });
}

/*
------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------
*/
function OnFailSaveMyView() {
    $(document).ready(function() {
        ScriptService.GetControlHtml("~/Uil/Controls/Personalisation/UpdatePanel/SignUpAJAX.ascx", CallbackLoadPanelHTML);
    });
}

/*
------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------
*/
function SetDropDownSelectedIndex() {
    $(document).ready(function() {
        selectedIndex = document.forms[0].ctl01_ddlMyViews.selectedIndex;
        document.forms[0].ctl01_ddlMyViews.selectedIndex = selectedIndex;
    });
}

/*
-------------------------------------------------------------------
Starts off the get my view selection process on My Views OnChange event
-------------------------------------------------------------------
*/
function GetMyViewFromDropDown() {
    $(document).ready(function() {
        var myView = $("#ctl01_ddlMySavedViews").val();
        // Handle the possiblity of shifting .Net client ID - TODO: Sort this out properly
        if (myView == null) {
            myView = $("#ctl00_PersonalisationBar1_persControl_ddlMySavedViews").val();
        }

        // Make sure user hasnt selected the default 'My Views'
        if (myView == 'My Saved Views') {
            return;
        }

        // Get the string length for our substring routine
        var stringLength = myView.length;
        // Take the view type from the substring routine to pass to the web service
        var viewType = myView.substring(stringLength - 1);
        // Take the view reocrd ID from the beginning of the substring
        var viewId = myView.substring(0, stringLength - 2);

        // Call the web service and return the traffic map view values
        if (viewType == 1) {
            ScriptService.GetMyMapView(viewId, CallBackGetMyMapView);
        }
        else if (viewType == 2) {
            GetMyMTFView(viewId, viewType);
        }
        else {
            GetMyDSView(viewId, viewType);
        }
    });
}

/*
-------------------------------------------------------------------
Takes the callback result string and delegates to GetMyMapView()
-------------------------------------------------------------------
*/
function CallBackGetMyMapView(result) {
    $(document).ready(function() {
        if (result == "DATABASE_OFFLINE") {
            DatabaseNotOnline();
            return;
        }
        else if (result == "OFFLINE") {
            NotOnline();
            return;
        }
        else {
            GetMyMapView(result);
        }
    });
}

/*
------------------------------------------------------------------------------------------------
Gets a users Traffic Map view and re-direct them to the map page if not on it
------------------------------------------------------------------------------------------------
*/
function GetMyMapView(result) {
    $(document).ready(function() {
        var mapViewArray = CreateKeyValueArray(result, "|");
        window.location = protocol + '//' + host + '/map.aspx?default=false&long0=' + mapViewArray["long0"] + '&lat0=' + mapViewArray["lat0"] + '&long1=' + mapViewArray["long1"] + '&lat1=' + mapViewArray["lat1"] + '&sd=' + mapViewArray["sd"] + '&ic=' + mapViewArray["ic"] + '&rw=' + mapViewArray["rw"] + '&aw=' + mapViewArray["aw"] + '&ms=' + mapViewArray["ms"] + '&tc=' + mapViewArray["tc"] + '&fe=' + mapViewArray["fe"] + '&fr=' + mapViewArray["fr"] + '&rc=' + mapViewArray["rc"] + "&hp=" + mapViewArray["hp"] + "&frc=" + mapViewArray["frc"] + "&fhp=" + mapViewArray["fhp"] + '&selectedview=' + mapViewArray["selectedview"] + "|1";
    });
}

/*
----------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------
*/
function GetMyMTFView(viewid, viewtype) {
    $(document).ready(function() {
        window.location = protocol + '//' + host + '/motorwayflow.aspx?default=false&viewid=' + viewid + '&selectedview=' + viewid + '|' + viewtype;
    });
}

/*
----------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------
*/
function GetMyDSView(viewid, viewtype) {
    $(document).ready(function() {
        window.location = protocol + '//' + host + '/disruptions.aspx?default=false&viewid=' + viewid + '&selectedview=' + viewid + '|' + viewtype;
    });
}

/*
----------------------------------------------------------------------------------------
Splits an input string into a key value pair array
----------------------------------------------------------------------------------------
*/
function CreateKeyValueArray(input, split) {
    var myArray = new Array();
    var splitter = input.split(split);

    for (var i = 0; i < splitter.length; i++) {
        // splits each of field-value pair
        var index = splitter[i].indexOf("=");
        var key = splitter[i].substring(0, index);
        var val = splitter[i].substring(index + 1);
        // saves each field-value pair in an array variable
        myArray[key] = val;
    }
    return myArray;
}

/*
----------------------------------------------------------------------------------------
Function to get round grouping radio buttons in repeater controls (multi-select problem)
----------------------------------------------------------------------------------------
*/
function SetUniqueRadioButton(nameregex, current) {
    re = new RegExp(nameregex);

    // S.F - 22/06/2010
    // Need to set another regex as the map mode selectors get overwritten otherwise
    r2 = new RegExp(/rblMapMode/);

    for (i = 0; i < document.forms[0].elements.length; i++) {
        elm = document.forms[0].elements[i]
        if (elm.type == 'radio') {
            if (re.test(elm.name) && !r2.test(elm.name)) {
                elm.checked = false;
            }
        }
    }
    current.checked = true;
}

/*
----------------------------------------------------------------------------------------------
Delete confirmation popup for delete checkbox, primarily used on the 'my personal views' page.
----------------------------------------------------------------------------------------------
*/
function confirmDelete(obj) {
    if (obj.checked) {
        if (confirm('Mark this view for deletion?')) {
            return true;
        }
        else {
            obj.checked = false;
            return false;
        }
    }
    else {
        return false
    }
}

/*
---------------------------------------------------------------------------
A handler to set a default button to the keydown event of an input textbox.
---------------------------------------------------------------------------
*/
function KeyDownDefaultButtonHandler(btn, e) {
    // process only the Enter key
    if (e.keyCode == 13) {
        // cancel the default submit
        e.returnValue = false;
        e.cancel = true;
        // submit the form by programmatically clicking the specified button
        btn.click();
    }
}

/*
---------------------------------------------------------------------------
Callback function used to get any custom user view layers. Called after a one
second timeout after the Navteq web service has initialsed.
---------------------------------------------------------------------------
*/
function GetMapLayers() {
    $(document).ready(function () {
        // Split the view coordinates into a useable array object
        var queryString = window.location.search;
        var trueQueryString = queryString.substring(1);
        var mapViewArray = CreateKeyValueArray(queryString, "&");

        /*------------- radio buttons that are set on by default ------------*/
        // Need to turn these off only if present in the query string, otherwise leave the defaults.
        if (mapViewArray["sd"] == "True") {
            $("#chkDelay").attr('checked', true);
            showDelayLayers();
        }
        else if (mapViewArray["sd"] != null) {
            hideDelayLayers();
            $("#chkDelayOff").attr('checked', true);
        }

        if (mapViewArray["ic"] == "True") {
            $("#chkIncidentsAndCongestion").attr('checked', true);
            showIncidentsAndCongestionLayers();
        }
        else if (mapViewArray["ic"] != null) {
            hideIncidentsAndCongestionLayers();
            $("#chkIncidentsAndCongestionOff").attr('checked', true);
        }

        if (mapViewArray["rc"] == "True") {
            $("#chkRoadClosures").attr('checked', true);
            showRoadClosureLayers();
        }
        else if (mapViewArray["rc"] != null) {
            hideRoadClosureLayers();
            $("#chkRoadClosuresOff").attr('checked', true);
        }

        if (mapViewArray["hp"] == "True") {
            $("#chkHighProfileEvents").attr('checked', true);
            showHighProfileEventLayers();
        }
        else if (mapViewArray["hp"] != null) {
            hideHighProfileEventLayers();
            $("#chkHighProfileEventsOff").attr('checked', true);
        }
        /*----------------------------------------------------------------*/

        if (mapViewArray["rw"] == "True") {
            $("#chkRoadworks").attr('checked', true);
            showRoadworksLayers();
        }
        else {
            hideRoadworksLayers();
        }
        if (mapViewArray["aw"] == "True") {
            $("#chkAdverseWeather").attr('checked', true);
            showAdverseWeatherLayers();
        }
        else {
            hideAdverseWeatherLayers();
        }

        if (mapViewArray["ms"] == "True") {
            $("#chkSignsOn").attr('checked', true);
            showRoadsideSignLayers();
        }
        else {
            hideRoadsideSignLayers();
        }
        if (mapViewArray["tc"] == "True") {
            $("#chkTrafficCamerasOn").attr('checked', true);
            showTrafficCameraLayers();
        }
        else {
            hideTrafficCameraLayers();
        }
        if (mapViewArray["fe"] == "True") {
            $("#chkFutureEventsOn").attr('checked', true);
            showFutureEventLayers();
        }
        else {
            hideFutureEventLayers();
        }
        if (mapViewArray["fr"] == "True") {
            $("#chkFutureRoadworksOn").attr('checked', true);
            showFutureRoadworksLayers();
        }
        else {
            hideFutureRoadworksLayers();
        }

        if (mapViewArray["frc"] == "True") {
            $("#chkFutureRoadClosures").attr('checked', true);
            showFutureRoadClosureLayers();
        }
        else {
            hideFutureRoadClosureLayers();
        }

        if (mapViewArray["fhp"] == "True") {
            $("#chkFutureHighProfileEvents").attr('checked', true);
            showFutureHighProfileEventLayers();
        }
        else {
            hideFutureHighProfileEventLayers();
        }
    });
}

/*
----------------------------------------------------------------------------------
check the covert captcha field for robot attacks.
----------------------------------------------------------------------------------
*/
function IsCovertCaptchaAttackPanel() {
    $(document).ready(function() {

        var covert = $("#txtCovertCaptchaPanel").val();

        if (covert != "") {
            alert('covert captcha detected robot attack on panel.');
            return true;
        }
        else {
            return false;
        }
    });
}

/*
----------------------------------------------------------------------------------
Does the user want to delete the MTF search?
----------------------------------------------------------------------------------
*/
function DeleteMTFConfirm() {
    var agree = confirm("Are you sure you want to delete this search?");

    if (agree) {
        return true;
    }
    return false;
}
