﻿function displayMessage(msg) {
    var cssClass = "";

    if (document.domain == "malmaison.com") {
        cssClass = "malmaison";
    }
    else if (document.domain == "hotelduvin.com") {
        cssClass = "HotelDuVin";
    }
    else {
        cssClass = "Smoak";
    }

    displayMessageBar(msg, cssClass, false);
}

function displayErrorBar(msg) {
    var cssClass = "";

    if (document.domain == "malmaison.com") {
        cssClass = "malmaison";
    }
    else if (document.domain == "hotelduvin.com") {
        cssClass = "HotelDuVin";
    }
    else {
        cssClass = "Smoak";
    }

    displayMessageBar(msg, cssClass, true);
}

function displayLoggedIn() {
    var cssClass = (document.domain == "malmaison.com") ? "malmaison" : "HotelDuVin";
    messageBar("You are now logged in", cssClass, false, 4000, true);
}

// display the message bar
function displayMessageBar(msg, classname, isError) {
    messageBar(msg, classname, isError, 8000, true);
}

// display the message bar
function displayTimedMessageBar(msg, classname, timeOut, isError) {
    messageBar(msg, classname, isError, timeOut, true);
}

// display message bar without closing
function displayStickyMessageBar(msg, classname, isError) {
    messageBar(msg, classname, isError, 999999999, false);
}

// display the message bar
function messageBar(msg, classname, isError, timeOut, showClose) {

    // hide any currently display bar
    $("#__notifyBar.sticky").hide();

    if (isError) {
        classname += " error";
    }

    if (!showClose) {
        classname += " sticky";
    }

    $.notifyBar({
        cls: classname,
        html: msg,
        delay: parseInt(timeOut),
        animationSpeed: 500,
        close: showClose
    });
}

// Used for highlighting/removing form field errors when an error notification is shown
function highlightFormErrors(errorIDs, flag) {
    var $ids = errorIDs.split(',');
    //
    if (flag) {
        $.each($ids, function (i, v) {
            $('#' + v).parent().addClass('validation-error');
        });
    } else {
        $.each($ids, function (i, v) {
            $('#' + v).parent().removeClass('validation-error');
        });
    }
}

function clearAllValidationHighlights() {
    $("#__notifyBar").hide();
    $('.validation-error').removeClass('validation-error');
}

function liveValidator() {
    $('.required').live('blur change', function () {
        if ($(this).val() != null && $(this).val().length > 0) {
            validationTypes($(this));
        }
    });
}

function submitValidator($parId, $eFlag, $msg, custom, messageCssClass, callback) {
    clearAllValidationHighlights();
    var f = "";
    $('#' + $parId + ' .required').each(function () {
        var $rt = validationTypes($(this));
        f = f + $rt;
    });

    var customVal = true;
    if (custom != null) {
        customVal = custom();
    }

    if (f.indexOf('e') == -1 && customVal) {
        if (callback != '') {

            eval(callback);
        }
        return true;
    } else {
        if ($eFlag) {
            if (!$("#__notifyBar").is(":visible")) {
                scrollToValidationError();
                displayMessageBar($msg, messageCssClass, true);
            }
        }
        return false;
    }
}

function scrollToValidationError() {
    var h = $(".validation-error:first");
    if (h != null) {
        $('html,body').animate({ scrollTop: h.offset().top - 100 }, 'slow');
    }
}

