/* SITE WIDE GLOBAL PLUGIN */

(function($){

jQuery.fn.site_wide = function($params) {
    
    var $defaults = {
        //
        searchText: 'actor/title/director'
    };
    var $p = jQuery.extend($defaults, $params);
    var $this = jQuery(this);
    var ie6 = false;
    var newMethods = {
        initiate_global: function() {
            $('#listDropdown select, #masthead_multi_select select').make_default_queue();
            $('#mnav > li, #amazon-uk-mnav > li').mega_dropdowns();
            ie6 = $.browser.msie&&($.browser.version == "6.0")&&!window.XMLHttpRequest;
            $('#quickSearchBox').search_button_validation();

        },
        make_default_queue: function() {
            $(this).change(function () {
                var queue_id = $(this).val();
                AJAX.set_queue_id(queue_id);
                $.getJSON("/ajax/rental/make_default_queue.html", {
                    queue_id: queue_id,
                    fr: Math.random()
                });
            });
        },
        mega_dropdowns: function() {
            $(this).each(function() {
                var id = $(this).attr('data-mdd');
                $(this).append($('#'+id));
                $(this).hover(
                    function() {
                        if(ie6) $('select').css('visibility', 'hidden'); //Hide select elements to fix issue on IE6
                        $(this).find('ul.drop_down').show();
                    },
                    function() {
                        if(ie6) $('select').css('visibility', 'visible'); //Reset visibility
                        $(this).find('ul.drop_down').hide();
                    }
                );
            });
        },
        search_button_validation: function() {
            $(this).submit(function () {
                var keywords = $("#search_keywords").val();
                if(keywords.length < 1 || keywords == $p.searchText || keywords.split(' ').join('').length < 1) {
                    // Keyword is blank, or default - do nothing
                    return false;
                }

            });
        }
    };
    
    jQuery.each(newMethods, function(i) {
        jQuery.fn[i] = this;
    });
    
    return this.each(function() {
        $this = $(this);
    });
    
};


$( function() {
    $(document).site_wide().initiate_global();
});

})(jQuery);

/**

    lovefilmbox

**/


