﻿/// <reference path="jquery-1.4.2.js" />
/// <reference path="jquery-1.4.2-vsdoc.js" />
function selectMenu(sender) {
    var menuItem = sender.attr("class");

    //show the relevant menu
    $("#masterMenu div").hide();
    $("#masterMenu div." + menuItem).show();

    //highlight the selected menuItem
    $("#menuList li.selected").removeClass("selected");
    sender.addClass("selected");
}

$(document).ready(function () {
    //*******MasterPage scripts*******

    //preload images for Main Menu
    (function ($) {
        var cache = [];
        // Arguments are image paths relative to the current page.
        $.preLoadImages = function () {
            var args_len = arguments.length;
            for (var i = args_len; i--; ) {
                var cacheImage = document.createElement('img');
                cacheImage.src = arguments[i];
                cache.push(cacheImage);
            }
        }
    })(jQuery)

    //jQuery.preLoadImages('images/layout/menu/main_over.jpg', 'images/layout/menu/main_on.jpg', 'images/layout/menu/forum_over.jpg', 'images/layout/menu/forum_on.jpg', 'images/layout/menu/downloads_over.jpg', 'images/layout/menu/downloads_on.jpg', 'images/layout/menu/hebrew_over.jpg', 'images/layout/menu/hebrew_on.jpg', 'images/layout/menu/fm2010_over.jpg', 'images/layout/menu/fm2010_on.jpg', 'images/layout/menu/fm2011_over.jpg', 'images/layout/menu/fm2011_on.jpg', 'images/layout/menu/fmhandheld_over.jpg', 'images/layout/menu/fmhandheld_on.jpg', 'images/layout/menu/research_over.jpg', 'images/layout/menu/research_on.jpg');

    //define Dialog for all pages
    $("#divMainDialog").dialog({
        autoOpen: false,
        title: "כותרת",
        modal: true,
        resizable: false
    });

    //set "datepicker" plugin for all relevant textboxes
    $(".dateTextbox").datepicker({
        dateFormat: 'dd/mm/yy',
        dayNamesMin: ['א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ש'],
        monthNames: ['ינואר', 'פברואר', 'מרץ', 'אפריל', 'מאי', 'יוני', 'יולי', 'אוגוסט', 'ספטמבר', 'אוקטובר', 'נובמבר', 'דצמבר'],
        prevText: 'הקודם',
        nextText: 'הבא',
        changeYear: true,
        yearRange: '1960:2010',
        showAnim: 'fadeIn',
        isRTL: true
    });

    //dialog for password recovery
    var dialog = $("#divPassword").dialog(
    {
        title: 'שחזור משתמש/סיסמה',
        autoOpen: false,
        resizable: false,
        modal: true,
        width: 400
    });

    dialog.children().show();

    //open the Password dialog
    $("a#lnkPassword").click(function () {
        $('#divPassword').dialog('open');

        //append the dialog to the ASP.NET form (by default, it is seperated)
        $("#divPassword").parent().appendTo($("form:first"));

        return false;
    });

    $("[id$='btnRecoverPassword']").click(function () {
        $("#divRecoverPasswordValidators").show();
    });

    //dialog for login
    var dialog = $("#divLoginDialog").dialog(
    {
        title: 'התחבר לאתר',
        autoOpen: false,
        resizable: false,
        modal: true,
        width: 400
    });

    //open the Login dialog
    $("a#lnkLogin").click(function () {
        $('#divLoginDialog').dialog('open');

        //append the dialog to the ASP.NET form (by default, it is seperated)
        $("#divLoginDialog").parent().appendTo($("form:first"));

        return false;
    });

    var inprog = 0;

    //small menus - AddItems - הוסף לאתר
    if ($("#lnkAddItems").length > 0) {
        var position = $("#lnkAddItems").position();
        position.top += $("#lnkAddItems").height();
        position.left += $("#lnkAddItems").width() - $("#divAddItems").width();
        $("#divAddItems").css({ left: position.left, top: position.top });

        $("#divMenuAddItems").hover(function () {
            if (inprog == 0) {
                inprog = 1;
                $("#divAddItems").slideDown();
            }
        }, function () {
            $("#divAddItems").slideUp(400, function () { inprog = 0; });
        });
    }

    var inprog2 = 0;

    //small menus - UserOptions - אפשרויות משתמש
    if ($("#lnkUserOptions").length > 0) {
        var position = $("#lnkUserOptions").position();
        position.top += $("#lnkUserOptions").height();
        position.left += $("#lnkUserOptions").width() - $("#divUserOptions").width();
        $("#divUserOptions").css({ left: position.left, top: position.top });

        $("#divMenuUserOptions").hover(function () {
            if (inprog2 == 0) {
                inprog2 = 1;
                $("#divUserOptions").slideDown();
            }
        }, function () {
            $("#divUserOptions").slideUp(400, function () { inprog2 = 0; });
        });
    }

    /*Random Content Interval
    -------------------------*/

    //show random content in the left header box (Blogs/Articles/Downloads...)
    var overRandomContentDiv = false;
    var timer;
    timer = window.setInterval(ChangeRandomContent, 5000);

    //overRandomContentDiv = whether the user is hovering the RandomContent div
    $("#divRandomContent").hover(function () {
        overRandomContentDiv = true;
    }, function () {
        overRandomContentDiv = false;
    });

    function ChangeRandomContent() {
        //if the user is not hover the div
        if (overRandomContentDiv == false) {
            var randomnumber = Math.floor(Math.random() * 4);

            //get all random content boxes
            var contentBoxes = $("[id^='divLatestContent_']");
            var currentlyVisibleBox = contentBoxes.index($("[id^='divLatestContent_']:visible"));

            //hide current boxes and show new content box (only if different from current box)
            if (currentlyVisibleBox != randomnumber) {
                contentBoxes.hide();
                contentBoxes.eq(randomnumber).stop(true, true).fadeIn('slow');
            }
        }
    }

    /*Blur and Focus events
    -----------------------*/

    //define events for Focus and Blur of the document
    /*if (false) {
    document.onfocusin = onFocus;
    document.onfocusout = onBlur;
    } else {
    window.onfocus = onFocus;
    window.onblur = onBlur;
    }

    //clear the slider timeout when bluring the document
    function onBlur() {
    clearInterval(timer);
    clearInterval(timerForum);
    };
    //redefine the slider timeout when focusing back
    function onFocus() {
    timer = window.setInterval(ChangeRandomContent, 5000);
    timerForum = window.setInterval(ChangeForumPosts, 5000);
    };*/

    /*Buttons
    ----------*/

    //define hover events for buttons
    $(".DarkMenuHeader").hover(function () {
        $(this).addClass("DarkMenuHeaderOver");
    }, function () {
        $(this).removeClass("DarkMenuHeaderOver");
    });

    $("#menuList li").click(function () {
        selectMenu($(this));
    });
    //*******MasterPage scripts*******


    //ucDateSelector - on each change of Year/Month/Day - update the relevant Textbox
    $("select[id$='ddl_Year'],select[id$='ddl_Month'],select[id$='ddl_Day']").change(function () {
        var selectedYear = $(this).parent().find("select[id$='ddl_Year']").val();
        var selectedMonth = $(this).parent().find("select[id$='ddl_Month']").val();
        var selectedDay = $(this).parent().find("select[id$='ddl_Day']").val();

        $(this).parent().find("[id$='txt_Date']").val(selectedDay + '/' + selectedMonth + '/' + selectedYear);
    });

    //add class to the validators
    $("span[id*='Validator'],span[id*='vld']").addClass("validator");

    //put tooltip to the admin and pms icons
    $(".pmsIcon,.adminIcon").tooltip({ effect: 'slide', predelay: 100, position: 'bottom center', offset: [20, 0] });
    $(".richeditor [title!='']").tooltip({ effect: 'slide', predelay: 100, position: 'top center', offset: [10, 0] });

    /*START - dialog for update profile reminder
    --------------------------------------*/
    if ($("[id$='hdnShowProfileDialog']").val() == "true") {
        var dialog = $("#divUpdateProfileDialog").dialog(
            {
                title: 'עדכון פרופיל אישי',
                autoOpen: true,
                resizable: false,
                modal: true,
                width: 500
            });
    }

    $("#CloseProfileDialog").click(function () {
        //Invoke AJAX method to update the last login
        AjaxWebService.SetUpdateProfileCookie(UpdateLastLogin_success, ajaxError);
        $("#divUpdateProfileDialog").dialog("close");
    });

    $("#UpdateProfile").click(function () {
        window.location = "Edit_My_Profile.aspx";
    });

    /*END - dialog for update profile reminder
    --------------------------------------*/

    /*Forum Posts (עכשיו בפורומים)
    --------------*/
    //Invoke AJAX method to get the latest forum posts
    AjaxWebService.LatestForumTopics(LatestForumTopics_success, ajaxError);

    var current = 1;
    var overForumPostsDiv = false;
    var timerForum;

    function LatestForumTopics_success(result) {
        $("#postRowTemplate").tmpl(result).appendTo("#divForumPosts");

        //changing the currently show post
        timerForum = window.setInterval(function () {
            //if the user is not hover the div
            if (overForumPostsDiv == false) {
                var itemsCount = result.length;
                var posts = $(".divForumPost");

                //hide current post and show the new post
                posts.hide();
                posts.eq(current).stop(true, true).fadeIn();

                //increase the counter
                current++;
                if (current >= itemsCount) {
                    current = 0;
                }
            }
        }, 5000);

        $(".divForumPost:first").show();

        if ($("[id$='hdnHideBottomBanner']").val() == "true") {
            $("a").attr('target', '_parent');
        }
    }

    //overForumPostsDiv = whether the user is hovering the ForumPosts div
    $("#divForumPosts").hover(
    function () {
        overForumPostsDiv = true;
    },
    function () {
        overForumPostsDiv = false;
    });

    /*------------*/

    /* Bottom Banner
    ----------------*/
    if ($("[id$='hdnHideBottomBanner']").val() != "true") {
        $("#bottomFixedBanner").slideDown();

        $("#bottomFixedBanner .close").click(function () {
            $("#bottomFixedBanner").slideUp();
        });
    }

    /*Left Ad Fixed Banner
    ----------------------*/
    $(window).resize(showHideAd);
    $(window).load(showHideAd);

    function showHideAd() {
        if ($(window).width() < 1300) {
            $("#leftFixedAd").hide();
            $("#rightFixedAd").hide();
        }
        else {
            $("#leftFixedAd").show();
            $("#rightFixedAd").show();
        }
    }

    $("#centerPopup").click(function () {
        $(this).hide();
    });

    /* right banner stay fixed
    -------------------*/
    //when the user scrolling - set the right banner ad as FIXED if neccesery
    $(window).scroll(function () {
        var rightColumnTotalHeight = $("#rightColumn").offset().top + $("#rightColumn").height() - 250;
        var adHeight = $("#rightColumnAd").height();
        var scrollPosition = $(window).scrollTop();

        if ($("#rightColumnAd").hasClass("rightColumnAdFixed")) {
            rightColumnTotalHeight += adHeight;
        }

        if (scrollPosition < rightColumnTotalHeight) {
            $("#rightColumnAd").removeClass("rightColumnAdFixed");
        }
        else {
            $("#rightColumnAd").addClass("rightColumnAdFixed");
        }
    });


    //Invoke AJAX method to update the last login of the current user
    AjaxWebService.UpdateLastLogin(UpdateLastLogin_success, ajaxError);

    function UpdateLastLogin_success() {
    }
});

