﻿var allowRound = true;
var allowAnimation = false;

var hasChanges = false;
var hasChangesMessageText = null;
var menuItemRedirectAction = null;
var menuAnimateEnd = false;
var fadeInTimeout = 1000;
var hideTimeout = 500;
var showChangesMessage = true;
var loadingElementFadeInTimeout = 0;
var defaultMenuAction = null;
var mainMenuID = null;

function IsIE8() {
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
        var ieversion = new Number(RegExp.$1)
        if (ieversion < 8) {
            return true;
        }
    }
    return false;
}

$(function () {
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
        var ieversion = new Number(RegExp.$1)
        if (ieversion < 8) {
            allowRound = false;
        }
    }
});

function DataHasBeenChanged() {
    if (showChangesMessage) {
        hasChanges = true;
    }
}

function MenuItemClick(url) {
    var urlForConfirmNo = url;

    if (!hasChanges && !$("#ValidationSummary1").hasClass('validation-summary-errors')) {
        $("#LoadingElement").fadeIn(loadingElementFadeInTimeout);
        window.location.href = url;
    }
    else {
        /*Needed in case if user click in "Confirm changes" message to the "No" button, then we need to redirect him only to a page which available for this country*/
        if (mainMenuID != null && defaultMenuAction != null) {
            if ($(mainMenuID).html().indexOf(url) < 0) {
                urlForConfirmNo = defaultMenuAction;
            }
        }
        //Show "Confirm changes" message
        var messageText = rc_dataHasBeenChanged;
        if (hasChangesMessageText != null) {
            messageText = hasChangesMessageText;
        }
        CSMessageBox(messageText, "yes/no/cancel", null, "ConfirmChanges_YesClick('" + url + "')", "ConfirmChanges_NoClick('" + urlForConfirmNo + "')", null);
    }
}
function ConfirmChanges_NoClick(url) {
    window.location.href = url;
}

function ConfirmChanges_YesClick(url) {
    $("#RedirectToNextTab").val("True");
    menuItemRedirectAction = url;
    SubmitForm();
}

function CSStatusMessage(text, delay) {
    if (enableDebug) {
        $("#StatusElement").html(text);
        $("#StatusElement").fadeIn(500);
    }
}


function FixIE6Png() {
    //Fixes for IE6
//    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
//        var ieversion = new Number(RegExp.$1)
//        if (ieversion <= 6) {
//            $(document).ready(function () {
//                $(document).pngFix();
//            });
//        }
//    }
}

//$(function () {
//    FixIE6Png();
//});

