﻿
//#region GlobalVariables

var varStatusMessage;
var varType;
var varUrl;
var varData;
var varProcessData;
var varSuccessFunction;
var varAsyc;
var varHideModalWhenDone = false;
var validationRules;

//#endregion GlobalVariables

$(document).ready(function () {
    GetValidationRules();
    PopulateEventHistory();
    PopulateEventTypes();
    SetEventLookupDefaults();
    SetRiskIndexThumbnails();
});


$(document).keyup(function (event) {
    if (event.keyCode == 13) {//enter key
        //whenever the user is in the login control, submit the login action
        if ($("input:focus").attr("id") == 'txtUserName' || $("input:focus").attr("id") == 'txtPassword') {
            BtnLoginClicked();
        }
//        //else if enter is clicked the event lookup is visible lookup events
//        else if ($('#eventLookup').is(":visible")) {
//            BtnLookupEventsClicked();
//        }
        return false;
    }
});

//#region CallWebServices

function callService() {
    var returnMessage;
    $.ajax(
    {
        type: "POST", //GET or POST or PUT or DELETE verb
        url: varUrl, // Location of the service
        data: JSON.stringify(varData), //Data sent to server
        contentType: "application/json; charset=utf-8", // content type sent to server
        dataType: "json", //Expected data format from server
        processdata: true, //True or False
        async: varAsyc, //True or False
        success: function (msg) {//On Successfull service call
            if (varSuccessFunction != null && varSuccessFunction != undefined && varSuccessFunction != '') {
                eval(varSuccessFunction + '(msg);');
            }
            else {
                returnMessage = msg;
            }
        },
        error: serviceFailed
    });

    varType = null; varUrl = null; varData = null; varProcessData = null; hideModalWhenDone = false;

    return returnMessage;
}

function serviceFailed(result) {
    varType = null; varUrl = null; varData = null; varProcessData = null; hideModalWhenDone = false;
    ShowNotificationMsg('Error connecting to web services', 'Error');
}

//#endregion


function SetRiskIndexThumbnails() {
    var curdate = new Date().toString();
    var randomQueryString = '?r=' + curdate.replace(/\s/g, ""); //will append this to the image url to ensure the rendered image is always the latest since the url will be unique
    $("#imgRiskIndexThumb").attr("src", "images/ClimateCast/Risk_Index_Number_US.jpg" + randomQueryString);
}

function GetValidationRules() {

    varType = "POST";
    varUrl = "Service.svc/GetValidationRules";
    varSuccessFunction = "GetValidationRulesComplete";
    varData = { "pageName": location.pathname.substring(1) };
    varContentType = "application/json; charset=utf-8";
    varDataType = "json";
    varProcessData = true;
    varAsyc = false;
    hideModalWhenDone = true;
    callService();
}

function GetValidationRulesComplete(result) {
    validationRules = result.GetValidationRulesResult;
}


function Validate(action) {
    var isValid = true;
    ClearErrorMessages();

    for (var i = 0; i < validationRules.length; i++) {
        if (validationRules[i].Action == action) {
            var validationRule = validationRules[i];

            for (var j = 0; j < validationRule.Fields.length; j++) {
                $(validationRule.Fields[j].Selector).each(function (i) {
                    if (!this.value.match(validationRule.Fields[j].Test)) {
                        var fieldToValidate = validationRule.Fields[j].Selector;
                        $(this).addClass("required");
                        if (validationRule.Fields[j].Message != '') {
                            $(fieldToValidate).parent().append("<div class='required'>" + validationRule.Fields[j].Message + "</div>");
                        }
                        isValid = false;
                    }
                });
            }
        }
    }

    return isValid;
}

function ClearErrorMessages() {
    $.each($("input[class*='required']"), function (i, v) {
        $(v).removeClass("required");
    });

    $.each($("select[class*='required']"), function (i, v) {
        $(v).removeClass("required");
    });

    $.each($("div[class*='required']"), function (i, v) {
        $(v).remove();
    });

    $.each($("span[class*='required']"), function (i, v) {
        $(v).remove();
    });

}

//#region EventLookup

function SetEventLookupDefaults() {

    if ($.cookie("eventTypeId") != null) {
        $("#ddlEventTypes").val($.cookie("eventTypeId"));
    }

    if ($.cookie("eventHistoryId") != null) {
        $("#ddlEventHistory").val($.cookie("eventHistoryId"));
    }

    AddRemoveAllPerilsOption();
    AddRemoveAllYearsOption();
}