function openDialog(title, height, width) {
    //update the dialog settings
    var mainDialog = $("#divMainDialog");
    mainDialog.dialog("option", "title", title);
    mainDialog.dialog("option", "height", height);
    mainDialog.dialog("option", "width", width);
    mainDialog.dialog("option", "position", "center");

    //show ajax LoadingImage in the dialog
    //mainDialog.html("<div class='loadingImage'>");

    mainDialog.dialog("open");

    return mainDialog;
}

function closeDialog() {
    var mainDialog = $("#divMainDialog");
    mainDialog.dialog("close");
}

//show popup div with image in the center of the screen
function showPopupDivCenterScreen(sender, show) {
    var divElement = $('#centerPopup');
    var imageContainer = divElement.find(".image");
    imageContainer.html("");

    //load the image to show
    var imgElement = $("<img>");

    imgElement.load(function () {
        //get the image size
        var imageWidth = $(this)[0].width;
        var imageHeight = $(this)[0].height;

        //get the window size
        var windowWidth = $(window).width();
        var windowHeight = $(window).height();
        var windowScrollTop = $(window).scrollTop();

        var leftPosition = (windowWidth - imageWidth) / 2;
        if (leftPosition < 0) {
            leftPosition = 0;
        }
        var topPosition = ((windowHeight - imageHeight) / 2) + windowScrollTop;
        if (topPosition < 0) {
            topPosition = 0;
        }

        divElement.css("left", leftPosition + "px");
        divElement.css("top", topPosition + "px");

        imageContainer.empty().append(imgElement);
        divElement.show();
    });

    imgElement.attr("src", $(sender).attr("src"));
}

