var widgetConfigOptions = {
    enableShowHide: true,
    showHideVisibleImageUrl: '/images/arrow_grey_down.png',
    showHideHiddenImageUrl: '/images/arrow_grey_right.png',
    ajaxControllerUrl: '/home/AjaxController.aspx',
    ajaxLoaderImageUrl: '/images/ajaxLoader.gif',
    layoutController: 'LayoutProcessor'
};

$(document).ready(function () {

    hookUpWidgets();
    selectableSearches();
    faq();
    exploreAllServices();

    // JMD - I have disabled this for now as its not working and it's release day!
    //homeSearchTabs();//
    printButton();
    openExploreAllServicesFromUrl();
    signpost();
    newWindow();
    hookUpSearchProvider();
    checkForNoJS();
    //atozSwitcher(); //VT am gonnae disable this unor, cos its causing AtoZ links not to fire.
    myResourceZebraColours();
    GoogleAnalyticEventTracker();
    setTimeout(widgetPanelAddButton, 200);
    clearInputs("Evidence, articles, books, elearning...", "input.clearTerm");

    $("a[rel^='prettyPhoto']").prettyPhoto({ deeplinking: false, keyboard_shortcuts: false, social_tools: '', theme: 'light_rounded' });
    $(".news-updates ul.newsFeed").addClass("bulletPoints");
    $(".news-updates ul.newsFeed>li").addClass("bulletPointItem");
});

function widgetPanelAddButton() {
    
    if ($("#Home .widgetRow").length > 0) {
        var leftHeight = 0;
        var rightHeight = 0;

        $("#c1 li").each(function () { leftHeight = leftHeight + $(this).height(); });
        $("#c2 li").each(function () { rightHeight = rightHeight + $(this).height(); });
        
        var addHtml = '<li id="addWidget" class="widget"><div><p><a href="/home/edit-widgets.aspx">Add a widget to the panel by clicking here</a></p></div></li>'
        
        if (rightHeight > leftHeight) {
            $("#c1").append(addHtml);
        }
        else {
            $("#c2").append(addHtml);
        }

        $('#addWidget').hide();
        $('#addWidget').fadeIn();
    }
}

function GoogleAnalyticEventTracker() {

    //What is here for me? links
    $("#Home .tknResources a").click(function() {    
        _gaq.push(['_trackEvent', 'What is here for me?', $(this).text(), $(this).attr('href')]);

    });

    //My quicklinks on homepage
    $("#Home .my-quick-links ul.newsFeed a").click(function() {
    _gaq.push(['_trackEvent', 'My quicklinks on homepage', $(this).text(), $(this).attr('href')]); 
    });



}

function newWindow() {
    var domain = document.domain;


    $("a[class!='mark'][href^='http']:not([href*='" + domain + "'][href*='http://shelcat.org/sfxlcl3/menu?'][rel*='shadowbox']), a[href*='/Referrer.aspx?url=']")
	    .addClass('newWindow');

    $("a[class!='mark'][href^='http']:not([href*='" + domain + "'][href*='http://shelcat.org/sfxlcl3/menu?'][rel*='shadowbox']), a[href*='/Referrer.aspx?provider=utd']")
	    .addClass('newWindow');



    $('.newWindow').click(function() {
        window.open(this.href);
        return false;
    });
}

function checkForNoJS() {
    //$('.noJs').hide();
    //$('.addToBrowser').removeAttr("disabled");
    $('.noJs').hide();
    $('.addToBrowser').show();
    $('.addToBrowser-disabled').hide().remove();
}

function signpost() {
    $('#searchresult_signpost').jqm({ overlay: 30, modal: true, toTop: true }).jqmShow();
}

function printButton() {
    $("#printButton").empty();
    $("#printButton").append("<a href='#' onclick='window.print(); return false'>Print</a>");
    $("#printButton").addClass("print");
}

function openExploreAllServicesFromUrl() {
    var open = gup("eas");
    if (open) {
        $('#explore').show("slow");
    }
}


function exploreAllServices() {
    $('#explore').hide();
    var h = $('#header').height();
    $('#explore').height(h);
    var clonedExplore = $('#explore').clone();
    $('#explore').remove();

    $(clonedExplore).appendTo($('.explore'));
    $('#explore').addClass('exploreAllServices');
    $('.exploreAllServices .wrapper').prepend("<img src='/images/close_popup.png' alt='close' class='fr' onclick='$(\"#explore\").hide(\"fast\")' />");
    $('.explore>a').click(function() {
        $('#explore').show("slow");
        return false;
    });
}