function validationTypes($el) {
    var regExDate = /^([0-9]){2}(\/|-){1}([0-9]){2}(\/|-)([0-9]){4}$/; // Date dd/mm/yyy 
    var regExEmail = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+$/; // Email a.a@a.com
    //
    var $rel = 0;
    if ($el.attr('rel')) {
        $rel = parseInt($el.attr('rel'));
    } else {
        $rel = 1;
    }
    // isDate - assuming dd/mm/yyyy format
    if ($el.hasClass('isDate')) {
        if (!regExDate.test($el.val())) {
            $el.parent().addClass('validation-error').removeClass('validated');
            return "e";
        } else {
            $el.parent().removeClass('validation-error').addClass('validated');
            return "-";
        }
    }
    // isInput - Generic for text values and selects must contain a string 1> in length
    if ($el.hasClass('isInput')) {
        if ($el.val().length < $rel) {
            $el.parent().addClass('validation-error').removeClass('validated');
            return "e";
        } else {
            $el.parent().removeClass('validation-error').addClass('validated');
            return "-";
        }
    }
    // isEmail
    if ($el.hasClass('isEmail')) {
        if (!regExEmail.test($el.val())) {
            $el.parent().addClass('validation-error').removeClass('validated');
            return "e";
        } else {
            $el.parent().removeClass('validation-error').addClass('validated');
            return "-";
        }
    }
    // isPassword
    if ($el.hasClass('isPassword')) {
        if ($el.val().length < $rel) {
            $el.parent().addClass('validation-error').removeClass('validated');
            return "e";
        } else {
            flag = "-";
            // Should password must be compared
            if ($el.attr('comparewithid')) {
                if ($el.val() == $('#' + $el.attr('comparewithid')).val()) {
                    flag = "-";
                } else {
                    flag = "e";
                }
            }
            if (flag == "-") {
                $el.parent().addClass('validated').removeClass('validation-error');
            } else {
                // Fail
                $el.parent().addClass('validation-error').removeClass('validated');
            }
            return flag;
        }
    }
}

function setDatePickersReadOnly() {
    $("input.isDate,input.hasDatePicker").each(function () {
        $(this).attr("readonly", "readonly");
    });
}

function showGenericPopupMessage(title, msg) {
    showTermsPopupMessage(title, msg, "");
}

function showTermsPopupMessage(title, msg, subtitle) {
    // set content
    $("#gPopupTitle").html(title);
    $("#gPopupText").html(msg);
    initCufon();

    //set terms only content
    if (subtitle != "") {
        $("#gPopupSubTitle").html(subtitle);
    }
    else {
        $("#termsOnlyTitle").hide();
    }

    // if the overlay has already been initialised we
    // just need to show it
    if ($("#genericPopup").data("initialised")) {
        $("#genericPopup").overlay().load();
    }
    else {
        // show popup
        $("#genericPopup").data("initialised", true);
        var col = (brandId == 0) ? "#111" : "#000";
        var op = (brandId == 0) ? 0.8 : 0.7;
        $("#genericPopup").overlay({
            fixed: false,
            mask: { color: col,
                loadSpeed: 200,
                opacity: op
            },
            load: true
        });
    }
}

var refreshDir = false;
var $locs;

function findDirections($grp) {
    if ($grp.length > 0) {
        $locs = new Array($('#' + $grp + ' #gmapDirStartPoint').val(), $('#' + $grp + ' #gmapDirEndPoint').val());
        refreshDir = true;
    } else {
        refreshDir = false;
        $grp = "";
    }
    // if the overlay has already been initialised we
    // just need to show it
    if ($('#gDirections-Wrap').data("initialised")) {
        $('#gDirections-Wrap').overlay().load();
    }
    else {
        $("#gDirections-Wrap").data("initialised", true);
        $('#gDirections-Wrap').overlay({
            // some mask tweaks suitable for modal dialogs
            fixed: false,
            mask: { color: '#111',
                loadSpeed: 1000,
                opacity: 0.8
            },
            load: true,
            onLoad: function () {
                // call external function for handle API query and avoid localising variables
                queryRoute();
            },
            onClose: function () { toggleSelects(true); },
            onBeforeLoad: function () { toggleSelects(false); }
        });
    }
}

function getDirections($grp) {
    $('#gDirections-Wrap').show();
    $("#gDirections-route p.loading").show();
    $("#gMapPrint").hide();
    $("#general-dir").slideUp("fast");
    if ($grp.length > 0) {
        $locs = new Array($('#' + $grp + ' #gmapDirStartPoint').val(), $('#' + $grp + ' #gmapDirEndPoint').val());
        refreshDir = true;
    } else {
        refreshDir = false;
        $grp = "";
    }
    queryRoute();
}