function InitGlobal() {

    FixIE6Png();

    //Alternative table row colors
    $(".contentTable tr").removeClass("table-td-alternative");
    $(".contentTable tbody tr").not(":hidden").filter(":odd").not('not-alternative').addClass("table-td-alternative");

    $(".table tr").removeClass("table-td-alternative");
    $(".table tbody tr").not(":hidden").filter(":odd").not('not-alternative').addClass("table-td-alternative");

    //Alternative table row colors
    $(".contentTable-small tr").removeClass("contentTable-small-alternative");
    $(".contentTable-small tbody tr").not(":hidden").filter(":odd").not('not-alternative').addClass("contentTable-small-alternative");

    //Init mainmenu features
    jQuery('#MainMenu td').not('.MenuItemActive').hover(function () {
        $(this).css('background-repeat', 'repeat-x');
        $(this).css('background-position', 'right -117px');
        $(this).find('a').css('color', 'white');
    }, function () {
        $(this).css('background-repeat', 'repeat-x');
        $(this).css('background-position', 'right 0px');
        $(this).find('a').css('color', '#000000');
    });

    //Init buttons, blocks
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
        var ieversion = new Number(RegExp.$1)
        if (ieversion < 8) {
            $('.button-gray').css('display', 'inline');
            $('.button-gray').css('zoom', '1');
            $('.button-blue').css('display', 'inline');
            $('.button-blue').css('zoom', '1');
        }
    }

    //Init loading element position
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
        var ieversion = new Number(RegExp.$1)
        if (ieversion < 8) {
            $('#LoadingElement').css('position', 'absolute');
            $(window).scroll(function () {
                $('#LoadingElement').css('top', $(this).scrollTop() + "px");
            });
        }
    }

    //Init .href class
    $('.href').mouseover(function () {
        $(this).addClass('hover');
    });
    $('.href').mouseout(function () {
        $(this).removeClass('hover');
    });

    //Hover span link
    jQuery('.link').hover(function () {
        $(this).addClass('hover');
    }, function () {
        $(this).removeClass('hover');
    });

    //Init .tag class
    $('.tag').mouseover(function () {
        $(this).addClass('hover');
    });
    $('.tag').mouseout(function () {
        $(this).removeClass('hover');
    });
    $('.tag-gray').mouseover(function () {
        $(this).addClass('hover');
    });
    $('.tag-gray').mouseout(function () {
        $(this).removeClass('hover');
    });

    //Round tag
    $('.tag').corner('5px');
    $('.tag-gray').corner('5px');

    //Round tabs
    $('.tabs a').corner('5px top');

    //Round project steps
    $('.step').corner('5px');

    //Hover dropdown
    jQuery('.dropdown-item').hover(function () {
        $(this).stop().animate({ backgroundColor: '#84C1FF' });
    }, function () {
        $(this).stop().animate({ backgroundColor: 'white' });
    });

    //Set culture for datepicker
    var calendarCultureName = rc_current_culture; //rc_current_culture.substring(0, rc_current_culture.indexOf('-', 0));

    if (rc_current_culture == 'es-MX') {
        jQuery(function ($) {
            $.datepicker.regional[calendarCultureName] = { clearText: 'Limpiar', clearStatus: '',
                closeText: 'Cerrar', closeStatus: '',
                prevText: '&lt;Ant', prevStatus: '',
                nextText: 'Sig&gt;', nextStatus: '',
                currentText: 'Hoy', currentStatus: '',
                monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio',
            'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
                monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun',
            'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
                monthStatus: '', yearStatus: '',
                weekHeader: 'Sm', weekStatus: '',
                dayNames: ['Domingo', 'Lunes', 'Martes', 'Mi&eacute;rcoles', 'Jueves', 'Viernes', 'S&aacute;bado'],
                dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mi&eacute;', 'Juv', 'Vie', 'S&aacute;b'],
                dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'S&aacute;'],
                dayStatus: 'DD', dateStatus: 'D, M d',
                dateFormat: 'dd/mm/yy', firstDay: 0,
                initStatus: '', isRTL: false
            };
            $.datepicker.setDefaults($.datepicker.regional[calendarCultureName]);
        });
    }
    else if (rc_current_culture == 'en-IE') {
        jQuery(function ($) {
            $.datepicker.regional['en-IE'] = {
                closeText: 'Done',
                prevText: 'Prev',
                nextText: 'Next',
                currentText: 'Today',
                monthNames: ['January', 'February', 'March', 'April', 'May', 'June',
                        'July', 'August', 'September', 'October', 'November', 'December'],
                monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                        'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
                dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
                dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
                dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
                weekHeader: 'Wk',
                dateFormat: 'dd/mm/yy',
                firstDay: 1,
                isRTL: false,
                showMonthAfterYear: false,
                yearSuffix: ''
            };
            $.datepicker.setDefaults($.datepicker.regional['en-IE']);
        });

    }

    //Fix MainMenu Active item
    if (allowAnimation) {
        if (menuAnimateEnd) {
            $(".MenuItemActive").css("top", "0px");
        }
        else {
            //Animate MainMenu
            $(".MenuItemActive").css('top', '-37px');
            $(".MenuItemActive").delay(200).animate({ top: "0px" }, function () {
                menuAnimateEnd = true;
            });
        }
    }
    else {
        $(".MenuItemActive").css("top", "0px");
    }

    $(".popup-content").resize(function () {
        FixPositionOfCloseButton(false, 80);
    });

    if (!(/MSIE (\d+\.\d+);/.test(navigator.userAgent))) {
        LightMenuElement('#MainMenu td');
    }

    MonitorChanges();

    //Fix IE6 block issues
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
        var ieversion = new Number(RegExp.$1)
        if (ieversion < 8) {
            $('.step').css('display', 'inline');
            $('.step').css('zoom', '1');
            $('.step').css('width', '25px');

            var ibElements = $('.inline-block');
            $(ibElements).removeClass('inline-block', 'inline');
            $(ibElements).css('display', 'inline');
            $(ibElements).css('zoom', '1');

            
        }
    }
}