function shortenTextString(text, limit) {
    if (text.length > limit) {
        text = text.substring(0,limit-3) + "...";
    }
    return text;
}

//Optional parameter includeMargin is used when calculating outer dimensions
(function ($) {
    $.fn.getHiddenDimensions = function (includeMargin) {
        var $item = this,
        props = { position: 'absolute', visibility: 'hidden', display: 'block' },
        dim = { width: 0, height: 0, innerWidth: 0, innerHeight: 0, outerWidth: 0, outerHeight: 0 },
        $hiddenParents = $item.parents().andSelf().not(':visible'),
        includeMargin = (includeMargin == null) ? false : includeMargin;

        var oldProps = [];
        $hiddenParents.each(function () {
            var old = {};

            for (var name in props) {
                old[name] = this.style[name];
                this.style[name] = props[name];
            }

            oldProps.push(old);
        });

        dim.width = $item.width();
        dim.outerWidth = $item.outerWidth(includeMargin);
        dim.innerWidth = $item.innerWidth();
        dim.height = $item.height();
        dim.innerHeight = $item.innerHeight();
        dim.outerHeight = $item.outerHeight(includeMargin);

        $hiddenParents.each(function (i) {
            var old = oldProps[i];
            for (var name in props) {
                this.style[name] = old[name];
            }
        });

        return dim;
    }
} (jQuery));