function queryRoute() {
    $('.gMapView-btn').show();
    if (refreshDir) {
        directionsDisplay.setPanel(document.getElementById("gDirections-route"));

        var start = $locs[0];
        var end = $locs[1];
        var request = new Object({
            origin: start,
            destination: end,
            unitSystem: google.maps.DirectionsUnitSystem.IMPERIAL,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        });
        directionsService.route(request, function (response, status) {
            $("#gDirections-route p.loading").hide();
            $("#gMapPrint").show();

            if (status == google.maps.DirectionsStatus.OK) {
                createCookie("gMapStart", start, null);
                directionsDisplay.setDirections(response);
            } else {
                $("#gDirections-route").children('div').remove();
            }
        });
    }
}

function printDirections() {
    var DocumentContainer = document.getElementById('gDirections-route');
    var WindowObject = window.open('', "TrackHistoryData",
                              "width=740,height=325,top=200,left=250,toolbars=no,scrollbars=yes,status=no,resizable=no");
    WindowObject.document.writeln('<style type="text/css">@import url(/css/gMap-print.css);</style>');
    WindowObject.document.writeln(DocumentContainer.innerHTML);
    WindowObject.document.close();
    WindowObject.focus();
    WindowObject.print();
    WindowObject.close();
}

// displays a banner if in test environment
function displayTestSystemLogo() {
    $("body").append("<div id='testEnvLogo'></div>");
}

// checks if valid flash player is installed
// - note : page must have reference to swfobject.js otherwise returns
// false
function hasValidFlashPlayer() {
    try {
        return (swfobject.hasFlashPlayerVersion("9.0.28"));
    }
    catch (e) { }
    return false;
}

// handle show/hide of selects for IE6 & below
function toggleSelects(b) {
    if (isIE6) {
        var $el = $("#mal > div:not([class*='modal']), #duVin > div:not([class*='modal'])").find('select');
        if (!b) {
            $el.css({ visibility: 'hidden' });
        }
        else {
            $el.css({ visibility: 'visible' });
        }
    }
}

// handle enter event on login pods (cross browser compatible)
function submitOnEnter(event, targetId) {
    if (event.keyCode == 13) {
        try {
            $("#" + targetId).click();
            if ($(".validation-error").length == 0) {
                eval($("#" + targetId).attr("href"));
            }
        }
        catch (e) { }
    }
}

// resend confirmation email
function resendRoomEmail(bookingRef) {
    // only check the entry if the field is valid
    try {
        $.ajax({
            url: getServiceUrl("BookingEngineService", "ResendRoomBookingEmail"),
            data: "{'bookingRef': '" + bookingRef + "'}",
            success: function (result) {
                if (result.d) {
                    $("a#lnkSendEmail").remove();
                    displayMessage("Your confirmation email has been resent.  You should received it within a few minutes");
                }
                else {
                    displayErrorBar("Unable to send email.");
                }
            }
        });
    }
    catch (e) { }
}

// resend confirmation email
function resendTableEmail(bookingRef) {
    // only check the entry if the field is valid
    try {
        $.ajax({
            url: getServiceUrl("BookingEngineService", "ResendTableBookingEmail"),
            data: "{'bookingRef': '" + bookingRef + "'}",
            success: function (result) {
                if (result.d) {
                    $("a#lnkSendEmail").remove();
                    displayMessage("Your confirmation email has been resent.  You should received it within a few minutes");
                }
                else {
                    displayErrorBar("Unable to send email.");
                }
            }
        });
    }
    catch (e) { }
}

// create cookie
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else {
        var expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function validateGVCheckout() {

    var css = (brandId) == 0 ? "malmaison" : "HotelDuVin";
    if (submitValidator('voucherForm', true, 'Please complete all of the required fields', null, css, 'null')) {
        if ($("#chkAgreeTC").is(':checked')) {
            $("#hidCheckout").val("submit");
            $("#frmMain").submit();
            $("#payPalSubmit").hide();
            $("#payPalBusy").show();
            return false;
        }
        else {
            $("#payPalSubmit .checkBoxContainer").addClass("validation-error");
            displayErrorBar("You must accept the terms and conditions before continuing with checkout");
        }
    }
    return false;
}

function getQuerystring(key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return default_;
    else
        return qs[1];
}