$(document).ready(function () {

    //Animate MainMenu
    $(".MenuItemActive").delay(200).animate({ top: "0px" }, function () {
        menuAnimateEnd = true;
    });

    //Animate h1, h2, h3, h4
    $(".note-red").hide().delay(500).show('clip', 1000);
    $(".note-gray").hide().delay(500).show('clip', 1000);
});

function MonitorChanges() {

    //Monitor content changes
    $("input").change(DataHasBeenChanged);
    $("textarea").change(DataHasBeenChanged);
    $("select").change(DataHasBeenChanged);

}

//Round div's
function RoundElements() {

    //Round div's
    if (allowRound) {

        /*Using this script IE support border but not support relative position*/
        //        DD_roundies.selectorsToProcess = [];
        //        DD_roundies.addRule('.roundedElement', '10px', true);
        //        DD_roundies.addRule('.roundedElementNoMargin', '10px', true);
        //        DD_roundies.addRule('.roundedElementPrimary', '10px 10px 0 0', true);
        //        DD_roundies.addRule('.roundedElementSecondary', '0 0 10px 10px', true);
        //        DD_roundies.addRule('.roundedElementSecondaryNoBG', '0 0 10px 10px', true);
        //        DD_roundies.addRule('.roundedElementSecondaryWhite', '0 0 10px 10px', true);
        //        DD_roundies.addRule('.roundedElementGray', '10px', true);
        //        DD_roundies.addRule('.roundedElementNoWidth', '10px 10px 10px 10px', true);
        //DD_roundies.addRule('.projectManager-report-box', '3px 3px 3px 3px', true);
        //InitDDRoundies();

        //$('.roundedElement').corner('10px');
        //$('.roundedElementNoMargin').corner('10px');
        //$('.roundedElementPrimary').corner('10px top');
        //$('.roundedElementSecondary').corner('10px bottom');
        //$('.roundedElementSecondaryNoBG').corner('10px bottom');
        //$('.roundedElementSecondaryWhite').corner('10px bottom');
        $('.roundedElementGray').corner('5px');
        //$('.roundedElementNoWidth').corner('10px');
    }
}

function InitDDRoundies() {
    var selectors = DD_roundies.selectorsToProcess;
    var length = selectors.length;
    var delayedCall = function (node, radii, index) {
        setTimeout(function () {
            DD_roundies.roundify.call(node, radii);
        }, index * 100);
    };
    for (var i = 0; i < length; i++) {
        var results = document.querySelectorAll(selectors[i].selector);
        var rLength = results.length;
        for (var r = 0; r < rLength; r++) {
            if (results[r].nodeName != 'INPUT') { /* IE8 doesn't like to do this to inputs yet */
                delayedCall(results[r], selectors[i].radii, r);
            }
        }
    }
}

function InitDropDown(id) {

    try {
        if ($('#' + id + 'Item' + $('#' + id + 'Hidden').val()).html().length > 90) {
            $('#' + id + 'Label').html($('#' + id + 'Item' + $('#' + id + 'Hidden').val()).html().substring(0, 89) + '...');
        }
        else {
            $('#' + id + 'Label').html($('#' + id + 'Item' + $('#' + id + 'Hidden').val()).html().substring(0, 89));
        }
    } catch (Error) { }
}