(function($){

    // Default settings
    var defaults = {};

    // Overlay reference and state
    var overlay = {
        node:    null,
        visible: false
    };

    // LovefilmBox reference and state
    var lfbox = {
        node:    null,
        visible: false
    };

    // Focus reference and states
    var focus = {
        onComplete: null,
        inDocument:    false,
        inLovefilmBox: false
    };

    $.fn.lovefilmbox = function() {
        // Set the defaults
        defaults = $.extend({}, $.fn.lovefilmbox.defaults);

        return this.each(function() {
            $(this).click(function(e) {
			    // Use the element data as a source of configuration options
                var options = gatherOptions($(this));

                // Capture the activator of the lovefilmbox so we
                // can return focus when the lovefilmbox is closed.
                focus.onComplete = this;

                // Show the lovefilmbox for this particular element
                $.showLovefilmBox(options);

                // Deal with any supplied callbacks
                // TODO: maybe this should be in the $.showLoveboxFilm()?
                if (options.fn) {
                    var content = $("#lovefilmbox div.lfbox_body");

                    // If there's a specified height and width
                    // then create a wrapper with those dimensions
                    if (options.height && options.width) {
                        var wrapper = $('<div></div>').css({
                            height:   options.height + 'px',
                            width:    options.width + 'px',
                            overflow: 'hidden'
                        });
                        content.append(wrapper);
                        content = wrapper;
                    }

                    // Call the callback function
                    options.fn(content, options);
                    showLovefilmBox();
                }

                // And finally, prevent the default action from taking place
                e.preventDefault();
            });
        });
    };

	$.fn.lovefilmbox.defaults = {
        height:  200,
        width:   300,
        opacity: 0.8,

		// HTML fragments for the lovefilmbox and it's content types
        overlay:       '<div id="lfoverlay"></div>',
        lfbox_wrapper: '<div id="lovefilmbox"></div>',
        lfbox_close:   '<a href="#" id="lfbox_close_btn" class="lfbox_close">' +
            LOVEFiLM.i18n.i18n('/global/close_button') +
            ' <img height="16" width="16" alt="" src="/lovefilm/images/product/overlay-close.gif"/></a>',
        lfbox_body:    '<div class="lfbox_body"></div>',

        image:  '<img src="" alt="" />',
        iframe: '<iframe frameborder="0" />',

        loading: '<div class="lfbox_loading"><img src="/images/icons/ajax_load_black.gif" alt="" width="10" height="10" border="0"> ' + LOVEFiLM.i18n.i18n('/lovefilm/visitor/login/loading') + '</div>'
	};
	
        /**
        Called from:
        * $.fn.lovefilmbox
        * Directly from other javascript code

            1.) Put overlay on the page
            2.) Put the LovefilmBox offscreen
                * If the content isn't immediately available, show a
                  loading animation and default size
            3.) Start overlay fade animation
            4.) oncomplete: show lovefilmbox centred.
            5.) Once content has loaded (and it's dimensions unknown:
                * Remove loading animation
                * If dimensions initially unknown:
                    * Calculate height of content
                    * Resize and recentre the LovefilmBox

    **/
    $.showLovefilmBox = function(options) {
        if (!options.type) {
            return;
        }

        if (!defaults.lfbox_wrapper) {
            // Set the defaults
            defaults = $.extend({}, $.fn.lovefilmbox.defaults);
        }

        // 1.) put the overlay on the page (invisible)
        createOverlay();

        // 2.) puts the LovefilmBox offscreen
        createLovefilmBox(options);

        // 3.) Fade in the overlay
        fadeInOverlay(function(){
            // 4.) Show the LovefilmBox when the fade finishes
            showLovefilmBox(options);
        });

        // Keep the focus within the lovefilmbox when document has focus
        manageFocus();

        return $("#lovefilmbox div.lfbox_body");
    };

    /**
        manageFocus -- sets up focusout and focusin listeners
        (if available) to manage the focus in a Modal-like way.
    **/
    function manageFocus() {

        if ($(document).focusout) {

            // Track focusin and focusout on lovefilmbox
            $("#lovefilmbox")
                .bind("focusout.lfbox", function(e) {
                    focus.inLovefilmBox = false;
                    if (focus.inDocument && !focus.inLovefilmBox) {
                        reclaimFocus();
                    }
                })
                .bind("focusin.lfbox", function(e) {
                    focus.inLovefilmBox = true;
                });

            // Track focusin and focusout on document
            $(document)
                .bind("focusout.lfbox", function(e) {
                    focus.inDocument = false;
                })
                .bind("focusin.lfbox", function(e) {
                    focus.inDocument = true;
                    if (focus.inDocument && !focus.inLovefilmBox) {
                        reclaimFocus();
                    }
                });

        }

        setEntryFocus();
    };

    function setEntryFocus() {
        // Set the focus to the close button
        // - the first focusable element
        $("#lovefilmbox a.lfbox_close").focus();
    }

    /**
        setExitFocus - when the lovefilmbox is closed this resets
        the focus back to the link that activated the lightbox.
    **/
    function setExitFocus() {
        if (focus.onComplete && focus.onComplete.focus) {
            focus.onComplete.focus();
            focus.onComplete = null;
        }
    }

    /**
        reclaimFocus - seizes the current focus and resets it
        to the first focusable element in the lovefilmbox.
    **/
    function reclaimFocus() {
        focus.inDocument    = true;
        focus.inLovefilmBox = true;
        setEntryFocus();
    };

    /**
        unmanageFocus -- unbinds event handlers on the document,
        and the manage focus event handlers on the lightbox
    **/
    function unmanageFocus() {
        $(document).unbind(".lfbox");
        $("#lovefilmbox").unbind(".lfbox");
    };


    /**
        closeAll - a one stop method that closes and cleans up
        a lovefilm box and overlay.
    **/
    function closeAll() {
        hideOverlay();
        hideLovefilmBox();
        unmanageFocus();
        setExitFocus();
    };


    function createOverlay() {
        // Lazy instantiate the overlay markup
        if (!overlay.node) {
            overlay.node = $(defaults.overlay);

            // Click overlay to remove everything
            overlay.node.click(function(e){
                closeAll();
                e.preventDefault();
            });

            $("body").append(overlay.node);
        }

        // Set the height and width of the overlay to the full document
        overlay.node.css({
            height: $(document).height(),
            width: $(document).width(),
            opacity: 0
        }).show();

        // Close if Escape pressed
        $(document).bind('keypress.lfbox', function(e) {
            if (e.keyCode==27) {
                closeAll();
            }
        });
    };

    function fadeInOverlay(callback) {
        if (callback) {
            overlay.node.animate(
                { opacity:  defaults.opacity },
                { complete: callback }
            );
        }
        else {
            overlay.node.animate(
                { opacity: defaults.opacity }
            );
        }

        overlay.visible = true;
    };

    function hideOverlay() {
        if (overlay.visible) {
            overlay.node.animate(
                { opacity: 0 },
                { complete: function() {
                        overlay.node.hide();
                        overlay.visible = false;
                    }
                }
            );
        }
    };



    function createLovefilmBox(options) {
        // Lazy-instantiate the lovefilmbox markup
        if (!lfbox.node) {
            lfbox.node = $(defaults.lfbox_wrapper)
                .append(defaults.lfbox_close)
                .append(defaults.lfbox_body)
                .addClass("offscreen");

            $("body").append(lfbox.node);
            $("#lovefilmbox a.lfbox_close").click(function(e) {
                closeAll();
                e.preventDefault();
            });
        }

        // repopulate lovefilmbox
        $("#lovefilmbox div.lfbox_body")
            //.empty()
            .append(insertBoxContent(options));

        if (options.height && options.width) {
            centreLovefilmBox(options);
        }

        // Show the box offscreen
        $("#lovefilmbox")
            .addClass("offscreen")
            .show();

    };


    function showLovefilmBox(options) {
        centreLovefilmBox();
        lfbox.node.removeClass("offscreen");
    };

    function centreLovefilmBox(options) {
        var lfNode = lfbox.node;
        if (lfNode) {
            var offset = $(document).scrollTop();
            var width  = lfNode.width();
            var height = lfNode.height();

            var viewport = {
                height: $(window).height(),
                width:  $(window).width()
            };

            if (width == 0) {
                width = $(".lfbox_body", lfNode).width();
            }

            var boxOffset = {
                height: -height/2 + offset,
                width:  -width/2
            }

            // Check the lovefilm box isn't tallen than the
            // current screen height, and fix to top
            // of viewport if this is indeed the case
            if (height > viewport.height) {
                boxOffset.height = -viewport.height/2 + offset;
            }

            if (width > viewport.width) {
                // 50 is double margins of 25px each
                boxOffset.width = -(width + 50 - viewport.width/2);
            }

            lfNode.css({
                'margin-top':  ( boxOffset.height ) + 'px',
                'margin-left': ( boxOffset.width ) + 'px'
            });
        }
    };

    function setLovefilmBoxContent(content) {
        $("#lovefilmbox div.lfbox_body").append(content);

        // Since the content is replaced, probably needs
        // recentering too
        centreLovefilmBox();
    };

    function removeLoadingMessage() {
        $("#lovefilmbox div.lfbox_body div.lfbox_loading").remove();
    }

    function hideLovefilmBox() {
        $("#lovefilmbox").hide();

        // Empty lovefilmbox.
        $("#lovefilmbox div.lfbox_body").empty();
    };


    /**
        gatherOptions - gathers all the option data from the
        clicked link.

        @param the clicked link
        @returns an options object
    **/
    function gatherOptions(link) {

        var options = {
            type:    link.attr('data-type'),
            width:   link.attr('data-width'),
            height:  link.attr('data-height'),
            src:     link.attr('data-src') || link.attr('href'),
            animate: true
        };

        if (!options.type) {
            options.type = 'image';
        }

        switch(options.type) {
            case 'image':
                options.alt = link.attr('title');
                break;
            case 'iframe':
                options.alt = link.attr('title');
                options.callback = link.attr('data-callback');
                options.ajaxUrl  = link.attr('data-url') || options.src;

                // IE7 hangs animation when loading an iframe
                if ($.browser.msie) {
                    options.animate = false;
                }
                break;
            case 'div':
                options.selector = link.attr('data-selector');
                break;
            case 'ajax':
                options.ajaxUrl  = link.attr('data-url') || options.src;
                options.callback = link.attr('data-callback');
                break;
            case 'swf':
                options.method = link.attr('data-callback');
                break;
            default:
                options.callback = link.attr('data-callback');
                break;
        }

        return options;
    };


    /**
        insertBoxContent -- generates the content to insert into
        the lovefilmbox

        @param options object
        @returns an HTML node that can be inserted directly into the
            lovefilmbox
    **/
    function insertBoxContent(options) {
        var content = '';

        switch(options.type) {
            case 'image':
                content = getImageContent(options);
                break;
            case 'iframe':
                content = getIframeContent(options);
                break;
            case 'div':
                content = getDivContent(options);
                break;
            case 'ajax':
                content = getAjaxContent(options);
                break;
            //case 'swf':
            //    content = getSwfContent(options);
            //    break;
            default:
                break;

            // TODO: Check for method on the jquery object
            // based on the attr.type
            if (options.callback) {
                var fn = stringToFunction(options.callback);
                if (typeof fn == 'function') {
                    options.fn = fn;
                }
            }

        }

        return content;
    };

    function getImageContent(options) {
        var image = new Image();

        var complete = false;

        // Create a handler when then image has loaded
        function updateContentHandler() {
            complete = true;
            removeLoadingMessage();
            setLovefilmBoxContent(
                $(defaults.image).attr({
                    src:    options.src,
                    height: image.height || options.height,
                    width:  image.width  || options.width,
                    alt:    options.alt
                })
            );
        };

        //image.onload = updateContentHandler;
        $(image).load(updateContentHandler);

        // Set after the onload handler, in case the image is
        // already cached
        image.src = options.src;

        // Return the "Loading..." content, to be replaced later with
        // the real content
        return (complete)
            ? null
            : getLoadingContent(options);
    };

    function getIframeContent(options) {
        var complete = false;

        // Create a handler when then image has loaded
        function updateContentHandler() {
            complete = true;
            removeLoadingMessage();
        };

        return $(defaults.iframe)
            .attr({
                src:    options.ajaxUrl,
                height: options.height,
                width:  options.width,
                title:  options.alt
            })
            .bind('load', updateContentHandler)
            .add(getLoadingContent(options)
                .css({
                    position: 'absolute',
                    top:      '0px',
                    left:     '0px',
                    width:    (1*options.width+40) + 'px',
                    height:   '10px'
                })
            );
    };

    function getDivContent(options) {
        var content = $(options.selector).clone();
        options.height = content.height();
        options.width  = content.width();
        return content;
    };

    function getAjaxContent(options) {
        var fn = null;

        if (options.callback) {
            fn = stringToFunction(options.callback);
        }

        var boxBody = $("#lovefilmbox div.lfbox_body");

        // In case the load completes before the loading content
        var complete = false;

        boxBody.load(options.ajaxUrl, function(response, status, xhr) {
            complete = true;
            removeLoadingMessage();
            showLovefilmBox();
            if (fn && typeof fn == 'function') {
                fn(boxBody, response, status, xhr);
            }
        });
        // Return the "Loading..." content, to be replaced later with
        // the real content. Unless the load event has already finished!
        return (complete)
            ? null
            : getLoadingContent(options);
    };


    function getLoadingContent(options) {
        var height = options.height || '100';
        var width  = options.width  || defaults.width;

        return $(defaults.loading).css({
            height:  height + 'px',
            width:   width  + 'px',
            opacity: 0.7
        });
    }


    /**
        stringToFunction - takes a callback given as a string
        and returns a reference to a function. Handles dot-syntax
        only.
        (TODO: Probably should be in a common functions namespace)

        @param name of a function as a string
        @returns a reference to the function
    **/
    function stringToFunction(str) {
        var segments = str.split('.');
        var fn       = window;

        for(var i=0, j=segments.length; i<j; i++) {
            if (fn[segments[i]]) {
                fn = fn[segments[i]];
            }
            else {
                return null;
            }
        }

        if (typeof fn == 'function') {
            return fn;
        }

        return null;
    };

})(jQuery);
    