function PopulateEventTypes() {
    varType = "POST";
    varUrl = "Service.svc/PopulateEventTypes";
    varSuccessFunction = "PopulateEventTypesComplete";
    varProcessData = true;
    varAsyc = false;
    hideModalWhenDone = true;
    callService();
}

function PopulateEventTypesComplete(result) {
    ShowNotification(result.notification);
    var eventTypes = result.PopulateEventTypesResult;
    $.each(eventTypes, function () {
        $("<option />").val(this.Value).text(this.Name).appendTo("#ddlEventTypes");
    });
}

function PopulateEventHistory() {
    varType = "POST";
    varUrl = "Service.svc/PopulateEventHistory";
    varSuccessFunction = "PopulateEventHistoryComplete";
    varProcessData = true;
    varAsyc = false;
    hideModalWhenDone = true;
    callService();
}

function PopulateEventHistoryComplete(result) {
    ShowNotification(result.notification);
    var eventHistory = result.PopulateEventHistoryResult;
    $.each(eventHistory, function () {
        $("<option />").val(this.Value).text(this.Name).appendTo("#ddlEventHistory");
    });

}


function SetEventCookies() {
    $.cookie("defaultLookup", false)
    $.cookie("eventTypeId", $("#ddlEventTypes").val())
    $.cookie("eventHistoryId", $("#ddlEventHistory").val())
}

function EventHistoryChanged() {
    AddRemoveAllPerilsOption();
    SetEventCookies();
    if (IsEventLookupListVisible()) {
        GetAlertEventsList();
    }
}

function EventTypeChanged() {
    AddRemoveAllYearsOption();
    SetEventCookies();
    if (IsEventLookupListVisible()) {
        GetAlertEventsList();
    }
}

function AddRemoveAllPerilsOption() {
    //if all years remove all perils from events
    if ($("#ddlEventHistory").val() == 9) {//all years
        $("#ddlEventTypes option[value=0]").remove(); //all perils removed
    }
    else {
        //add all perils if it doesn't exists
        if ($('#ddlEventTypes option[value=0]').length == 0) { //all perils doesn't exists, add it
            $("<option />").val(0).text('All Perils').prependTo("#ddlEventTypes");
        }
    }
}

function AddRemoveAllYearsOption() {
    //if all perils remove all years from event history
    if ($("#ddlEventTypes").val() == 0) {//all perils
        $("#ddlEventHistory option[value=9]").remove();
    }
    else {
        //add all years if it doesn't exists
        if ($('#ddlEventHistory option[value=9]').length == 0) { //all years doesn't exists, add it
            $("<option />").val(9).text('All Years').appendTo("#ddlEventHistory");
        }
    }
}



function GetAlertEventsList() {

    $('#eventLookupListTable').show();
    var eventTitle = $("select[id$='ddlEventHistory'] :selected").text() + " " + $("select[id$='ddlEventTypes'] :selected").text();
    $('#eventLookupListTitle').html(eventTitle);

    if ($.cookie("eventTypeId") == null) {
        $.cookie("eventTypeId", 0)
    }

    if ($.cookie("eventHistoryId") == null) {
        $.cookie("eventHistoryId", 1)
    }

    var defaultLookup = true;

    if ($.cookie("defaultLookup") != null) {
        defaultLookup = $.cookie("defaultLookup");
    }

    DisplayLoadingAnimation();
    varType = "POST";
    varUrl = "Service.svc/GetAlertEventsList";
    varSuccessFunction = "GetAlertEventsListComplete";
    varData = { "eventTypeID": $.cookie("eventTypeId"), "eventHistoryID": $.cookie("eventHistoryId"), "getDefaultEvents": defaultLookup };
    varProcessData = true;
    varAsyc = true;
    hideModalWhenDone = true;
    callService();
}

function GetAlertEventsListComplete(result) {
    HideLoadingAnimation();
    ShowNotification(result.notification);
    var eventListHtml = result.GetAlertEventsListResult;
    if (eventListHtml == '') {
        eventListHtml = "<b>The event filters that you selected did not return any results.  Please adjust your selections.</b>";
    }
    //$('#eventLookupList').hide().html(eventListHtml).fadeIn("slow");
    $('#eventLookupList').html(eventListHtml);
}

//#endregion

//#region GrowlNotification

function ShowNotification(notification) {

    if (notification.Message == '') return;

    var bgColor = '#66B366';
    if (notification.NotificationType == 1) bgColor = '#FF6666'; //error
    $('<div class="growlNotice"></div>')
        .append('<div class="growlSkin" style="background-color: ' + bgColor + '"></div>')
        .append('<span class="growlClose">close</span>')
        .append($('<div class="growlContent"></div>').html('<p>' + notification.Message + '</p>'))
        .hide()
        .appendTo('#growl')
        .show();

    $('.growlNotice').delay(3000).fadeOut();

    $('.growlClose').click(function () {
        $(this).closest('.growlNotice').remove();
    });

}