function AddCloseButtonForPopup(obj, closeCode, rightPosition, margin) {
    //Show close button
    if ($('#PopupClose' + obj.replace('#', '').replace('.', '')).length == 0) {
        var closeImg = $("<img class=\"popup-close-img\" onclick=\"ClosePopup('" + obj + "','" + closeCode + "')\" id=\"PopupClose" + obj.replace('#', '').replace('.', '') + "\" alt=\"\" src=\"" + rc_contentUrl + "/Images/Shared/close.png\" />");
        $(obj).parent().append(closeImg);
    }

    if (margin == null || margin == 'null' || margin == 'undefined') {
        margin = 0;
    }

    var top = $(obj).position().top - 15;
    var left = ($(obj).position().left) + $(obj).width() + 5 + margin;
    if (rightPosition != null && rightPosition != 'undefined' && rightPosition) {
        left = ($(obj).position().left - 15);
    }

    $('#PopupClose' + obj.replace('#', '').replace('.', '')).css("top", top);
    $('#PopupClose' + obj.replace('#', '').replace('.', '')).css("left", left);
    $('#PopupClose' + obj.replace('#', '').replace('.', '')).show();
}

function ClosePopup(obj, releaseCode) {
    if (releaseCode == null || releaseCode == 'null' || releaseCode == 'undefined') {
        $(obj).hide("fast");
    }
    $('#PopupClose' + obj.replace('#', '').replace('.', '')).fadeOut("fast");
    eval(releaseCode);
}

function FixPositionOfCloseButton(rightPosition, margin) {
    var obj = '.popup-content';
    if (margin == null || margin == 'null' || margin == 'undefined') {
        margin = 0;
    }

    var top = $(obj).position().top - 15;
    var left = ($(obj).position().left) + $(obj).width() + 5 + margin;
    if (rightPosition != null && rightPosition != 'undefined' && rightPosition) {
        left = ($(obj).position().left - 15);
    }

    $('.popup-close-img').css("top", top);
    $('.popup-close-img').css("left", left);
    $('.popup-close-img').show();
}

function ClosePopup(obj, releaseCode) {
    if (releaseCode == null || releaseCode == 'null' || releaseCode == 'undefined') {
        $(obj).hide("fast");
    }
    $('#PopupClose' + obj.replace('#', '').replace('.', '')).fadeOut("fast");
    eval(releaseCode);
}

function ClosePopups(releaseCode) {
    if (releaseCode == null || releaseCode == 'null' || releaseCode == 'undefined') {
        $('.popup-content').hide("fast");
    }
    $('.popup-close-img').remove();
    eval(releaseCode);
}

/*POPUP*/
function TogglePopup(obj, useCloseButton, useScroll) {
    $("body").append($(obj));
    if ($(obj).is(":hidden")) {
        ClosePopups();
        if (!IsIE8()) {
            $(obj).fadeIn(500);
        }
        else {
            $(obj).show();
        }
        $(obj).css('max-width', $("body").width() - 200 + 'px');
        $(obj).centerAbsolute(50);
        if (useScroll) {
            $(window).scrollTop($(obj).position().top - 15);
        }
        if (useCloseButton) {
            AddCloseButtonForPopup(obj, null, false, 80);
        }
        InitGlobal();
    }
    else {
        $(obj).hide();
        ClosePopup(obj);
    }

    RoundElements();
}

function FixPopupPosition(obj) {
    $(obj).css('max-width', $("body").width() - 200 + 'px');
    $(obj).width($(obj).width());
    $(obj).height($(obj).height());
    $(obj).centerAbsolute(50);
    $(window).scrollTop($(obj).position().top - 50);
}
/*END POPUP*/



function InsertTextAtCaret(areaId, text) {
    hasChanges = true;
    var txtarea = document.getElementById(areaId);
    var scrollPos = txtarea.scrollTop;
    var strPos = 0;
    var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?
		"ff" : (document.selection ? "ie" : false));
    if (br == "ie") {
        txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart('character', -txtarea.value.length);
        strPos = range.text.length;
    }
    else if (br == "ff") strPos = txtarea.selectionStart;

    var front = (txtarea.value).substring(0, strPos);
    var back = (txtarea.value).substring(strPos, txtarea.value.length);
    txtarea.value = front + text + back;
    strPos = strPos + text.length;
    if (br == "ie") {
        txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart('character', -txtarea.value.length);
        range.moveStart('character', strPos);
        range.moveEnd('character', 0);
        range.select();
    }
    else if (br == "ff") {
        txtarea.selectionStart = strPos;
        txtarea.selectionEnd = strPos;
        txtarea.focus();
    }
    txtarea.scrollTop = scrollPos;
}