/**
    stop_adverts, removes the iframe adverts
**/
function stop_adverts(){
    $('#advertLEADERBOARD, #advertSKY, #advertMPU, #advertRHS').remove();
}

//create namespace for functions in site_wide_base
LOVEFiLM.site_wide_base = (LOVEFiLM.site_wide_base === undefined) ? {} : Lovefilm.site_wide_base;

/**
* Set a DOM element to have an active style and check input radio when clicked or keydown
* @param {Object}	classes		has the following structure:
*								- classes.item - this is the element to acted upon
*			.					- classes.activeStyle - this the CSS style to apply to an active element
*/
LOVEFiLM.site_wide_base.selectPackage = function(classes) {
	jQuery(classes.item).bind('click keydown', function(){
		jQuery(classes.item).removeClass(classes.activeStyle);
		jQuery(this).addClass(classes.activeStyle).find('input').attr('checked','checked');
    });
};


// My Activity slideDown.
$(document).ready(function() {
    if ($('#my_lovefilm div.rental_summary').length) {
        var $showlink = $('<a href="#encouragement"/>')
            .text(LOVEFiLM.i18n.i18n('/global/widgets/activity/how_to_add_titles'))
            .click(function(e) {
                $('#my_lovefilm div.encouragement').slideDown();
                $(this).remove();
                e.preventDefault();
            });
        $('#my_lovefilm div.rental_summary ul.options li.last')
            .append($showlink);
    }
});

// Zebra-striping of tables
$(document).ready(function() {
    $('tbody.zebra tr:even').addClass('even');
});