function ShowNotificationMsg(msg, notificationType) {

    if (notificationType == 'Success')
        notificationType = 0;
    else if (notificationType == 'Error')
        notificationType = 1;

    var notification = {
        "Message": msg,
        "NotificationType": notificationType
    }
    ShowNotification(notification);
}


//#endregion

//#region ButtonClicks

function BtnLookupEventsClicked() {

    $.cookie("defaultLookup", false); //set the default lookup to false once the lookup button is clicked.
    var locationPath = location.pathname.toLowerCase();

    //if not on the default page, redirect to the default page.
    if (locationPath.indexOf('default.aspx') == -1) {
        window.location.href('default.aspx');
    }
    else {
        GetAlertEvents(); //function is in default.js 
    }

}

function BtnClearClicked() {
    $("#txtUserName").val('');
    $("#txtPassword").val('');
}



//#endregion

//#region Login/Logout

function BtnLoginClicked() {

    if (!Validate("Login")) return;

    var rememberMe = false;
    if ($('#chkRememberMe:checked').val() !== undefined) {
        rememberMe = true;
    }
    DisplayLoadingAnimation();
    varType = "POST";
    varUrl = "Service.svc/Login";
    varSuccessFunction = "LoginComplete";
    varData = { "userName": $("#txtUserName").val(), "password": $("#txtPassword").val(), "rememberMe": rememberMe };
    varProcessData = true;
    varAsyc = true;
    hideModalWhenDone = true;
    callService();
}

function LoginComplete(result) {
    HideLoadingAnimation();
    ShowNotification(result.notification);
    var loggedIn = result.LoginResult;
    if (loggedIn) {
        //if logged in set the cookie

        if ($('#chkRememberMe:checked').val() !== undefined) {
            $.cookie("UserID", $("#txtUserName").val(), { expires: 1 });
        }
        else {
            $.cookie("UserID", $("#txtUserName").val());
        }

        $('#aboutHelpLink').show();
        $('#loginBox').fadeOut();
        $('<span>Welcome ' + $.cookie("UserID") + ' &nbsp;&nbsp;<a href="Logout.aspx" onclick="Logout();">Log Out</a></span><br />').prependTo('#today');

        //window.location = 'default.aspx';
    }
    else {
        //redirect to the login page
        var queryString = "?m=0&err=" + result.errorCode;
        window.location = 'login.aspx' + queryString;
    }
}


function Logout() {
    $.cookie("UserID", null);
}


//#endregion

//#region Misc

function IsEventLookupListVisible() {
    return $('#eventLookupListTable').is(":visible");
}


function DisplayLoadingAnimation() {

    $('#pageDialog').dialog({ autoOpen: false, modal: true, draggable: false, resizable: false, width: 265, height: 110 });
    $('#pageDialog').html('<div border="0" style="width: 100%; height: 100%; text-align: center; vertical-align: middle;"><img src="images/icons/loading.gif" width="250" height="100" /></div>');
    $('#pageDialog').dialog('open');
}

function HideLoadingAnimation() {
    $('#pageDialog').dialog('close');
}

function UserLoggedIn() {
    if ($.cookie("UserID") == null || $.cookie("UserID") == '')
        return false;
    else
        return true;
}

function GetErrorMessage(errorCode) {
    varType = "POST";
    varUrl = "Service.svc/GetErrorMessage";
    varSuccessFunction = "";
    varData = { "errorCode": errorCode };
    varProcessData = true;
    varAsyc = false;
    hideModalWhenDone = true;
    var result = callService();
    ShowNotification(result.notification);
    return result.GetErrorMessageResult;
}


function CheckMaxLength(id, length) {
    var field = document.getElementById(id);
    if (field) {
        if (field.value.length >= length)
            field.value = field.value.substring(0, length);
    }
}


//#endregion

//#region Default.js code

/* Start General Code */
function centerProgressModal(updateProgressControlID, updateProgressDiv) {

    // debugger;
    // Sys.UI.DomElement.setLocation(updateProgressDiv, 0, 0);
    var updateProgressControl = $get(updateProgressControlID);
    var updateProgressDiv = $get(updateProgressDiv);

    //Change the display stype of both the progress div as well as the UpdateProgress control, otherwise
    //the offsetWidth/Height will both be 0, and the progress indicator will not center on the page
    updateProgressControl.style.display = '';
    updateProgressDiv.style.display = '';

    //Find the page dimensions
    var scrollX = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;
    var scrollY = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;

    var windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
    var windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;

    var x = Math.round(windowWidth / 2 - updateProgressDiv.offsetWidth / 2) + scrollX;
    var y = Math.round(windowHeight / 2 - updateProgressDiv.offsetHeight / 2) + scrollY;

    //position the progress indicator element
    Sys.UI.DomElement.setLocation(updateProgressDiv, x, y);
}