function ShowTip(buttonID, descriptionID) {

    if ($('#' + descriptionID).is(":hidden")) {
        var top = ($("#" + buttonID).position().top + $("#" + buttonID).height);
        var left = ($("#" + buttonID).position().left - 50);
        $('#' + descriptionID).css('top', top + 'px');
        $('#' + descriptionID).css('left', left + 'px');
        $('#' + descriptionID).show();
    }else {
        $('#' + descriptionID).hide();
    }
    
}

/*JQUERY HELPERS*/
jQuery.fn.center = function () {
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
        var ieversion = new Number(RegExp.$1)
        if (ieversion < 8) {
            this.css("position", "absolute");
            this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
        }
        else {
            this.css("top", ($(window).height() - this.height()) / 2 + "px");
            this.css("position", "fixed");
        }
    }
    else {
        this.css("top", ($(window).height() - this.height()) / 2 + "px");
        this.css("position", "fixed");
    }
    this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
    return this;
}


/*JQUERY HELPERS*/
jQuery.fn.centerAbsolute = function (margin) {

    $("UpdateTarget").prepend(this);

    this.css("position", "absolute");
    var top = ($(window).height() - this.height()) / 2 + $(window).scrollTop();
    if (top < margin) {
        top = margin;
    }

    var left = ($(window).width() / 2 - this.width() / 2) - margin;
    this.css("top", top + "px");
    this.css("left", left + "px");

    return this;
}

function SetHeader(ownerID, noCache, force) {
    if (noCache == true) {
        var time = new Date();
        $('#Header').css("background-image", "url('" + rc_hostUrl + "/GetHeaderImage?ownerID=" + ownerID + "&noCache=" + time + "&force=" + force + "')");
    }
    else {
        $('#Header').css("background-image", "url('" + rc_hostUrl + "/GetHeaderImage?ownerID=" + ownerID + "&force=" + force + "')");
    }
}

$.fn.extend({
    // Calls the handler function if the user has clicked outside the object (and not on any of the exceptions)
    clickOutside: function (handler, exceptions) {
        var $this = this;

        $("body").bind("click", function (event) {
            if (exceptions && $.inArray(event.target, exceptions) > -1) {
                return;
            } else if ($.contains($this[0], event.target)) {
                return;
            } else {
                handler(event, $this);
            }
        });

        return this;
    }
});


/*::::::::::::::*/


function htmlEncode(value) {
    return $('<div/>').text(value).html();
}

function htmlDecode(value) {
    return $('<div/>').html(value).text();
}

function validateEmail(email) 
{
    filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (filter.test(email)) {
        // Yay! valid
        return true;
    }
    else
    { return false; }
}

function isInt(value) {
    if ((parseFloat(value) == parseInt(value)) && !isNaN(value)) {
        return true;
    } else {
        return false;
    }
}

function LightMenuElement(elName)
{
    // DOM Ready
    $(function () {

        var originalBGplaypen = $(elName).css("background-color"),
                            x, y, xy, bgWebKit, bgMoz,
                            lightColor = "rgba(255,255,255,0.75)",
                            gradientSize = 100;

        var originalBGplaypen2 = $(elName).css("background"),
                            x, y, xy, bgWebKit, bgMoz,
                            lightColor = "rgba(255,255,255,0.75)",
                            gradientSize = 100;

        // Basic Demo
        $(elName).not('.MenuItemActive').mousemove(function (e) {

            x = e.pageX - this.offsetLeft;
            y = e.pageY - this.offsetTop;
            xy = x + " " + y;

            bgWebKit = "-webkit-gradient(radial, " + xy + ", 0, " + xy + ", " + gradientSize + ", from(" + lightColor + "), to(rgba(255,255,255,0.0))), " + originalBGplaypen;
            bgMoz = "-moz-radial-gradient(" + x + "px " + y + "px 45deg, circle, " + lightColor + " 0%, " + originalBGplaypen + " " + gradientSize + "px)";

            $(this)
                                                .css({ background: bgWebKit })
                                                .css({ background: bgMoz });

        }).mouseleave(function () {
            $(this).css({ background: originalBGplaypen2 });
        });

    });
}