function selectableSearches() {
    $("a.mark").click(function () {
        // For anyone else working on this, please don't, just assign to Ant
        var element = $(this);

        element.toggleClass("selected");
        element.attr("id", "selectedSearchItem");
        callListenEvent("selectedSearchItem"); // calls addSearchToSelectedSearch() in saveAndShareWidget.js - comments FTW
        element.attr("id", "");

        element.text((element.is(".selected") ? 'Remove from Save & Share' : 'Add to Save & Share'));

        // Text of "Remove from Save & Share" is overwriting header text in MRS. Toggle class to enlarge/shrink header text.
        element.parents("ul.addResourceList").first().siblings("h4").children("a").toggleClass("saveAndShared");
        return false;
    });
}

function myResourceZebraColours() {
    //$('#content ul.listing .myResourceLine:even').css('background-color', '#F5F0F4');
    //$('#content ul.listing .myResourceLine:even').addClass('bgDark');
    var myResourceLists = $('#content ul.listing li');
    //myResourceLists.css('background-color', 'red');
    myResourceLists.each(function(index) {
        myResourceLists.find('.myResourceLine:even').addClass('bgDark');
    });

}

String.prototype.normalize_space = function() {
    // Replace repeated spaces, newlines and tabs with a single space
    return this.replace(/^\s*|\s(?=\s)|\s*$/g, "");
}

function faq() {
    $(".faq h3").wrapInner("<a href='#'></a>");
    $(".faqContent").slideUp("fast");
    $(".faq h3 a").click(function() {
        $(this).parents("li").children(".faqContent").slideToggle("slow");
        return false;
    });
}


function homeSearchTabs() {
    $("#tabSearchMain li a").click(function() {
        var url = $(this).attr("href");
        var formType;
        if (url.indexOf("adv") >= 0) { formType = "adv" } else { formType = "basic" }
        url = url.replace(".aspx", "/homeSearchAjax.aspx");
        homeSearchAjax(url, formType);
        return false;
    });
}


function homeSearchAjax(url, formType) {
    $.ajax({
        url: url,
        cache: false,
        success: function(html) {
            $("#searchForm").hide();
            $("#searchForm").empty();
            $("#searchForm").append($(html).find("#searchForm>div"));
            $("#searchMain").attr("class", formType);
            $("#searchForm").fadeIn("fast");
        }
    });
}

function gup(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}

$(document).ready(function() {
    var scrollPosition = getCookie('autoScroll_scrollPosition');
    var rememberScroll = getCookie('autoScroll_rememberScroll');

    if (scrollPosition && rememberScroll) {
        $(window).scrollTop(scrollPosition);
        deleteCookie('autoScroll_rememberScroll');
    }

    var IMAGE_TRANSITION_TIME = 5000;
    var AUTO_TRANSITION_SPEED = 500;
    var MANUAL_TRANSITION_SPEED = 150;

    $('div.ImageWidget').each(function() {
        var currentTransitionSpeed = AUTO_TRANSITION_SPEED;
        var imageChangeTimer;
        var currentImage;
        var transitionInProgress = false;

        var totalImages = $(this).find('div.boxContent > div.boxInner > ul > li').length;

        if (totalImages > 1) {
            currentImage = $(this).find('div.boxContent > div.boxInner > ul > li:visible');

            imageChangeTimer = setTimeout(function() {
                changeImage(true);
            }, IMAGE_TRANSITION_TIME);

            $(this).find('.PagingLinks a').click(function(e) {
                e.preventDefault();

                clearTimeout(imageChangeTimer);
                currentTransitionSpeed = MANUAL_TRANSITION_SPEED;

                if ($(this).parent().hasClass('Previous')) {
                    changeImage(false);
                }
                else {
                    changeImage(true);
                }
            });
        }

        function changeImage(isForward) {
            if (!transitionInProgress) {
                transitionInProgress = true;

                var nextImage = isForward ? currentImage.next() : currentImage.prev();

                if (nextImage.length == 0) {
                    nextImage = isForward ? currentImage.parent().find('li:first') : currentImage.parent().find('li:last');
                }

                var nextElementHeight = nextImage.height();
                var currentElementHeight = currentImage.height();

                if (nextElementHeight > currentElementHeight) {
                    //currentImage.parent().parent().height(nextElementHeight);
                }

                currentImage.find('a img').fadeOut(currentTransitionSpeed, function() {
                    currentImage.hide();
                    nextImage.find('a img').hide();
                    nextImage.show();

                    nextImage.find('a img').fadeIn(currentTransitionSpeed, function() {
                        //currentImage.parent().parent().height(nextElementHeight);

                        currentImage = nextImage;

                        transitionInProgress = false;
                        currentTransitionSpeed = AUTO_TRANSITION_SPEED;

                        imageChangeTimer = setTimeout(function() {
                            changeImage(true);
                        }, IMAGE_TRANSITION_TIME);
                    });
                });
            }
        }
    });

    $('.jqAutoScroll').click(function() {
        setCookie('autoScroll_rememberScroll', true);
        return true;
    });
});