function showPopup(currentControl, targetDiv, position) {

    var popupDiv = $get(targetDiv);

    popupDiv.style.display = '';

    var boundsTarget = Sys.UI.DomElement.getBounds(currentControl);
    var boundsPopup = Sys.UI.DomElement.getBounds(popupDiv);

    var x = boundsTarget.x;
    var y = boundsTarget.y + boundsTarget.height;

    if (position == 'above') {
        x = boundsTarget.x;
        y = boundsTarget.y - boundsPopup.height;
    }

    Sys.UI.DomElement.setLocation(popupDiv, x, y);
}

function hidePopup(targetDiv) {

    var popupDiv = $get(targetDiv);
    popupDiv.style.display = 'none';
}


function openWindow(strURL, intWidth, intHeight, strWindowName, strScrollBars, intOffsetLeft, intOffsetTop, strFeatures) {
    if (typeof (strWindowName) == 'undefined') strWindowName = "PopUpWin";
    if (typeof (strScrollBars) == 'undefined') strScrollBars = "1";

    var intLeft = (((screen.width - intWidth) / 2));
    var intTop = (((screen.height - intHeight) / 2) - 25);

    if (typeof (intOffsetLeft) != 'undefined') intLeft += intOffsetLeft;
    if (typeof (intOffsetTop) != 'undefined') intTop += intOffsetTop;

    // Added to allow override of window features/options
    if (typeof (strFeatures) == 'undefined') {
        strFeatures = "toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=" + strScrollBars + ",resizable=1";
    }

    strFeatures += ",left=" + intLeft + ",top=" + intTop;
    strFeatures += ",width=" + intWidth + ",height=" + intHeight;

    winPopUp = window.open(strURL, strWindowName, strFeatures);
    setTimeout("winPopUp.focus()", 50);

    return winPopUp;
}

function findPosX(obj) {
    var curleft = 0;

    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;

        }
        while (obj = obj.offsetParent);
    }

    return curleft;
}

function findPosY(obj) {
    var curtop = 0;

    if (obj.offsetParent) {
        do {
            curtop += obj.offsetTop;
        }
        while (obj = obj.offsetParent);
    }

    return curtop;
}

function writeCookieEx(strName, strValue, intDays) {
    if (intDays) {
        var date = new Date();
        date.setTime(date.getTime() + (intDays * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else {
        var expires = "";
    }

    document.cookie = strName + "=" + strValue + "; path=/";
}

function readCookieEx(strName, strDefault) {
    var strNameEQ = strName + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1, c.length);
            if (c.indexOf(strNameEQ) == 0) {
                return c.substring(strNameEQ.length, c.length);
            }
        }
    }
    return strDefault;
}

/* End General Code */


/* Start TimePeriodTable Code */

function hideUnhideInstructions(nodeID, imgID) {
    var nodeID = document.getElementById(nodeID);
    var imgPM = document.getElementById(imgID);

    if (nodeID.className == "hidden") {
        nodeID.className = "shown";
        imgPM.src = "images/minus.gif";
    }
    else {
        nodeID.className = "hidden";
        imgPM.src = "images/plus.gif";
    }
}

function expandCollapseTimePeriods(eventTimePeriodID, eventCreator, clicked) {
    var lastState = readCookieEx("closeMore", '');

    if (lastState == '') //default to closed
    {
        lastState = "closed";
    }

    if (clicked) //Set change state
    {
        if (lastState == "opened") {
            closeMore();
            writeCookieEx("closeMore", "closed", "");
        }

        if (lastState == "closed") {
            openMore();
            writeCookieEx("closeMore", "opened", "");
        }
    }
    else //Set last state
    {
        if (lastState == "opened") {
            openMore();
        }

        if (lastState == "closed") {
            closeMore();
        }
    }
}

