﻿// variables
var _fontStep = 1; // font size has 5 steps
// time out "portal menu" 
var closeAll;
var clearAll;
// timeout variable "home page"
var cloaseDashBoard;

// load cooliris gallery
var initializeCoolirisGallery = false;

// this will disable multi ajax calls
var request;

// this will specify if prev enabled or not in image library
var rightEnabled = false;

// this will specify if next enabled or not in image library
var leftEnabled = true;

// this member will specify that erro will be throwen as alert or not "Debug Purpose"
var raiseError = false;

// functions
function setCookie(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 getCookie(name) {
    var nameEQ = name + "=";
    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(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
    }
	//............... change Font Size................//
function increasFontSize(elem, steps) { // elem is jQuery element
    var currentFontSize = elem.css('font-size');
    var currentFontSizeNum = parseFloat(currentFontSize, 10);
    
    
    var newFontSize = currentFontSizeNum + steps ;
	elem.css('font-size', newFontSize.toString() + 'px');
    
    return;
}


function decreasFontSize(elem, steps) { // elem is jQuery element

    var currentFontSize = elem.css('font-size');
    var currentFontSizeNum = parseFloat(currentFontSize, 10);

    var newFontSize = currentFontSizeNum - steps;
    elem.css('font-size', newFontSize.toString() + 'px');

    return;
}
//............... End change Font Size...........//
// highlight menu items in master page "portal menu" 
function HighLight(ref, colIndex) {
    // highlight child li's
    $("div.Navbg").children(".ItemsSeleted").removeClass("ItemsSeleted");
    $("div.Navbg > div:eq(" + (colIndex - 1) + ")").addClass("ItemsSeleted");

    $("div.topNav ul").children(".headerItemSeleted").removeClass("headerItemSeleted");
    $(ref).parent().addClass("headerItemSeleted");
}

// Toggle Urgent Panel
function ToggleUrgentPanel() {
	setCookie('UrgentPanelOfImamUni', '1', 0);
	$('div.tHeader').slideUp();
	
}

// Toggle Voting Panel
function ToggleVotingPanel() {
    if ($('div.vote_area').length > 0) {
        if ($('div.vote_area').is(':hidden'))
            $('div.vote_area').slideDown();
        else
            $('div.vote_area').slideUp();
    }
}

// FAQ Collabsible
function FAQToggle(obj) {
    if (obj != null) {
        var currentItem = $(obj);
        currentItem.parent().children('div.FAQBody').slideToggle();
    }
}

function FAQMainToggle(obj) {
    if (obj != null) {
        var currentItem = $(obj);
        var collabse_img = currentItem.children('img');
        if (collabse_img.attr('src') == '/_layouts/images/plus.gif') {
            $('div.FAQMainBody').slideUp();
            $('ul.main_list_ul li').each(function() {
                $(this).find('a').children("img[src$='minus.gif']").attr('src', '/_layouts/images/plus.gif');
            });

            collabse_img.attr('src', '/_layouts/images/minus.gif');
        }
        else
            collabse_img.attr('src', '/_layouts/images/plus.gif');

        currentItem.parent().children('div.FAQMainBody').slideToggle();
    }
}

// Center Your Popup
var popupWindow = null;
function CenteredPopup(url, winName, w, h, scroll) {
    LeftPosition = (screen.width) ? (screen.width - w) / 2 : 0;
    TopPosition = (screen.height) ? (screen.height - h) / 2 : 0;
    settings = 'height=' + h + ',width=' + w + ',top=' + TopPosition + ',left=' + LeftPosition + ',scrollbars=' + scroll + ',resizable';
    popupWindow = window.open(url, winName, settings);
}

// callback method for jcarousel external next-prev buttons "dashboard control"
function dashboardcarousel_initCallback(carousel) {
    $('#dashboardcarousel-next').bind('click', function() {
        carousel.next();
        return false;
    });

    $('#dashboardcarousel-prev').bind('click', function() {
        carousel.prev();
        return false;
    });
};

// Document ready event
$(document).ready(function() {
    // font enlarge and smaller click events
	$('.smallerfont').click(function () {
	
        if (_fontStep == 1) {
            return false;
        }
        else {
			$('.enlargerfont').css('display','block');
            decreasFontSize($('.printcontent'), 2);
			decreasFontSize($('.DG2_odd_td'), 2);
			decreasFontSize($('.DG2_header'), 2);
			_fontStep = _fontStep - 1;
			
			if(_fontStep ==1)
				$('.smallerfont').css('display','none');
			
        }
        return false;
    });
	// hide minimze button at the begining.
    $('.smallerfont').css('display','none');
	
	$('.enlargerfont').click(function () {
	    
        if (_fontStep == 6) {
            return false;
        }
        else {
			// show the smaller button
		    $('.smallerfont').css('display','block');
		    increasFontSize($('.printcontent'), 2);   
			increasFontSize($('.DG2_odd_td'), 2);
			increasFontSize($('.DG2_header'), 2);
			_fontStep = _fontStep + 1;
			
			if(_fontStep == 6) 
				$('.enlargerfont').css('display','none');
        }
        
		return false;
    });

    // open the first faq main div
    if ($('div.FAQMainBody').length > 0) {
        if ($('div.FAQMainBody').eq(0).lenght != -1) {
            $('div.FAQMainBody').eq(0).prev('a').children('img').attr('src', '/_layouts/images/minus.gif');
            $('div.FAQMainBody').eq(0).slideDown();
        }
    }

    //cooliris gallery initialization
    if (initializeCoolirisGallery) {
        var flashvars = {
            feed: 'http://content.imamu.edu.sa/MediaFeeds/' + $("#DirectoryNameHiddenField").val().toString() + '/feed.xml'
        };
        var params = {
            allowFullScreen: "true",
            allowscriptaccess: "always"
        };
        swfobject.embedSWF("/_LAYOUTS/ImamPortal/SWF/cooliris.swf", "wall", "770", "500", "9.0.0", "", flashvars, params);

        // reset flag
        initializeCoolirisGallery = false;
    }

    // initilaize sitemap ---------------------------------------------------
    if (window.location.pathname.toLowerCase() == "/pages/portal/sitemap.aspx" || window.location.pathname.toLowerCase() == "/newportal/Pages/sitemap.aspx") {
        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "http://www.imamu.edu.sa/ImamServices/ImamPortalService.svc/GetPortalSiteMap",
            data: '{"ApplicationStaticName": "' + $("#SiteMapApplicationStaticNameHiddenField").val().toString() + '"}',
            dataType: "json",
            success: function(msg) {
                $("#divPortalSiteMap").html(msg.d);
                var siteMapTree = $("#PortalSiteMap").simpletreeview({
                    open: '<img alt="" border="0" src="/_LAYOUTS/ImamPortal/Ar/Images/InternalPages/SiteMap/min_bullet.gif" />',
                    close: '<img alt="" border="0" src="/_LAYOUTS/ImamPortal/Ar/Images/InternalPages/SiteMap/plus_bullet.gif" />',
                    slide: true,
                    speed: 'fast',
                    collapsed: true,
                    expand: '0.0'
                });
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                if (raiseError)
                    alert(textStatus + ": (" + XMLHttpRequest.statusText + ")");
            }
        });
    }

    // DashBoard ------------------------------------------
    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "http://www.imamu.edu.sa/ImamServices/ImamPortalService.svc/LoadDashBoard",
        data: '{"siteURL": "' + $("#DashBoardSiteURLHiddenField").val().toString() + '", "listName": "' + $("#DashBoardListNameHiddenField").val().toString() + '", "viewName": "' + $("#DashBoardViewNameHiddenField").val().toString() + '"}',
        dataType: "json",
        beforeSend: function() {
            // this is where we append a loading image
            $(".IconsPro").block({
                message: '<img src="/_LAYOUTS/ImamPortal/Ar/Images/MainPortal/ajax-loader.gif" alt="Loading..." />',
                css: { border: '0', background: 'none', align: 'absmiddle' }
            });
        },
        success: function(msg) {
            $(".IconsPro").unblock();
            $("#dashboardcarousel").html(msg.d);

            // initiate carousel instance "dashboard control"
            $('.jcarousel-FIcons').jcarousel({
                visible: parseInt($("#DashBoardVisibleQtyHiddenField").val()),
                scroll: parseInt($("#DashBoardScrollQtyHiddenField").val()),
                initCallback: dashboardcarousel_initCallback,
                buttonNextHTML: null,
                buttonPrevHTML: null,
                itemFallbackDimension: 685,
                wrap: "both"
            });

            // animate footer dashboard
            //cloaseDashBoard = setTimeout(function() {
            //    var div_footer = $('.footer_links');
            //    if (div_footer.is(":visible")) {
            //        div_footer.slideUp('slow');
            //        $("#btnFooterPanel").html('الإختصارات السريعة');
            //    }
            //}, 2000);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            if (raiseError)
                alert(textStatus + ": (" + XMLHttpRequest.statusText + ")");
        }
    });

    $("#btnFooterPanel").click(function() {
        var footer = $('.footer_links');

        if (footer.is(":hidden")) {
            // scroll to bottom of the page
            $('html, body').animate({ scrollTop: 60000 }, 'slow');

            footer.slideDown();

            $(this).html('<img src="/_LAYOUTS/ImamPortal/Images/footer_arrow_down.gif" width="32" height="7" />الإختصارات السريعة');
        }
        else {
            footer.slideUp();
            $(this).html('<img src="/_LAYOUTS/ImamPortal/Images/footer_arrow_up.gif" width="32" height="7" />الإختصارات السريعة');
        }

        return false;
    });

    // hook the mouseup events to each header "portal menu" 
    $("div.topNav").mouseup(function() {
        //find the body whose header was clicked
        var body = $("div.Navbg");
        if (body.is(":hidden")) {
            body.slideDown('slow');
        }
    });

    // hook the mouseleave mouseenter events to menu container div "portal menu" 
    $("#menu_container").mouseleave(function() {
        closeAll = setTimeout(function() {
            $("div.Navbg").slideUp('slow');
            clearAll = setTimeout(function() { $("div.Navbg").children(".ItemsSeleted").removeClass("ItemsSeleted"); }, 1000);
        }, 2000);
    }).mouseenter(function() {
        clearTimeout(closeAll);
        clearTimeout(clearAll);
    });

    // Quick Links --------------------------------------------------------
    if ($('#portal_quick_links_main_div').length > 0) {
        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "http://www.imamu.edu.sa/ImamServices/ImamPortalService.svc/LoadQuickLinks",
            data: '{"siteURL": "' + $("#QuickLinksSiteURLHiddenField").val().toString() + '", "listName": "' + $("#QuickLinksListNameHiddenField").val().toString() + '", "secondLevelListName": "' + $("#QuickLinksSecondLevelListNameHiddenField").val().toString() + '", "viewName": "' + $("#QuickLinksViewNameHiddenField").val().toString() + '"}',
            dataType: "json",
            beforeSend: function() {
                // this is where we append a loading image
                $("#portal_quick_links_main_div").block({
                    message: '<img src="/_LAYOUTS/ImamPortal/Ar/Images/MainPortal/ajax-loader.gif" alt="Loading..." />',
                    css: { border: '0', background: 'none', align: 'absmiddle' }
                });
            },
            success: function(msg) {
                $("#portal_quick_links_main_div").unblock();
                $("#portal_quick_links_main_div").html(msg.d);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                if (raiseError)
                    alert(textStatus + ": (" + XMLHttpRequest.statusText + ")");
            }
        });
    }

    // Important Links --------------------------------------------------------
    if ($('#portal_important_links_main_div').length > 0 ) {
        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "http://www.imamu.edu.sa/ImamServices/ImamPortalService.svc/LoadImportantLinks",
            data: '{"siteURL": "' + $("#ImportantLinksSiteURLHiddenField").val().toString() + '", "listName": "' + $("#ImportantLinksListNameHiddenField").val().toString() + '", "viewName": "' + $("#ImportantLinksViewNameHiddenField").val().toString() + '", "ctrlTitle": "' + $("#ImportantLinksCtrlTitleHiddenField").val().toString() + '"}',
            dataType: "json",
            beforeSend: function() {
                // this is where we append a loading image
                $("#portal_important_links_main_div").block({
                    message: '<img src="/_LAYOUTS/ImamPortal/Ar/Images/MainPortal/ajax-loader.gif" alt="Loading..." />',
                    css: { border: '0', background: 'none', align: 'absmiddle' }
                });
            },
            success: function(msg) {
                $("#portal_important_links_main_div").unblock();
                $("#portal_important_links_main_div").html(msg.d);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                if (raiseError)
                    alert(textStatus + ": (" + XMLHttpRequest.statusText + ")");
            }
        });
    }

    // Advertisements -----------------------------------------------------
    if ($('#portal_adv_main_div').length > 0) {
        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "http://www.imamu.edu.sa/ImamServices/ImamPortalService.svc/LoadAdvertisements",
            data: '{"siteURL": "' + $("#AdvertisementsSiteURLHiddenField").val().toString() + '", "listName": "' + $("#AdvertisementsListNameHiddenField").val().toString() + '", "viewName": "' + $("#AdvertisementsViewNameHiddenField").val().toString() + '"}',
            dataType: "json",
            beforeSend: function() {
                // this is where we append a loading image
                $("#portal_adv_main_div").block({
                    message: '<img src="/_LAYOUTS/ImamPortal/Ar/Images/MainPortal/ajax-loader.gif" alt="Loading..." />',
                    css: { border: '0', background: 'none', align: 'absmiddle' }
                });
            },
            success: function(msg) {
                $("#portal_adv_main_div").unblock();
                $("#portal_adv_main_div").html(msg.d);

                // start cycle plugin
                $('#portal_adv_main_div').cycle({
                    fx: 'fade',
                    timeout: parseInt($("#AdvertisementsTimeoutHiddenField").val().toString()),
                    pause: true,
                    pauseOnPagerHover: true,
                    next: '#adv_next',
                    prev: '#adv_prev',
                    pager: '#adv_pager'
                });
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                if (raiseError)
                    alert(textStatus + ": (" + XMLHttpRequest.statusText + ")");
            }
        });

    }

    // all below code related to portal home page and not to master
    // so you should check if this current page is th home page or not
    if (window.location.pathname.toLowerCase() != "/pages/portalhomepage.aspx" && window.location.pathname.toLowerCase() != "/visitors/pages/default.aspx" && window.location.pathname.toLowerCase() != "/newportal/pages/default.aspx" && window.location.pathname.toLowerCase() != "/pages/default.aspx" && window.location.pathname.toLowerCase() != "/pages/default_3.aspx")
        return;

    // latest news counter
    var lnCounter = 1;

    if (window.location.pathname.toLowerCase() == "/pages/portalhomepage.aspx" || window.location.pathname.toLowerCase() == "/pages/default.aspx" || window.location.pathname.toLowerCase() == "/pages/default_3.aspx" || window.location.pathname.toLowerCase() == "/newportal/pages/default.aspx") {
        // load latest news at ready event
        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "http://www.imamu.edu.sa/ImamServices/ImamPortalService.svc/LoadNews",
            data: '{"siteURL": "' + $("#SiteURLHiddenField").val().toString() + '", "listName": "' + $("#ListNameHiddenField").val().toString() + '", "tabsCount": "' + parseInt($("#TabsCountHiddenField").val().toString()) + '", "sender": "ReadyEvent"}',
            dataType: "json",
            beforeSend: function() {
                // this is where we append a loading image
                $("#news_tab_body").block({
                    message: '<img src="/_LAYOUTS/ImamPortal/Ar/Images/MainPortal/ajax-loader.gif" alt="Loading..." />',
                    css: { border: '0', background: 'none', align: 'absmiddle' }
                });
            },
            success: function(msg) {
                $("#news_tab_body").unblock();
                $("#news_tab_body").html(msg.d.html);

                /* start fixing empty tabs */
                // hide unused tabs
                $(".newsTabSelector ul li").each(function(i, e) {
                    if ((i + 1) > msg.d.itemsCount)
                        $(this).hide();
                });

                // reset tabs count value
                $("#TabsCountHiddenField").val(msg.d.itemsCount.toString());
                /* end fixing empty tabs */

                $("#news_tab_body").everyTime(5000, "LatestNews", function(i) {

                    var tabContent = $('div#newsblock_' + lnCounter.toString());
                    var tabLi = $(".newsTabSelector ul").children('li:eq(' + (lnCounter - 1).toString() + ')');

                    // hide all divs contains news
                    $("#news_tab_body").children('div.newsblock').hide();

                    $(tabContent).show();

                    // remove the selected class from the last clicked anchor parent "li"
                    $(".newsTabSelector ul").children().children("a").parent("li.selected").removeClass("selected");

                    // add href attribute to the last clicked anchor to be clickable
                    $(".newsTabSelector ul").children().children("a").attr("href", "#");

                    // add the selected class to the current clicked anchor parent "li"
                    $(tabLi).addClass("selected");

                    // remove href attribute from the current clicked anchor to be unclickable
                    $(tabLi).find('a').removeAttr("href");

                    if (lnCounter == parseInt($("#TabsCountHiddenField").val().toString()))
                        lnCounter = 1;
                    else
                        lnCounter++;
                });
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                if (raiseError)
                    alert(textStatus + ": (" + XMLHttpRequest.statusText + ")");
            }
        });

        $("#news_tab_body").mouseenter(function() {
            $("#news_tab_body").stopTime("LatestNews");
        }).mouseleave(function() {
            $("#news_tab_body").everyTime(5000, "LatestNews", function(i) {

                var tabContent = $('div#newsblock_' + lnCounter.toString());
                var tabLi = $(".newsTabSelector ul").children('li:eq(' + (lnCounter - 1).toString() + ')');

                // hide all divs contains news
                $("#news_tab_body").children('div.newsblock').hide();

                $(tabContent).show();

                // remove the selected class from the last clicked anchor parent "li"
                $(".newsTabSelector ul").children().children("a").parent("li.selected").removeClass("selected");

                // add href attribute to the last clicked anchor to be clickable
                $(".newsTabSelector ul").children().children("a").attr("href", "#");

                // add the selected class to the current clicked anchor parent "li"
                $(tabLi).addClass("selected");

                // remove href attribute from the current clicked anchor to be unclickable
                $(tabLi).find('a').removeAttr("href");

                if (lnCounter == parseInt($("#TabsCountHiddenField").val().toString()))
                    lnCounter = 1;
                else
                    lnCounter++;
            });
        });

        $(".newsTabSelector ul").children().children("a").click(function() {
            if ($(this).parent().hasClass("selected"))
                return;

            // index of list item
            var tabIndex = $(this).parent().index() + 1;

            lnCounter = tabIndex;

            // hide all divs contains news
            $("#news_tab_body").children('div.newsblock').hide();

            $("#news_tab_body").children('div#newsblock_' + tabIndex.toString()).show();

            // remove the selected class from the last clicked anchor parent "li"
            $(".newsTabSelector ul").children().children("a").parent("li.selected").removeClass("selected");

            // add href attribute to the last clicked anchor to be clickable
            $(".newsTabSelector ul").children().children("a").attr("href", "#");

            // add the selected class to the current clicked anchor parent "li"
            $(this).parent().addClass("selected");

            // remove href attribute from the current clicked anchor to be unclickable
            $(this).removeAttr("href");
        });
    }

    // main portal tabs

    // Load Announcements at ready events ------------------------------------------------------------------------------------------------------
    // next-timer related index
    var nextIndex = 1;
    // previous btn related index
    var prevIndex = 0;

    // only one item
    var onlyOneItem = false;

    var announcementsTmpURL = '#tab_LatestAnnouncements';

    var timeOut = 5000; // default if not specified
    try {
        timeOut = parseInt($("#AnnouncementTimeoutHiddenField").val().toString());
    }
    catch (Error) { }

    // enable animation effects
    $.fx.off = false;

    //On Click Event
    $("div.tabs ul li").click(function() {
        if ($(this).hasClass("selected"))
            return;

        $("div.tabs ul li.selected").find("a").attr("href", announcementsTmpURL);

        $("div.tabs ul li").removeClass("selected"); // remove any "active" class
        $(this).addClass("selected"); // add "active" class to selected tab
        var selectedTab = $(this).find("a").attr("href"); // find the rel attribute value to identify the active tab + content
        announcementsTmpURL = selectedTab;
        $(this).find("a").attr("href", "javascript:void(0);");

        if (selectedTab == "#tab_LatestAnnouncements") {
            $("div.TabbedBox").children("div.box").hide();
            $(selectedTab).show();

            // reset index
            nextIndex = 1;

            $.ajax({
                type: "POST",
                contentType: "application/json",
                url: "http://www.imamu.edu.sa/ImamServices/ImamPortalService.svc/LoadAnnouncements",
                data: '{"siteURL": "' + $("#AnnouncementSiteURLHiddenField").val().toString() + '", "listName": "' + $("#AnnouncementListNameHiddenField").val().toString() + '", "slideIndex": "' + nextIndex + '", "sender": "ClickEvent"}',
                dataType: "json",
                beforeSend: function() {
                    // this is where we append a loading image
                    $("#tab_LatestAnnouncementsContent").block({
                        message: '<img src="/_LAYOUTS/ImamPortal/Ar/Images/MainPortal/ajax-loader.gif" alt="Loading..." />',
                        css: { border: '0', background: 'none', align: 'absmiddle' }
                    });
                },
                success: function(msg) {
                    $("#tab_LatestAnnouncementsContent").unblock();
                    $("#tab_LatestAnnouncementsContent").empty().html(msg.d.html);

                    // only one item
                    if (msg.d.itemsCount.toString() == '1') {
                        $("#btn_right_next").hide();
                        $("#btn_left_next").hide();
                        onlyOneItem = true;
                    }
                    else {
                        // if this item is the last one
                        if (nextIndex == parseInt(msg.d.itemsCount.toString())) {
                            // assign previndex
                            prevIndex = nextIndex - 1;

                            // reset i
                            nextIndex = 1;
                        }
                        else
                            if (nextIndex == 1) { // first item
                            // assign previndex
                            prevIndex = parseInt(msg.d.itemsCount.toString());

                            // increment i
                            nextIndex++;
                        }
                        else {
                            // assign previndex
                            prevIndex = nextIndex - 1;

                            // increment i
                            nextIndex++;
                        }

                        $("#tab_LatestAnnouncementsContent").everyTime(timeOut, "Announcements", function(i) {
                            $.ajax({
                                type: "POST",
                                contentType: "application/json",
                                url: "http://www.imamu.edu.sa/ImamServices/ImamPortalService.svc/LoadAnnouncements",
                                data: '{"siteURL": "' + $("#AnnouncementSiteURLHiddenField").val().toString() + '", "listName": "' + $("#AnnouncementListNameHiddenField").val().toString() + '", "slideIndex": "' + nextIndex + '", "sender": "ReadyEvent"}',
                                dataType: "json",
                                success: function(msg) {
                                    $("#tab_LatestAnnouncementsContent").fadeOut("slow", function() {
                                        $("#tab_LatestAnnouncementsContent").empty();
                                        $("#tab_LatestAnnouncementsContent").html(msg.d.html).fadeIn("slow");
                                    });

                                    // if this item is the last one
                                    if (nextIndex == parseInt(msg.d.itemsCount.toString())) {
                                        // assign previndex
                                        prevIndex = nextIndex - 1;

                                        // reset i
                                        nextIndex = 1;
                                    }
                                    else
                                        if (nextIndex == 1) { // first item
                                        // assign previndex
                                        prevIndex = parseInt(msg.d.itemsCount.toString());

                                        // increment i
                                        nextIndex++;
                                    }
                                    else {
                                        // assign previndex
                                        prevIndex = nextIndex - 1;

                                        // increment i
                                        nextIndex++;
                                    }
                                },
                                error: function(XMLHttpRequest, textStatus, errorThrown) {
                                    if (raiseError)
                                        alert(textStatus + ": (" + XMLHttpRequest.statusText + ")");
                                    else
                                        $("#tab_LatestAnnouncementsContent").unblock();
                                }
                            });
                        });
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    if (raiseError)
                        alert(textStatus + ": (" + XMLHttpRequest.statusText + ")");
                    else
                        $("#tab_LatestAnnouncementsContent").unblock();
                }
            });
        }
        else {
            $("#tab_LatestAnnouncementsContent").stopTime("Announcements");
            $("div.TabbedBox").children("div.box").hide(); // hide all tab content
            $(selectedTab).show(); // fade in the active content
        }
        return false;
    });

    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "http://www.imamu.edu.sa/ImamServices/ImamPortalService.svc/LoadAnnouncements",
        data: '{"siteURL": "' + $("#AnnouncementSiteURLHiddenField").val().toString() + '", "listName": "' + $("#AnnouncementListNameHiddenField").val().toString() + '", "slideIndex": "' + nextIndex + '", "sender": "ReadyEvent"}',
        dataType: "json",
        beforeSend: function() {
            // this is where we append a loading image
            $("#tab_LatestAnnouncementsContent").block({
                message: '<img src="/_LAYOUTS/ImamPortal/Ar/Images/MainPortal/ajax-loader.gif" alt="Loading..." />',
                css: { border: '0', background: 'none', align: 'absmiddle' }
            });
        },
        success: function(msg) {
            $("#tab_LatestAnnouncementsContent").unblock();
            $("#tab_LatestAnnouncementsContent").empty().html(msg.d.html);

            // only one item
            if (msg.d.itemsCount.toString() == '1') {
                $("#btn_right_next").hide();
                $("#btn_left_next").hide();
                onlyOneItem = true;
            }
            else {
                // if this item is the last one
                if (nextIndex == parseInt(msg.d.itemsCount.toString())) {
                    // assign previndex
                    prevIndex = nextIndex - 1;

                    // reset i
                    nextIndex = 1;
                }
                else
                    if (nextIndex == 1) { // first item
                    // assign previndex
                    prevIndex = parseInt(msg.d.itemsCount.toString());

                    // increment i
                    nextIndex++;
                }
                else {
                    // assign previndex
                    prevIndex = nextIndex - 1;

                    // increment i
                    nextIndex++;
                }

                $("#tab_LatestAnnouncementsContent").everyTime(timeOut, "Announcements", function(i) {
                    $.ajax({
                        type: "POST",
                        contentType: "application/json",
                        url: "http://www.imamu.edu.sa/ImamServices/ImamPortalService.svc/LoadAnnouncements",
                        data: '{"siteURL": "' + $("#AnnouncementSiteURLHiddenField").val().toString() + '", "listName": "' + $("#AnnouncementListNameHiddenField").val().toString() + '", "slideIndex": "' + nextIndex + '", "sender": "ReadyEvent"}',
                        dataType: "json",
                        success: function(msg) {
                            $("#tab_LatestAnnouncementsContent").fadeOut("slow", function() {
                                $("#tab_LatestAnnouncementsContent").empty();
                                $("#tab_LatestAnnouncementsContent").html(msg.d.html).fadeIn("slow");
                            });

                            // if this item is the last one
                            if (nextIndex == parseInt(msg.d.itemsCount.toString())) {
                                // assign previndex
                                prevIndex = nextIndex - 1;

                                // reset i
                                nextIndex = 1;
                            }
                            else
                                if (nextIndex == 1) { // first item
                                // assign previndex
                                prevIndex = parseInt(msg.d.itemsCount.toString());

                                // increment i
                                nextIndex++;
                            }
                            else {
                                // assign previndex
                                prevIndex = nextIndex - 1;

                                // increment i
                                nextIndex++;
                            }
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown) {
                            if (raiseError)
                                alert(textStatus + ": (" + XMLHttpRequest.statusText + ")");
                            else
                                $("#tab_LatestAnnouncementsContent").unblock();
                        }
                    });
                });
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            if (raiseError)
                alert(textStatus + ": (" + XMLHttpRequest.statusText + ")");
            else
                $("#tab_LatestAnnouncementsContent").unblock();
        }
    });

    // only apply mouse enter and leave events if there are more than one slide
    if (!onlyOneItem) {
        $("#tab_LatestAnnouncements").mouseenter(function() {
            $("#tab_LatestAnnouncementsContent").stopTime("Announcements");
        }).mouseleave(function() {
            $("#tab_LatestAnnouncementsContent").everyTime(timeOut, "Announcements", function(i) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json",
                    url: "http://www.imamu.edu.sa/ImamServices/ImamPortalService.svc/LoadAnnouncements",
                    data: '{"siteURL": "' + $("#AnnouncementSiteURLHiddenField").val().toString() + '", "listName": "' + $("#AnnouncementListNameHiddenField").val().toString() + '", "slideIndex": "' + nextIndex + '", "sender": "ReadyEvent"}',
                    dataType: "json",
                    success: function(msg) {
                        $("#tab_LatestAnnouncementsContent").fadeOut("slow", function() {
                            $("#tab_LatestAnnouncementsContent").empty();
                            $("#tab_LatestAnnouncementsContent").html(msg.d.html).fadeIn("slow");
                        });

                        // if this item is the last one
                        if (nextIndex == parseInt(msg.d.itemsCount.toString())) {
                            // assign previndex
                            prevIndex = nextIndex - 1;

                            // reset i
                            nextIndex = 1;
                        }
                        else
                            if (nextIndex == 1) { // first item
                            // assign previndex
                            prevIndex = parseInt(msg.d.itemsCount.toString());

                            // increment i
                            nextIndex++;
                        }
                        else {
                            // assign previndex
                            prevIndex = nextIndex - 1;

                            // increment i
                            nextIndex++;
                        }
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        if (raiseError)
                            alert(textStatus + ": (" + XMLHttpRequest.statusText + ")");
                        else
                            $("#tab_LatestAnnouncementsContent").unblock();
                    }
                });
            });
        });
    }

    // next btn function
    $("#btn_right_next").click(function() {
        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "http://www.imamu.edu.sa/ImamServices/ImamPortalService.svc/LoadAnnouncements",
            data: '{"siteURL": "' + $("#AnnouncementSiteURLHiddenField").val().toString() + '", "listName": "' + $("#AnnouncementListNameHiddenField").val().toString() + '", "slideIndex": "' + nextIndex + '", "sender": "ReadyEvent"}',
            dataType: "json",
            beforeSend: function() {
                // this is where we append a loading image
                $("#tab_LatestAnnouncementsContent").block({
                    message: '<img src="/_LAYOUTS/ImamPortal/Ar/Images/MainPortal/ajax-loader.gif" alt="Loading..." />',
                    css: { border: '0', background: 'none', align: 'absmiddle' }
                });
            },
            success: function(msg) {
                $("#tab_LatestAnnouncementsContent").unblock();
                $("#tab_LatestAnnouncementsContent").empty().html(msg.d.html);

                // if this item is the last one
                if (nextIndex == parseInt(msg.d.itemsCount.toString())) {
                    // assign previndex
                    prevIndex = nextIndex - 1;

                    // reset i
                    nextIndex = 1;
                }
                else
                    if (nextIndex == 1) { // first item
                    // assign previndex
                    prevIndex = parseInt(msg.d.itemsCount.toString());

                    // increment i
                    nextIndex++;
                }
                else {
                    // assign previndex
                    prevIndex = nextIndex - 1;

                    // increment i
                    nextIndex++;
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                if (raiseError)
                    alert(textStatus + ": (" + XMLHttpRequest.statusText + ")");
                else
                    $("#tab_LatestAnnouncementsContent").unblock();
            }
        });
    });

    // previous btn function
    $("#btn_left_next").click(function() {
        if (prevIndex > 0) {
            $.ajax({
                type: "POST",
                contentType: "application/json",
                url: "http://www.imamu.edu.sa/ImamServices/ImamPortalService.svc/LoadAnnouncements",
                data: '{"siteURL": "' + $("#AnnouncementSiteURLHiddenField").val().toString() + '", "listName": "' + $("#AnnouncementListNameHiddenField").val().toString() + '", "slideIndex": "' + prevIndex + '", "sender": "ReadyEvent"}',
                dataType: "json",
                beforeSend: function() {
                    // this is where we append a loading image
                    $("#tab_LatestAnnouncementsContent").block({
                        message: '<img src="/_LAYOUTS/ImamPortal/Ar/Images/MainPortal/ajax-loader.gif" alt="Loading..." />',
                        css: { border: '0', background: 'none', align: 'absmiddle' }
                    });
                },
                success: function(msg) {
                    $("#tab_LatestAnnouncementsContent").unblock();
                    $("#tab_LatestAnnouncementsContent").empty().html(msg.d.html);

                    // if this item is the last one
                    if (prevIndex == parseInt(msg.d.itemsCount.toString())) {
                        // decrement previndex
                        prevIndex--;

                        // reset i
                        nextIndex = 1;
                    }
                    else
                        if (prevIndex == 1) { // first item
                        // assign i
                        nextIndex = prevIndex + 1;

                        // assign previndex
                        prevIndex = parseInt(msg.d.itemsCount.toString());
                    }
                    else {
                        // assign i
                        nextIndex = prevIndex + 1;

                        // decrement previndex
                        prevIndex--;
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    if (raiseError)
                        alert(textStatus + ": (" + XMLHttpRequest.statusText + ")");
                    else
                        $("#tab_LatestAnnouncementsContent").unblock();
                }
            });
        }
    });

    // Top Links Tabs ------------------------------------------------------------------------------    
    // declare temp ref
    var tempHref = "#";

    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "http://www.imamu.edu.sa/ImamServices/ImamPortalService.svc/LoadTopLinksTabs",
        data: '{"siteURL": "' + $("#TopLinksSiteURLHiddenField").val().toString() + '", "lookupListName": "' + $("#TopLinksLookUpListNameHiddenField").val().toString() + '", "listName": "' + $("#TopLinksListNameHiddenField").val().toString() + '", "sender": "ReadyEvent"}',
        dataType: "json",
        success: function(msg) {
            $("#tab_TopLinksContent").empty();
            $("#tab_TopLinksContent").html(msg.d.ResponceHTML);

            if (msg.d.Errors == 0) {
                var firstListItem = $("div.LinksTitles ul li:first");
                var anchorElement = $(firstListItem).find("a");

                // load links
                $.ajax({
                    type: "POST",
                    contentType: "application/json",
                    url: "http://www.imamu.edu.sa/ImamServices/ImamPortalService.svc/LoadTopLinks",
                    data: '{"siteURL": "' + $("#TopLinksSiteURLHiddenField").val().toString() + '", "listName": "' + $("#TopLinksListNameHiddenField").val().toString() + '", "category": "' + $(anchorElement).attr("name") + '", "sender": "ReadyEvent"}',
                    dataType: "json",
                    success: function(msg) {
			var relatedID = '#';
			
			if($(anchorElement).attr("href").split('#')[1] == undefined)
			   relatedID += $(anchorElement).attr("href");                	   
			else
			   relatedID += $(anchorElement).attr("href").split('#')[1];

                        $(relatedID).empty();
                        $(relatedID).html(msg.d);			
                        tempHref = $(anchorElement).attr("href");
                        $(anchorElement).removeAttr("href");
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        if (raiseError)
                            alert(textStatus + ": (" + XMLHttpRequest.statusText + ")");
                    }
                });

                //On Click Event "applying tab behaviour"
                $("div.LinksTitles ul li").click(function() {
                    if ($(this).hasClass("selected"))
                        return;

                    $("div.LinksTitles ul li.selected").find("a").attr("href", tempHref); // reassign href to the last selected
                    $("div.LinksTitles ul li.selected").removeClass("selected"); // remove any "selected" class                    
                    $(this).addClass("selected"); // add "active" class to selected tab
                    
		    // find the rel attribute value to identify the active tab + content
                    tempHref = $(this).find("a").attr("href");

                    var selectedTab = '#';
		    
                    if($(this).find("a").attr("href").split('#')[1] == undefined)
                	   selectedTab += $(this).find("a").attr("href");
			else
			   selectedTab += $(this).find("a").attr("href").split('#')[1];
                    
                    $(this).find("a").removeAttr("href"); // remove href attr to make anchor unclickable
                    $("#tab_TopLinksContent").children("div.Linksbody").hide(); // hide all tab content
                    $(selectedTab).show(); // fade in the active content

                    var category = $(this).find("a").attr("name");
                    // load links
                    $.ajax({
                        type: "POST",
                        contentType: "application/json",
                        url: "http://www.imamu.edu.sa/ImamServices/ImamPortalService.svc/LoadTopLinks",
                        data: '{"siteURL": "' + $("#TopLinksSiteURLHiddenField").val().toString() + '", "listName": "' + $("#TopLinksListNameHiddenField").val().toString() + '", "category": "' + category + '", "sender": "ClickEvent"}',
                        dataType: "json",
                        beforeSend: function() {
                            // this is where we append a loading image
                            $(selectedTab).html('<div style=\"width:100%; height: 77px; text-align:center; vertical-align:middle;\" ><img src="/_LAYOUTS/ImamPortal/Ar/Images/MainPortal/ajax-loader.gif" alt="Loading..." /></div>');
                        },
                        success: function(msg) {
                            $(selectedTab).empty();
                            $(selectedTab).html(msg.d);			    
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown) {
                            if (raiseError)
                                alert(textStatus + ": (" + XMLHttpRequest.statusText + ")");
                        }
                    });

                    return false;
                });
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            if (raiseError)
                alert(textStatus + ": (" + XMLHttpRequest.statusText + ")");
        }
    });
	
	if ($("#div_UniversityPhotoGallery").length > 0) {

		// photo gallery index -- according to the visible images QTY
		var photoGalleryIndex = parseInt($("#UniversityPhotoGalleryVisibleQtyHiddenField").val()) + 1;
		var loadingListItem = '<li class="aright LibImg"><img style="width:' + parseInt($("#UniversityPhotoGalleryWidthHiddenField").val().toString()) + 'px; height:84px;" src="/_LAYOUTS/ImamPortal/Ar/Images/MainPortal/ajax-loader-gallery.gif" alt="Loading..." /></li>';

		// University Gallery ------------------------------------------
		$.ajax({
			type: "POST",
			contentType: "application/json",
			url: "http://www.imamu.edu.sa/ImamServices/ImamPortalService.svc/LoadUniversityPhotoGallery",
			data: '{"siteURL": "' + $("#UniversityPhotoGallerySiteURLHiddenField").val().toString() + '", "listName": "' + $("#UniversityPhotoGalleryListNameHiddenField").val().toString() + '", "slidesCount": "' + parseInt($("#UniversityPhotoGalleryVisibleQtyHiddenField").val().toString()) + '", "imageWidth": "' + parseInt($("#UniversityPhotoGalleryWidthHiddenField").val().toString()) + '"}',
			dataType: "json",
			success: function(msg) {
				$("#div_UniversityPhotoGallery").html(msg.d.html);

				if (parseInt($("#UniversityPhotoGalleryVisibleQtyHiddenField").val()) == parseInt(msg.d.itemsCount.toString())) // there are no more items avialable
				{
					// disable next btn btn
					$("#universityphotogallery-next").attr('disabled', true);
					leftEnabled = false;
				}
				else
					leftEnabled = true;

				// by default disable prev btn
				$("#universityphotogallery-prev").attr('disabled', true);
				rightEnabled = false;
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				// on error disable next btn & prev btn
				$("#universityphotogallery-next").attr('disabled', true);
				$("#universityphotogallery-prev").attr('disabled', true);
				rightEnabled = false;
				leftEnabled = false;
				if (raiseError)
					alert(textStatus + ": (" + XMLHttpRequest.statusText + ")");
			}
		});

		$("#universityphotogallery-next").click(function() {
			if (!leftEnabled)
				return false;

			$.ajax({
				type: "POST",
				contentType: "application/json",
				url: "http://www.imamu.edu.sa/ImamServices/ImamPortalService.svc/LoadPhotoGalleryImage",
				data: '{"siteURL": "' + $("#UniversityPhotoGallerySiteURLHiddenField").val().toString() + '", "listName": "' + $("#UniversityPhotoGalleryListNameHiddenField").val().toString() + '", "slideIndex": "' + photoGalleryIndex + '", "imageWidth": "' + parseInt($("#UniversityPhotoGalleryWidthHiddenField").val().toString()) + '"}',
				dataType: "json",
				beforeSend: function() {
					// this is where we append a loading image
					// prevent concurrent clicks
					leftEnabled = false;
					// remove the first item
					$("#div_UniversityPhotoGallery ul li:first").remove();
					// append loading item
					$("#div_UniversityPhotoGallery ul").append(loadingListItem);
				},
				success: function(msg) {
					$("#div_UniversityPhotoGallery ul li:last").html(msg.d.html);

					// by default enable prev btn
					$("#universityphotogallery-prev").removeAttr('disabled');
					rightEnabled = true;

					if (photoGalleryIndex == parseInt(msg.d.itemsCount.toString())) {
						// disable next btn btn
						$("#universityphotogallery-next").attr('disabled', true);
						leftEnabled = false;
					}
					else
						leftEnabled = true;

					// icrement index
					photoGalleryIndex++;
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					if (raiseError)
						alert(textStatus + ": (" + XMLHttpRequest.statusText + ")");
				}
			});
		});


		$("#universityphotogallery-prev").click(function() {
			if (!rightEnabled)
				return false;

			$.ajax({
				type: "POST",
				contentType: "application/json",
				url: "http://www.imamu.edu.sa/ImamServices/ImamPortalService.svc/LoadPhotoGalleryImage",
				data: '{"siteURL": "' + $("#UniversityPhotoGallerySiteURLHiddenField").val().toString() + '", "listName": "' + $("#UniversityPhotoGalleryListNameHiddenField").val().toString() + '", "slideIndex": "' + Math.abs((photoGalleryIndex - 1) - parseInt($("#UniversityPhotoGalleryVisibleQtyHiddenField").val())) + '", "imageWidth": "' + parseInt($("#UniversityPhotoGalleryWidthHiddenField").val().toString()) + '"}',
				dataType: "json",
				beforeSend: function() {
					// this is where we append a loading image
					// prevent concurrent clicks
					rightEnabled = false;
					// remove the first item
					$("#div_UniversityPhotoGallery ul li:last").remove();
					// append loading item
					$("#div_UniversityPhotoGallery ul").prepend(loadingListItem);
				},
				success: function(msg) {
					$("#div_UniversityPhotoGallery ul li:first").html(msg.d.html);

					// by default enable next btn
					$("#universityphotogallery-next").removeAttr('disabled');
					leftEnabled = true;

					//decrement index
					photoGalleryIndex--;

					if ((photoGalleryIndex - 1) == parseInt($("#UniversityPhotoGalleryVisibleQtyHiddenField").val())) {
						// disable next btn
						$("#universityphotogallery-prev").attr('disabled', true);
						rightEnabled = false;
					}
					else
						rightEnabled = true;

				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					if (raiseError)
						alert(textStatus + ": (" + XMLHttpRequest.statusText + ")");
				}
			});
		});
		
	}
	
	if ($('#tab_RulesRegulationsContent').length > 0) {
        // Rules & Regulations ------------------------------------------------------------------------------    
        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "http://www.imamu.edu.sa/ImamServices/ImamPortalService.svc/LoadRulesRegulations",
            data: '{"siteURL": "' + $("#RulesRegulationsSiteURLHiddenField").val().toString() + '", "listName": "' + $("#RulesRegulationsPagesLibNameHiddenField").val().toString() + '", "sender": "ReadyEvent"}',
            dataType: "json",
            success: function(msg) {
                $("#tab_RulesRegulationsContent").empty();
                $("#tab_RulesRegulationsContent").html(msg.d);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                if (raiseError)
                    alert(textStatus + ": (" + XMLHttpRequest.statusText + ")");
            }
        });
    }

	if ($('#tab_LibrariesContent').length > 0) {
        // Libraries Links Tabs ------------------------------------------------------------------------------    

        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "http://www.imamu.edu.sa/ImamServices/ImamPortalService.svc/LoadTopLinksTabs_V2",
            data: '{"siteURL": "' + $("#LibrariesLinksSiteURLHiddenField").val().toString() + '", "listName": "' + $("#LibrariesLinksListNameHiddenField").val().toString() + '", "lookuplistName": "' + $("#LibrariesLinksLookUpListNameHiddenField").val().toString() + '", "archivePage": "' + $("#LibrariesLinksArchivePageHiddenField").val().toString() + '", "sender": "ReadyEvent"}',
            dataType: "json",
            success: function(msg) {
                $("#tab_LibrariesContent").empty();
                $("#tab_LibrariesContent").html(msg.d.ResponceHTML);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                if (raiseError)
                    alert(textStatus + ": (" + XMLHttpRequest.statusText + ")");
            }
        });
    }

    // Right News Tabs -------------------------------------------------------------------------------------
    // declare temp href
    var right_news_temphref = "#";
    var RightNewsTabs = $("#NewsTabsHiddenField").val().toString();
    var RightNewsDivClass = $("#NewsDivClassHiddenField").val().toString();
    var RightNewsTabPrefix = $("#NewsTabPrefixHiddenField").val().toString();
    var RightNewsTabClass = $("#NewsTabClassHiddenField").val().toString();
    var RightNewsMoreURLS = $("#NewsMoreURLSHiddenField").val().toString();
    var RightNewsMoreLinkstooltips = $("#NewsMoreLinksTooltipsHiddenField").val().toString();
    var NewsShowRSS = $("#NewsShowRssHiddenField").val().toString().toLowerCase();

	// remove the first li added for handling W3C standards
	if($('ul.' + RightNewsTabClass + ' li').size() > 0)
	$('ul.' + RightNewsTabClass + ' li').eq(0).remove();

    // first get an array from the delimited string
    var rString = $.trim(RightNewsTabs);
    if (rString.substring(rString.length - 1) == ',')
        rString = rString.substring(0, rString.length - 1);

    var array = rString.split(',');

    // get an array from the delimited string for more urls for each tab
    var rURLS = $.trim(RightNewsMoreURLS);
    if (rURLS.substring(rURLS.length - 1) == ',')
        rURLS = rURLS.substring(0, rURLS.length - 1);

    var rightURLS = rURLS.split(',');

    // get an array from the delimited string for more urls tooltips for each tab
    var rURLSTooltips = $.trim(RightNewsMoreLinkstooltips);
    if (rURLSTooltips.substring(rURLSTooltips.length - 1) == ',')
        rURLSTooltips = rURLSTooltips.substring(0, rURLSTooltips.length - 1);

    var rightURLSTooltips = rURLSTooltips.split(',');

    $.each(array, function(rightNewsIndex, value) {
        if (array.length == 1) // only one item
            $('ul.' + RightNewsTabClass + '').append("<li class=\"aright last selected\"><a href=\"#" + RightNewsTabPrefix + "" + (rightNewsIndex + 1) + "\"><div class=\"txt\"><span>" + value + "</span></div></a></li>");
        else
            if (rightNewsIndex == 0) // first one
            $('ul.' + RightNewsTabClass + '').append("<li class=\"aright first selected\"><a href=\"#" + RightNewsTabPrefix + "" + (rightNewsIndex + 1) + "\"><div class=\"txt\"><span>" + value + "</span></div></a></li>");
        else
            if (rightNewsIndex < (array.length - 1))
            $('ul.' + RightNewsTabClass + ' li:last').after("<li class=\"aright\"><a href=\"#" + RightNewsTabPrefix + "" + (rightNewsIndex + 1) + "\"><div class=\"txt\"><span>" + value + "</span></div></a></li>");
        else // last one
            $('ul.' + RightNewsTabClass + ' li:last').after("<li class=\"aright last\"><a href=\"#" + RightNewsTabPrefix + "" + (rightNewsIndex + 1) + "\"><div class=\"txt\"><span>" + value + "</span></div></a></li>");
    });

    //Default Action   
    $('.' + RightNewsDivClass + '').hide(); //Hide all content
    $('ul.' + RightNewsTabClass + ' li:first').addClass("selected").show(); //Activate first tab
    // save anchor href attribute
    right_news_temphref = $('ul.' + RightNewsTabClass + ' li:first').find("a").attr("href");
    $('ul.' + RightNewsTabClass + ' li:first').find("a").removeAttr("href");

    // set default (1st tab) tab more url
    $('#moreNews').attr('href', rightURLS[$('ul.' + RightNewsTabClass + ' li:first').index()]);
    $('#moreNews').attr('title', rightURLSTooltips[$('ul.' + RightNewsTabClass + ' li:first').index()]);

    if (NewsShowRSS == "true") {
        // set tab rss url
        $('#NewsRSS').attr('href', '/_layouts/ImamPortal/RssGenerator.aspx?WebSiteUrl=' + rightURLS[$('ul.' + RightNewsTabClass + ' li:first').index()].toString() + '&RssLink=' + rightURLS[$('ul.' + RightNewsTabClass + ' li:first').index()].toString());
        $('#NewsRSS').attr('title', array[$('ul.' + RightNewsTabClass + ' li:first').index()]);
    }

    $('.' + RightNewsDivClass + ':first').show(); //Show first tab content

    //On Click Event
    $('ul.' + RightNewsTabClass + ' li').click(function() {
        if ($(this).hasClass("selected"))
            return;

        $('ul.' + RightNewsTabClass + ' li.selected').find("a").attr("href", right_news_temphref);
        $('ul.' + RightNewsTabClass + ' li.selected').removeClass("selected"); //Remove any "selected" class

        // reassign temp href
        right_news_temphref = $(this).find("a").attr("href");

        $(this).addClass("selected"); //Add "active" class to selected tab
        $('.' + RightNewsDivClass + '').hide(); //Hide all tab content

        var rightactiveTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content

        $(rightactiveTab).show(); //Fade in the active content

        $(this).find("a").removeAttr("href");

        // set tab more url
        $('#moreNews').attr('href', rightURLS[$(this).index()]);
        $('#moreNews').attr('title', rightURLSTooltips[$(this).index()]);

        if (NewsShowRSS == "true") {
            // set tab rss url
            $('#NewsRSS').attr('href', '/_layouts/ImamPortal/RssGenerator.aspx?WebSiteUrl=' + rightURLS[$(this).index()].toString() + '&RssLink=' + rightURLS[$(this).index()].toString());
            $('#NewsRSS').attr('title', array[$(this).index()]);
        }

        return false;
    });

    // Left Events Tabs -------------------------------------------------------------------------------------
    // declare temp href
    var left_events_temphref = "#";
    var LeftEventsTabs = $("#EventsTabsHiddenField").val().toString();
    var LeftEventsDivClass = $("#EventsDivClassHiddenField").val().toString();
    var LeftEventsTabPrefix = $("#EventsTabPrefixHiddenField").val().toString();
    var LeftEventsTabClass = $("#EventsTabClassHiddenField").val().toString();
    var LeftEventsMoreURLS = $("#EventsMoreURLSHiddenField").val().toString();
    var LeftEventsMoreLinksTootips = $("#EventsMoreLinksTooltipsHiddenField").val().toString();
    var EventsShowRSS = $("#EventsShowRssHiddenField").val().toLowerCase();

	// remove the first li added for handling W3C standards
	if($('ul.' + LeftEventsTabClass + ' li').size() > 0)
	$('ul.' + LeftEventsTabClass + ' li').eq(0).remove();

    // first get an array from the delimited string
    var lString = $.trim(LeftEventsTabs);
    if (lString.substring(lString.length - 1) == ',')
        lString = lString.substring(0, lString.length - 1);

    var array = lString.split(',');

    // get an array from the delimited string for more urls for each tab
    var lURLS = $.trim(LeftEventsMoreURLS);
    if (lURLS.substring(lURLS.length - 1) == ',')
        lURLS = lURLS.substring(0, lURLS.length - 1);

    var leftURLS = lURLS.split(',');

    // get an array from the delimited string for more urls tooltips for each tab
    var lURLSTooltips = $.trim(LeftEventsMoreLinksTootips);
    if (lURLSTooltips.substring(lURLSTooltips.length - 1) == ',')
        lURLSTooltips = lURLSTooltips.substring(0, lURLSTooltips.length - 1);

    var leftURLSTooltips = lURLSTooltips.split(',');

    $.each(array, function(leftEventsIndex, value) {
        if (array.length == 1) // only one item
            $('ul.' + LeftEventsTabClass + '').append("<li class=\"aright last selected\"><a href=\"#" + LeftEventsTabPrefix + "" + (leftEventsIndex + 1) + "\"><div class=\"txt\"><span>" + value + "</span></div></a></li>");
        else
            if (leftEventsIndex == 0) // first one
            $('ul.' + LeftEventsTabClass + '').append("<li class=\"aright first selected\"><a href=\"#" + LeftEventsTabPrefix + "" + (leftEventsIndex + 1) + "\"><div class=\"txt\"><span>" + value + "</span></div></a></li>");
        else
            if (leftEventsIndex < (array.length - 1))
            $('ul.' + LeftEventsTabClass + ' li:last').after("<li class=\"aright\"><a href=\"#" + LeftEventsTabPrefix + "" + (leftEventsIndex + 1) + "\"><div class=\"txt\"><span>" + value + "</span></div></a></li>");
        else // last one
            $('ul.' + LeftEventsTabClass + ' li:last').after("<li class=\"aright last\"><a href=\"#" + LeftEventsTabPrefix + "" + (leftEventsIndex + 1) + "\"><div class=\"txt\"><span>" + value + "</span></div></a></li>");
    });

    //Default Action
    $('.' + LeftEventsDivClass + '').hide(); //Hide all content
    $('ul.' + LeftEventsTabClass + ' li:first').addClass("selected").show(); //Activate first tab
    // save anchor href attribute
    left_events_temphref = $('ul.' + LeftEventsTabClass + ' li:first').find("a").attr("href");
    $('ul.' + LeftEventsTabClass + ' li:first').find("a").removeAttr("href");

    // set default (1st tab) tab more url
    $('#moreEvents').attr('href', leftURLS[$('ul.' + LeftEventsTabClass + ' li:first').index()]);
    $('#moreEvents').attr('title', leftURLSTooltips[$('ul.' + LeftEventsTabClass + ' li:first').index()]);

    if (EventsShowRSS == "true") {
        // set tab rss url
        $('#EventsRSS').attr('href', '/_layouts/ImamPortal/RssGenerator.aspx?WebSiteUrl=' + leftURLS[$('ul.' + LeftEventsTabClass + ' li:first').index()].toString() + '&RssLink=' + leftURLS[$('ul.' + LeftEventsTabClass + ' li:first').index()].toString());
        $('#EventsRSS').attr('title', array[$('ul.' + LeftEventsTabClass + ' li:first').index()]);
    }

    $('.' + LeftEventsDivClass + ':first').show(); //Show first tab content

    //On Click Event
    $('ul.' + LeftEventsTabClass + ' li').click(function() {
        if ($(this).hasClass("selected"))
            return;

        $('ul.' + LeftEventsTabClass + ' li.selected').find("a").attr("href", left_events_temphref);
        $('ul.' + LeftEventsTabClass + ' li.selected').removeClass("selected"); //Remove any "selected" class

        // reassign temp href
        left_events_temphref = $(this).find("a").attr("href");

        $(this).addClass("selected"); //Add "active" class to selected tab
        $('.' + LeftEventsDivClass + '').hide(); //Hide all tab content

        var activeTab = '#';

        if ($(this).find("a").attr("href").split('#')[0].length == 0)
            activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
        else
            activeTab = "#" + $(this).find("a").attr("href").split('#')[1];

        $(activeTab).show(); //Fade in the active content

        $(this).find("a").removeAttr("href");

        // set tab more url
        $('#moreEvents').attr('href', leftURLS[$(this).index()]);
        $('#moreEvents').attr('title', leftURLSTooltips[$(this).index()]);

        if (EventsShowRSS == "true") {
            // set tab rss url
            $('#EventsRSS').attr('href', '/_layouts/ImamPortal/RssGenerator.aspx?WebSiteUrl=' + leftURLS[$(this).index()].toString() + '&RssLink=' + leftURLS[$(this).index()].toString());
            $('#EventsRSS').attr('title', array[$(this).index()]);
        }

        return false;
    });

    // university places counter
    var upCounter = 1;

    if (window.location.pathname.toLowerCase() == "/visitors/pages/default.aspx") {

        // Benefits Tabs -------------------------------------------------------------------------------------
        // declare temp href
        var left_benefits_temphref = "#";
        var LeftBenefitsTabs = $("#BenefitsTabsHiddenField").val().toString();
        var LeftBenefitsDivClass = $("#BenefitsDivClassHiddenField").val().toString();
        var LeftBenefitsTabPrefix = $("#BenefitsTabPrefixHiddenField").val().toString();
        var LeftBenefitsTabClass = $("#BenefitsTabClassHiddenField").val().toString();
        var LeftBenefitsMoreURLS = $("#BenefitsMoreURLSHiddenField").val().toString();
        var LeftBenefitsMoreLinksTootips = $("#BenefitsMoreLinksTooltipsHiddenField").val().toString();

	// remove the first li added for handling W3C standards
	if($('ul.' + LeftBenefitsTabClass + ' li').size() > 0)
	$('ul.' + LeftBenefitsTabClass + ' li').eq(0).remove();

        // first get an array from the delimited string
        var lString = $.trim(LeftBenefitsTabs);
        if (lString.substring(lString.length - 1) == ',')
            lString = lString.substring(0, lString.length - 1);

        var array = lString.split(',');

        // get an array from the delimited string for more urls for each tab
        var lBenefitsURLS = $.trim(LeftBenefitsMoreURLS);
        if (lBenefitsURLS.substring(lBenefitsURLS.length - 1) == ',')
            lBenefitsURLS = lBenefitsURLS.substring(0, lURLS.length - 1);

        var leftBenefitsURLS = lBenefitsURLS.split(',');

        // get an array from the delimited string for more urls tooltips for each tab
        var lURLSBenefitsTooltips = $.trim(LeftBenefitsMoreLinksTootips);
        if (lURLSBenefitsTooltips.substring(lURLSBenefitsTooltips.length - 1) == ',')
            lURLSBenefitsTooltips = lURLSBenefitsTooltips.substring(0, lURLSBenefitsTooltips.length - 1);

        var leftBenefitsURLSTooltips = lURLSBenefitsTooltips.split(',');

        $.each(array, function(leftBenefitsIndex, value) {
            if (array.length == 1) // first one
                $('ul.' + LeftBenefitsTabClass + '').append("<li class=\"aright last selected\"><a href=\"#" + LeftBenefitsTabPrefix + "" + (leftBenefitsIndex + 1) + "\"><div class=\"txt\"><span>" + value + "</span></div></a></li>");
            else
                if (leftBenefitsIndex == 0) // first one
                $('ul.' + LeftBenefitsTabClass + '').append("<li class=\"aright first selected\"><a href=\"#" + LeftBenefitsTabPrefix + "" + (leftBenefitsIndex + 1) + "\"><div class=\"txt\"><span>" + value + "</span></div></a></li>");
            else
                if (leftBenefitsIndex < (array.length - 1))
                $('ul.' + LeftBenefitsTabClass + ' li:last').after("<li class=\"aright\"><a href=\"#" + LeftBenefitsTabPrefix + "" + (leftBenefitsIndex + 1) + "\"><div class=\"txt\"><span>" + value + "</span></div></a></li>");
            else // last one
                $('ul.' + LeftBenefitsTabClass + ' li:last').after("<li class=\"aright last\"><a href=\"#" + LeftBenefitsTabPrefix + "" + (leftBenefitsIndex + 1) + "\"><div class=\"txt\"><span>" + value + "</span></div></a></li>");
        });

        //Default Action
        $('.' + LeftBenefitsDivClass + '').hide(); //Hide all content
        $('ul.' + LeftBenefitsTabClass + ' li:first').addClass("selected").show(); //Activate first tab
        // save anchor href attribute
        left_benefits_temphref = $('ul.' + LeftBenefitsTabClass + ' li:first').find("a").attr("href");
        $('ul.' + LeftBenefitsTabClass + ' li:first').find("a").removeAttr("href");
        // set default (1st tab) tab more url
        $('#moreBenefits').attr('href', leftBenefitsURLS[$('ul.' + LeftBenefitsTabClass + ' li:first').index()]);
        $('#moreBenefits').attr('title', leftBenefitsURLSTooltips[$('ul.' + LeftBenefitsTabClass + ' li:first').index()]);
        $('.' + LeftBenefitsDivClass + ':first').show(); //Show first tab content

        //On Click Event
        $('ul.' + LeftBenefitsTabClass + ' li').click(function() {
            if ($(this).hasClass("selected"))
                return;

            $('ul.' + LeftBenefitsTabClass + ' li.selected').find("a").attr("href", left_benefits_temphref);
            $('ul.' + LeftBenefitsTabClass + ' li.selected').removeClass("selected"); //Remove any "selected" class

            // reassign temp href
            left_benefits_temphref = $(this).find("a").attr("href");

            $(this).addClass("selected"); //Add "active" class to selected tab
            $('.' + LeftBenefitsDivClass + '').hide(); //Hide all tab content

            var activeTab = '#';

            if ($(this).find("a").attr("href").split('#')[0].length == 0)
                activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
            else
                activeTab = "#" + $(this).find("a").attr("href").split('#')[1];

            $(activeTab).show(); //Fade in the active content

            $(this).find("a").removeAttr("href");

            // set tab more url
            $('#moreBenefits').attr('href', leftBenefitsURLS[$(this).index()]);
            $('#moreBenefits').attr('title', leftBenefitsURLSTooltips[$(this).index()]);

            return false;
        });


        // load university places at ready event
        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "http://www.imamu.edu.sa/ImamServices/ImamPortalService.svc/LoadUniversityPlaces",
            data: '{"siteURL": "' + $("#SiteURLHiddenField").val().toString() + '", "listName": "' + $("#ListNameHiddenField").val().toString() + '", "viewName": "' + $("#ViewNameHiddenField").val().toString() + '", "tabsCount": "' + parseInt($("#TabsCountHiddenField").val().toString()) + '", "sender": "ReadyEvent"}',
            dataType: "json",
            beforeSend: function() {
                // this is where we append a loading image
                $("#news_tab_body").block({
                    message: '<img src="/_LAYOUTS/ImamPortal/Ar/Images/MainPortal/ajax-loader.gif" alt="Loading..." />',
                    css: { border: '0', background: 'none', align: 'absmiddle' }
                });
            },
            success: function(msg) {
                $("#news_tab_body").unblock();
                $("#news_tab_body").html(msg.d.html);

                /* start fixing empty tabs */
                // hide unused tabs
                $(".newsTabSelector ul li").each(function(i, e) {
                    if ((i + 1) > msg.d.itemsCount)
                        $(this).hide();
                });

                // reset tabs count value
                $("#TabsCountHiddenField").val(msg.d.itemsCount.toString());
                /* end fixing empty tabs */

                $("#news_tab_body").everyTime(5000, "UniversityPlaces", function(i) {

                    var tabContent = $('div#places_block_' + upCounter.toString());
                    var tabLi = $(".newsTabSelector ul").children('li:eq(' + (upCounter - 1).toString() + ')');

                    // hide all divs contains news
                    $("#news_tab_body").children('div.places_block').hide();

                    $(tabContent).show();

                    // remove the selected class from the last clicked anchor parent "li"
                    $(".newsTabSelector ul").children().children("a").parent("li.selected").removeClass("selected");

                    // add href attribute to the last clicked anchor to be clickable
                    $(".newsTabSelector ul").children().children("a").attr("href", "#");

                    // add the selected class to the current clicked anchor parent "li"
                    $(tabLi).addClass("selected");

                    // remove href attribute from the current clicked anchor to be unclickable
                    $(tabLi).find('a').removeAttr("href");

                    if (upCounter == parseInt($("#TabsCountHiddenField").val().toString()))
                        upCounter = 1;
                    else
                        upCounter++;
                });
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                if (raiseError)
                    alert(textStatus + ": (" + XMLHttpRequest.statusText + ")");
            }
        });

        $("#news_tab_body").mouseenter(function() {
            $("#news_tab_body").stopTime("UniversityPlaces");
        }).mouseleave(function() {
            $("#news_tab_body").everyTime(5000, "UniversityPlaces", function(i) {

                var tabContent = $('div#places_block_' + upCounter.toString());
                var tabLi = $(".newsTabSelector ul").children('li:eq(' + (upCounter - 1).toString() + ')');

                // hide all divs contains news
                $("#news_tab_body").children('div.places_block').hide();

                $(tabContent).show();

                // remove the selected class from the last clicked anchor parent "li"
                $(".newsTabSelector ul").children().children("a").parent("li.selected").removeClass("selected");

                // add href attribute to the last clicked anchor to be clickable
                $(".newsTabSelector ul").children().children("a").attr("href", "#");

                // add the selected class to the current clicked anchor parent "li"
                $(tabLi).addClass("selected");

                // remove href attribute from the current clicked anchor to be unclickable
                $(tabLi).find('a').removeAttr("href");

                if (upCounter == parseInt($("#TabsCountHiddenField").val().toString()))
                    upCounter = 1;
                else
                    upCounter++;
            });
        });

        $(".newsTabSelector ul").children().children("a").click(function() {
            if ($(this).parent().hasClass("selected"))
                return;

            // index of list item
            var tabIndex = $(this).parent().index() + 1;

            upCounter = tabIndex;

            // hide all divs contains news
            $("#news_tab_body").children('div.places_block').hide();

            $("#news_tab_body").children('div#places_block_' + tabIndex.toString()).show();

            // remove the selected class from the last clicked anchor parent "li"
            $(".newsTabSelector ul").children().children("a").parent("li.selected").removeClass("selected");

            // add href attribute to the last clicked anchor to be clickable
            $(".newsTabSelector ul").children().children("a").attr("href", "#");

            // add the selected class to the current clicked anchor parent "li"
            $(this).parent().addClass("selected");

            // remove href attribute from the current clicked anchor to be unclickable
            $(this).removeAttr("href");
        });
    }

    /* end */
});