function atozSwitcher() {
    if ($('.atoz').length) {
        var tabs = $('.atoz li a');
        var sections = $('.results div');

        atozSwitcherIt(tabs, sections);
    }
}

function atozSwitcherIt(tabTrigger, tabSections) {

    var tabTrigger = tabTrigger;
    var tabSections = tabSections;

    tabSections.hide().filter(':first').show();
    tabTrigger.filter(':first').parent().addClass('current');

    tabTrigger.click(function() {
        var shell = $(this).text();
        shell = "#alphaWidgetSection-" + shell;

        tabTrigger.parent().removeClass('current');
        $(this).parent().addClass('current');

        tabSections.filter(':visible').fadeOut("slow", function() {
            $(shell).fadeIn("slow");
        });

        return false
    });

    $('span.allLink a').click(function() {
        tabSections.fadeIn("slow");
        return false;
    });
}



function getCookie(name) {
    name = escape($.trim(name));

    var cookies = document.cookie.split(';');

    for (var i = 0; i < cookies.length; i++) {
        var cookieCrumbs = cookies[i].split('=');
        var cookieName = $.trim(cookieCrumbs[0]);
        var cookieValue = cookieCrumbs[1];

        if (cookieName == name) {
            return unescape(cookieValue);
        }
    }

    return false;
}

function setCookie(name, value) {
    document.cookie = escape($.trim(name)) + '=' + escape(value) + ';path=/';
}

function deleteCookie(name) {
    document.cookie = escape($.trim(name)) + '=;expires=Thu, 01-Jan-70 00:00:01 GMT;path=/';
}

$(window).scroll(function() {
    document.cookie = "autoScroll_scrollPosition=" + $(this).scrollTop();
});

//----- Recent Activity Widget Functionality -----//
jQuery.hookUpRecentActivityWidget = function (maxItems) {
    $(document).ready(function () {
        var recentActivityWidget = $('div.RecentActivity div.boxContent div.boxInner');

        if ($('.ActivityList').size() > 1) {
            $('.ActivityList:first').remove();
        }

        var html = '<ul class="ActivityMenu fc">' +
                    '<li class="first selected"><a href="#AllList">All</a></li>';

        recentActivityWidget.find('div.ActivityList h3').each(function () {
            var list = $(this).next('ul');
            html += '<li><a href="#' + list.attr('class') + '">' + $(this).text() + '</a></li>';
        });

        html += '</ul>';

        recentActivityWidget.find('ul, h3').css('display', 'none');

        recentActivityWidget.prepend(html);

        recentActivityWidget.find('ul.ActivityMenu li a').click(function () {
            $(this).parents('ul.ActivityMenu').find('li').removeClass('selected');
            $(this).parents('li').addClass('selected');

            recentActivityWidget.find('ul:not(.ActivityMenu), h3').css('display', 'none');

            var indexOfHash = $(this).attr('href').indexOf('#');
            var className = $(this).attr('href').substring(indexOfHash + 1);
            recentActivityWidget.find('ul.' + className).css('display', 'block');

            return false;
        });

        var allItemClasses = new Array();

        recentActivityWidget.find('.ActivityList > ul > li').each(function () {
            allItemClasses.push($(this).attr('class').replace(' alt', ''));
        });

        allItemClasses.sort();
        allItemClasses.reverse();

        var allItemsHtml = '<ul class="AllList">';

        var itemLength = allItemClasses.length < maxItems ? allItemClasses.length : maxItems;

        var altRow = false;
        for (var i = 0; i < itemLength; i++) {
            var element = recentActivityWidget.find('.ActivityList ul li.' + allItemClasses[i]);
            allItemsHtml += '<li' + (altRow ? ' class="alt"' : '') + '>' + element.html() + '</li>';

            altRow = !altRow;
        }

        allItemsHtml += '</ul>';

        recentActivityWidget.find('.ActivityList').append(allItemsHtml);

    });
}

/* Clears the input text and replaces with a set value passed into the function along with the Jquery hook to get the inputs */
function clearInputs(defaultText,hook) {
    var inputText = defaultText;
    var inputs = function () { return $(hook) } ();

    if (inputs.val() == "") {
        inputs.val(inputText)
    }
    
    inputs.focus(function (eventObject) {
        if (inputText == this.value) {
            this.value = "";
        }
    })
    .blur(function (eventObject) {
        if (this.value == "") {
            this.value = inputText;
        }
    })
    .parentsUntil("form").find("input[type=submit]").click(function () {
        if (inputs.val() == inputText) {
            inputs.val("");
        }
    });
}