function openMore(hideableNames, closeMoreButton) {
    var hideableNames = document.getElementById('time-period-table').getElementsByTagName('tr');
    var closeMoreButton = document.getElementById('close-more');

    for (i = 5; i < hideableNames.length; i++) //change the i to change the number of rows exposed
    {
        if (navigator.appName.indexOf("Microsoft") > -1) //IE
        {
            hideableNames[i].style.display = "block";
        }
        else //Mozilla/Firefox
        {
            hideableNames[i].style.display = 'table-row';
        }

        closeMoreButton.innerHTML = "&#160;&#160;<img id='close-more-img' class='close-more-img' src='images/up.gif'/>&#160;&#160;&#160;&#160;&#160;Close&#160;&#160;&#160;&#160;&#160;";
    }
}

function closeMore(closeMoreButton) {
    var hideableNames = document.getElementById('time-period-table').getElementsByTagName('tr');
    var closeMoreButton = document.getElementById('close-more');

    for (i = 5; i < hideableNames.length; i++) //change the i to change the number of rows exposed
    {
        hideableNames[i].style.display = "none";
        closeMoreButton.innerHTML = "&#160;&#160;<img id='close-more-img' class='close-more-img' src='images/down.gif'/>&#160;&#160;&#160;&#160;&#160;More&#160;&#160;&#160;&#160;";
    }
}

function colorSelected(eventTimePeriodID, eventCreator) {
    var getEventCreator = eventTimePeriodID + eventCreator;
    document.getElementById(getEventCreator).className = "colorSelected";
}

/* End TimePeriodTable Code */

/* Start Scenario Navigator Code */

function openNavagator(strURL) {
    var secondwindow;
    secondwindow = window.open(strURL, 'ScenarioNavigator', 'height=700, width=700, scrollbars=yes, menubar=no, toolbar=no, resizable=yes');
}

/* End Scenario Navigator Code */

/* Start Help Library Code */

function showHelpLibrary() {
    openWindow('help/default.htm', 780, 500, 'HelpLibrary', "1", 0, 0, 'toolbar=1,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1');
}

/* End Help Library Code */

/* Start Menu Code */

var tabAboutTimer;
var tabPerilsTimer;
var tabModelingTimer;

function hideUnhide(nodeID, classCss, parentObj) {
    var parentLeft = findPosX(parentObj);
    var parentTop = findPosY(parentObj);

    var node = document.getElementById(nodeID);
    node.className = classCss;
    node.style.top = (parentTop + 36) + "px"; //36 is a "magic number". If UI is adjusted, this needs to be changed.
    node.style.left = (parentLeft + 10) + "px"; //10 is a "magic number". If UI is adjusted, this needs to be changed.

    if (nodeID == "tab-about") {
        document.getElementById("tab-perils").className = "hidden";
        document.getElementById("tab-modeling").className = "hidden";
    }

    if (nodeID == "tab-perils") {
        document.getElementById("tab-about").className = "hidden";
        document.getElementById("tab-modeling").className = "hidden";
    }

    if (nodeID == "tab-modeling") {
        document.getElementById("tab-perils").className = "hidden";
        document.getElementById("tab-about").className = "hidden";
    }
}

function startTimer(nodeID) {
    var milliSeconds = 300; //this sets the mouseover timer

    if (nodeID == 'tab-about') {
        tabAboutTimer = window.setTimeout("closeMenu('" + nodeID + "')", milliSeconds);
    }

    if (nodeID == 'tab-perils') {
        tabPerilsTimer = window.setTimeout("closeMenu('" + nodeID + "')", milliSeconds);
    }

    if (nodeID == 'tab-modeling') {
        tabModelingTimer = window.setTimeout("closeMenu('" + nodeID + "')", milliSeconds);
    }
}

function closeMenu(nodeID) {
    document.getElementById(nodeID).className = "hidden";
}

function killTimer(nodeID) {
    if (nodeID == 'tab-about') {
        window.clearTimeout(tabAboutTimer);
    }

    if (nodeID == 'tab-perils') {
        window.clearTimeout(tabPerilsTimer);
    }

    if (nodeID == 'tab-modeling') {
        window.clearTimeout(tabModelingTimer);
    }
}

/* End Menu Code */

/* FeePrompt.aspx */

function FeeForm_Validator(confirmCheckBox) {
    var accepttrue = document.getElementById("accept");
    var agreementValue = document.getElementById("agreement");

    switch (confirmCheckBox.checked) {
        case true:
            accepttrue.disabled = false;
            agreementValue.value = "Accept";
            break;
        case false:
            accepttrue.disabled = true;
            agreementValue.value = "Decline";
            break;
    }
}

/* End FeePrompt.aspx */

/* Validation Functions */

function ValidateChecked(oSrc, args) {
    debugger;

    if (document.all[controlToValidate].checked == false) {
        args.IsValid = false;
    }
}

/* End Validation Functions */

//#endregion Default.js code


