/// <reference path="jquery-vsdoc.js" />   
var TABS = {
    visible: false,
    active: false
};

// ==========================================================================================================
// =============================== BROWSER ==================================================================
// ==========================================================================================================

function browser() {
    $.each($.browser, function(i, val) {
        if (val == true) $("body").addClass(i);
        if (i == "msie6" && val == true && parseFloat($.browser.version.substr(0, 3)) <= 6.9) {
            $(".ub_tabimg").bgiframe();
        }
    });
}

// ==========================================================================================================
// ============================== NAVIGATION ================================================================
// ==========================================================================================================

var pcurrent,
    ptimeout,
    intent_timeout,
    intent_target;

function navigation() {

    var currentUrl = window.location.pathname + window.location.search;
    $('#navigation .navigation a, #navigation .sub_navigation a').each(function() {
        if ($(this).attr('href') == currentUrl) {
            var rel = $(this).addClass('current pcurrent').attr('rel');
            if (rel == undefined) return;
            if ($(this).parents('.navigation').length > 0) {
                if ($.browser.msie) $('#subnav_' + rel).show();
                else $('#subnav_' + rel).stop().fadeIn(500);
            }
            else {
                rel = $(this).parents('.sub_navigation').css({ 'opacity': 1, 'display': 'block' }).attr('id');
                if (rel == undefined) return;
                rel = rel.substring(7);
                var pcurrent_section = $('#navigation .navigation a[rel=' + rel + ']').addClass('current');
                Cufon.replace(this, {
                    hover: true
                });
            }
            pcurrent = this;
            return;
        }
    });

    // set classes of separator on hover - to allow for image control
    //    $("#navigation .navigation li:not(.sep), .ui-tabs-nav li:not(.sep)").hover(function() {
    //        // var $this = $(this);
    //        if ($(this).find('a.current').length > 0) return;
    //        $(this).prev(".sep").addClass("ol");
    //        $(this).next(".sep").addClass("or");
    //        }, function() {
    //        // var $this = $(this);
    //        $(this).prev(".sep").removeClass("ol");
    //        $(this).next(".sep").removeClass("or");
    //    });

    $("#navigation .navigation li a[rel]").hover(function() {
        if ($("#navigation #subnav_" + $(this).attr('rel') + ":visible").length) return;
        intent_target = $(this);
        if (intent_timeout) clearTimeout(intent_timeout);
        intent_timeout = setTimeout(function() {
            var prev_current = $("#navigation .navigation li a.current").removeClass("current");
            Cufon.replace(prev_current, {
                textShadow: "1px 1px rgba(51, 51, 51, 0.5)",
                hover: true
            });
            var $this = intent_target;
            var rel = $this.attr("rel");
            $(".sub_navigation").hide().css('opacity', 1);
            if ($.browser.msie) $("#subnav_" + rel).show();
            else $("#subnav_" + rel).stop().fadeIn(500);
        }, 500);
    }, function() {

    });

    $("#navigation .sub_navigation").hover(function() {
        clearTimeout(intent_timeout);
        var n = $(this).attr('id').replace('subnav_', '');
        $('#navigation .navigation a[rel=' + n + ']').addClass('current');
    }, function() {
    });

    $("#navigation .sub_navigation li a").hover(function() {
        var prev_current = $("#navigation .sub_navigation li a.current").removeClass("current");
        Cufon.replace(prev_current, {
            hover: true
        });
    }, function() {
    });

    $("#navigation .navigation li a:not([rel])").hover(function() {
        $(".sub_navigation").hide();
    }, function() {
    });

    $("#navigation").hover(function() {
        clearTimeout(ptimeout);
    }, function() {
        $('#navigation .navigation a').removeClass('current');
        ptimeout = setTimeout(function() {
            var rel = $(pcurrent).addClass('current').attr('rel');
            $(".sub_navigation").hide().css('opacity', 1);
            if ($(pcurrent).parents('.navigation').length > 0) {
                if ($.browser.msie) $('#subnav_' + rel).show();
                else $('#subnav_' + rel).stop().fadeIn(500);
                Cufon.replace(pcurrent, {
                    textShadow: "1px 1px rgba(51, 51, 51, 0.5)",
                    hover: true
                });
            }
            else {
                rel = $(pcurrent).parents('.sub_navigation').css({ 'opacity': 1, 'display': 'block' }).attr('id');
                if (rel == undefined) return;
                rel = rel.substring(7);
                var pcurrent_section = $('#navigation .navigation a[rel=' + rel + ']').addClass('current');
                Cufon.replace(pcurrent_section, {
                    textShadow: "1px 1px rgba(51, 51, 51, 0.5)",
                    hover: true
                });
                Cufon.replace(pcurrent, {
                    hover: true
                });
            }
        }, 3000);
    });

    $('#print_playlist').click(function() {
        window.open(this.href, '', 'width=100,height=100,left=0,location=no,menubar=no,resizable=yes,scrollbars=no,status=no,titlebar=no,toolbar=no,top=0');
        return false;
    });
}

// ==========================================================================================================
// =============================== OTHER CUFON REPLACEMENTS =================================================
// ==========================================================================================================

function otherCufon() {
    if ($('#quick_registration').length) {
        Cufon.replace("#quick_registration p");
    }
}

// ==========================================================================================================
// =============================== AUTOSUGGEST ==============================================================
// ==========================================================================================================

function autosuggest() {
    $("input.autosuggest").autocomplete("/Services/Autosuggest.asmx/GetTerms", {
        parse: function(data) {
            var parsed = [];

            $(data).find("string").each(function() {
                parsed[parsed.length] = {
                    data: [$(this).text()],
                    value: $(this).text(),
                    result: [$(this).text()]
                };
            });
            return parsed;
        },
        dataType: "xml",
        datakey: "string",
        max: 5,
        delay: 100,
        minChars: 3,
        selectFirst: false,
        extraParams: { searchType: $("select.ddlSearchType option:selected").text() }
    });
}

function manageSearchTextBox(obj) {
    $("input.autosuggest").flushCache();
    $("input.autosuggest").setOptions({ extraParams: { searchType: obj.options[obj.selectedIndex].value} });
}

// ==========================================================================================================
// =============================== VIDEO PLAYER =============================================================
// ==========================================================================================================

var VIDEO_PLAYER = {
    isAnimating: false,
    currentPanel: 1,
    totalAssets: 0,
    totalPanels: 0,
    lastPanelAssetCount: 0,
    distance: 60 * 4,
    duration: 200,
    easing: '',
    toggleAnimation: function() {
        VIDEO_PLAYER.isAnimating = !VIDEO_PLAYER.isAnimating;
    },
    params: {
        wmode: "transparent",
        allowscriptaccess: "always",
        allowfullscreen: "true",
        bgcolor: "#000000"
    },
    attributes: {
        id: "video_swf",
        name: "video_player"
    }
}

function getFlashMovie(movieName) {
    var isIE = navigator.appName.indexOf("Microsoft") != -1;
    return (isIE) ? window[movieName] : document[movieName];
}

function videoplayer() {
    if ($('#video_player.home').length) videoplayerHome();
    else if ($('#video_player.landing').length) videoplayerLanding();
    else if ($('#video_player.slice').length) videoplayerSlice();
    else if ($('#trailers').length) videoplayerTrailers();
}

function videoplayerHome() {
    var date = new Date();
    var timestamp = date.getTime();
    var homeXmlUrl = "/Common/XML/videos.ashx?type=Homepage";
    var flashvars = {
        XmlUrl: homeXmlUrl,
        switchSpeed: 5
    };

    swfobject.embedSWF("/Common/Flash/videoplayer.swf", "video_swf", "480", "270", "9.0.115", "", flashvars, VIDEO_PLAYER.params, VIDEO_PLAYER.attributes, function(e) {
        if (!e.success) return;
        if (navigator.appName.indexOf("Microsoft") != -1) window.video_player = swfobject.getObjectById("video_swf");
        $.ajax({
            url: homeXmlUrl,
            dataType: "xml",
            success: function(data) {
                var lis = '';
                $(data).find('asset').each(function() {
                    lis += '<li><a><em>' + $(this).find('category').text() + '</em><br />' + $(this).find('title').text() + '</a></li>';
                });
                $('#video_player.home #videos ul').append(lis);
                Cufon.replace("#video_player.home #videos li a", { hover: true });

                VIDEO_PLAYER.totalAssets = $('#video_player li').length;
                VIDEO_PLAYER.totalPanels = Math.ceil(VIDEO_PLAYER.totalAssets / 4);
                VIDEO_PLAYER.lastPanelAssetCount = VIDEO_PLAYER.totalAssets % 4;

                $('#video_player .controls').click(function() {
                    if (VIDEO_PLAYER.isAnimating) return;
                    VIDEO_PLAYER.toggleAnimation();

                    var top = parseInt($('#video_player ul').css('margin-top').split('px')[0]);
                    var calculatedDistance;

                    if ($(this).attr('id') == 'down') {
                        if (VIDEO_PLAYER.currentPanel == VIDEO_PLAYER.totalPanels) {
                            VIDEO_PLAYER.toggleAnimation();
                            return;
                        }
                        calculatedDistance = top - VIDEO_PLAYER.distance;
                        if ((VIDEO_PLAYER.currentPanel == VIDEO_PLAYER.totalPanels - 1) && (VIDEO_PLAYER.lastPanelAssetCount != 0)) {
                            calculatedDistance += 60 * (4 - VIDEO_PLAYER.lastPanelAssetCount);
                        }
                        $('#video_player ul').stop().animate({ 'marginTop': calculatedDistance }, VIDEO_PLAYER.duration, VIDEO_PLAYER.easing, VIDEO_PLAYER.toggleAnimation);
                        VIDEO_PLAYER.currentPanel++;
                    } else {
                        if (VIDEO_PLAYER.currentPanel == 1) {
                            VIDEO_PLAYER.toggleAnimation();
                            return;
                        }
                        calculatedDistance = top + VIDEO_PLAYER.distance;
                        if ((VIDEO_PLAYER.currentPanel == 2) && (VIDEO_PLAYER.lastPanelAssetCount != 0)) {
                            calculatedDistance -= 60 * (4 - VIDEO_PLAYER.lastPanelAssetCount);
                        }
                        $('#video_player ul').stop().animate({ 'marginTop': calculatedDistance }, VIDEO_PLAYER.duration, VIDEO_PLAYER.easing, VIDEO_PLAYER.toggleAnimation);
                        VIDEO_PLAYER.currentPanel--;
                    }
                });

                $('#video_player.home #videos li a').live('click', function() {
                    $('#video_player.home #videos li a.selected').removeClass('selected');
                    $(this).addClass('selected');
                    Cufon.replace($('#video_player.home #videos li a'));
                    getFlashMovie("video_player").switchAsset($('#video_player.home #videos li a').index(this));
                });

                $('#video_player.home #videos li a:eq(0)').addClass('selected');
                Cufon.replace($('#video_player.home #videos li a'));
            }
        });
    });
}

var prevIndex = 0;
function switchPanel(index) {
    if (VIDEO_PLAYER.totalAssets > 4) {
        if (VIDEO_PLAYER.isAnimating) return;
        VIDEO_PLAYER.toggleAnimation();
        if (index == 0) {
            $('#video_player ul').stop().animate({ 'marginTop': 0 }, VIDEO_PLAYER.duration, VIDEO_PLAYER.easing, VIDEO_PLAYER.toggleAnimation);
            VIDEO_PLAYER.currentPanel = 1;
        } else if ((index == VIDEO_PLAYER.totalAssets - 1) && prevIndex == 0) {
            var calculatedDistance = -((VIDEO_PLAYER.totalPanels - 1) * 240);
            if (VIDEO_PLAYER.lastPanelAssetCount != 0) calculatedDistance += (4 - VIDEO_PLAYER.lastPanelAssetCount) * 60;
            $('#video_player ul').stop().animate({ 'marginTop': calculatedDistance }, VIDEO_PLAYER.duration, VIDEO_PLAYER.easing, VIDEO_PLAYER.toggleAnimation);
            VIDEO_PLAYER.currentPanel = VIDEO_PLAYER.totalPanels;
        } else {
            VIDEO_PLAYER.toggleAnimation();
            if (index > prevIndex && index % 4 == 0) {
                $('#video_player #down').trigger('click');
            } else if ((index < prevIndex) && (index == VIDEO_PLAYER.totalAssets - 5)) {
                $('#video_player #up').trigger('click');
            }
        }
        prevIndex = index;
    }
    $('#video_player.home #videos li a.selected').removeClass('selected');
    $('#video_player.home #videos li a').eq(index).addClass('selected');
    Cufon.replace("#video_player.home #videos li a", { hover: true });
}

function videoplayerTrailers() {
    $('#trailers .results a.trailer_link').click(function(e) {
        e.preventDefault();
        var flashvars = {
            XmlUrl: makeTrailerXml($(this).attr('href'), $(this).next().attr('href'))
        };

        swfobject.embedSWF("/Common/Flash/videoplayer640.swf", "video_swf", "640", "360", "9.0.115", "", flashvars, VIDEO_PLAYER.params, VIDEO_PLAYER.attributes);
    });

    $('#popular .title a, #popular .details a').click(function(e) {
        e.preventDefault();
        var flashvars = {
            XmlUrl: makeTrailerXml($(this).attr('href'), $(this).parent().nextAll('.trailer_info_item').find('a').attr('href'))
        };
        swfobject.embedSWF("/Common/Flash/videoplayer640.swf", "video_swf", "640", "360", "9.0.115", "", flashvars, VIDEO_PLAYER.params, VIDEO_PLAYER.attributes);
    });

    var trailer_xml = "<assets><asset><media>/Common/Images/banner_trailers_ins.jpg</media></asset></assets>";
    if ($('#trailer').hasClass('fightback')) trailer_xml = "<assets><asset><title>Great in Gallipoli</title><media>/Common/Video/Fightback/gallipoli.flv</media></asset><asset><title>Too many ads on TV!</title><media>/Common/Video/Fightback/ftatv.flv</media></asset><asset><title>Pay TV is repetitive!</title><media>/Common/Video/Fightback/paytv.flv</media></asset><asset><title>The cinema is expensive!</title><media>/Common/Video/Fightback/cinema.flv</media></asset><asset><title>Follow your basic instinct</title><media>/Common/Video/Fightback/basicinstinct.flv</media></asset><asset><title>It's buffering...</title><media>/Common/Video/Fightback/buffering.flv</media></asset></assets>";
    if ($('#trailer').hasClass('supernatural')) trailer_xml = "<assets><asset><title>Angel Of The Lord 2</title><media>/common/video/supernatural/angelofthelord.flv</media></asset></assets>";
    swfobject.embedSWF("/Common/Flash/videoplayer640.swf", "video_swf", "640", "360", "9.0.115", "", { XmlUrl: trailer_xml }, VIDEO_PLAYER.params, VIDEO_PLAYER.attributes);
}

function makeTrailerXml(media, link) {
    return "<assets><asset><media>" + media + "</media><link>" + link + "</link></asset></assets>";
}

function videoplayerLanding() {
    var homeXmlUrl = "home";
    var date = new Date();
    var timestamp = date.getTime();

    var page = window.location.pathname;
    page = page.substring(1, page.indexOf("/Default.aspx"));
    switch (page) {
        case "Movies":
            homeXmlUrl = "Movies";
            break;
        case "TV":
            homeXmlUrl = "TV";
            break;
        case "Games":
            homeXmlUrl = "Games";
            break;
        case "FamilyKids":
            homeXmlUrl = "Family";
            break;
    }

    homeXmlUrl = "/Common/XML/videos.ashx?type=" + homeXmlUrl;

    var flashvars = {
        XmlUrl: homeXmlUrl,
        switchSpeed: 5
    };
    swfobject.embedSWF("/Common/Flash/videoplayer.swf", "video_swf", "480", "270", "9.0.115", "", flashvars, VIDEO_PLAYER.params, VIDEO_PLAYER.attributes);
}

function videoplayerSlice() {
    var date = new Date();
    var timestamp = date.getTime();
    var homeXmlUrl = "/Common/Flash/home.xml?time=" + timestamp;
    var flashvars = {
        XmlUrl: homeXmlUrl,
        switchSpeed: 5
    };
    swfobject.embedSWF("/Common/Flash/videoplayer.swf", "video_swf", "100%", "100%", "9.0.115", "", flashvars, VIDEO_PLAYER.params, VIDEO_PLAYER.attributes);
}

// ==========================================================================================================
// =============================== CAROUSEL =================================================================
// =============================== AND TABS =================================================================
// ==========================================================================================================

var CAROUSEL = {
    timer: false,
    liwidth: 142,
    modal: {
        show: function(e, i) {
            var html = $(e).next("div").html();
            var pos = $(e).position();

            // set index of visible modal ready for check below (show/hide)
            CAROUSEL.modal.i = i;

            // modal positioning
            $("#carousel_info")
                .css({ top: pos.top + 50, left: pos.left - 101.5 })
                .empty()
                .html(html)
                .fadeIn(500);
        },
        i: -1
    }
}

function carousel() {
    //add class last to the last li in every list
    $('#carousel ul.items li:last-child').addClass('last');

    // bind events for info modal
    $("#carousel ul.items li").find("img").bind("mouseenter", function(e) {
        var img_a = $(this).parent();
        var img_li = $(this).parent().parent();
        var index = $(this).closest(".items").find("> li").index(img_li);
        if ($("#carousel_info").is(":hidden")) {
            CAROUSEL.modal.show(img_a, index);
        }
        else {
            // hide modal
            $("#carousel_info").hide();
            CAROUSEL.modal.show(img_a, index);
        }
    });

    $('#carousel').mouseleave(function() {
        $('#carousel_info').hide();
    });

    // activate tabs
    $(".ui-tabs-nav a")
    .click(function(e) {
        e.preventDefault();
        if ($(this).hasClass('prev') || $(this).hasClass('next')) return; // ignore arrow buttons in format carousel

        if ($("#carousel_info").is(":visible")) { $("#carousel_info").hide(); }

        var href = $(this).attr("href").split("#"),
            url = href[0],
            context = "#" + href[1];

        $(this).parent().siblings().removeClass("ui-tabs-selected").end().addClass("ui-tabs-selected");
        Cufon.replace($(this).parent().siblings(), {
            textShadow: "1px 1px rgba(51, 51, 51, 0.5)",
            hover: true
        });

        // for tabs not in carousel
        if ($(this).parents('#carousel').length == 0) {
            $(this).closest('.ui-tabs-nav').siblings(".items").hide();
            $(this).closest('.ui-tabs-nav-scrollable').siblings(".items").hide();
            $(context).fadeIn(500);
            if ($('body').hasClass('msie')) $(this).parents('.panel').find('.pl, .pr').each(function() { $(this).hide().show(); });
            return;
        }

        $("#carousel ul.items").each(function() {
            // position to work out width before fadein
            var $this = $(this).css({ display: "block", marginTop: "-9999em", marginLeft: "-9999em" });
            var l = $("> li", $this).length;
            // remove margin right value as li.last has no margin
            var w = (l * CAROUSEL.liwidth) - parseInt($("> li:eq(0)", $this).css("marginRight"), 10);
            //if the list has no items the width is 0 not NaN
            if (l == 0) w = 0;
            $this.css({ marginTop: "", marginLeft: "", display: "none" }).width(w);
        });

        // animate/vary size scrollbar width according to amount of li's
        // remove = arbitary amount to remove per li
        var remove = 20;
        $("#sb_track .wrapper").css("left", 0);
        $("#sb_track .wrapper").find("#sbt").width("912px");
        $("#sb_track .wrapper").find("#sbt").animate({ width: $("#sbt").width() - ($(context + "> li").length * remove) }, 500);

        //fake preloading on initial load, then display each subsequent tab super quick
        if (!$("#viewport").hasClass('loading')) {
            CAROUSEL.timer = setTimeout(function() {
                $(context).fadeIn(100);
                scrollSetup();
            }, 100);
        }
        else {
            CAROUSEL.timer = setTimeout(function() {
                $("#viewport").removeClass("loading");
                $(context).fadeIn(500);
                scrollSetup();
            }, 1500);
        }
    });


    $('.ui-tabs-nav').each(function() {
        $(this).find('a:eq(0)').trigger('click');
    });

    $("#sb_track .wrapper").bind("mousedown", function() {
        $(this).find("#sbt").addClass("active");
    }).bind("mouseup", function() {
        $(this).find("#sbt").removeClass("active");
    }).bind("dragstart", function() {
        $("body").css("cursor", "pointer");
    }).bind("dragend", function() {
        $(this).find("#sbt").removeClass("active");
        $("body").css("cursor", "");
    }).bind("drag", function(e) {

        if ($("#carousel_info").is(":visible")) { $("#carousel_info").hide(); }

        var width = $("#sb_track .wrapper").width(),
        maxLeft = 914 - width;

        // scrollbar movement
        e.offsetX -= $("#scrollbar").offset().left;
        var offset = e.offsetX > maxLeft ? maxLeft : Math.max(0, e.offsetX);
        $(this).css({ left: offset });

        // carousel movement
        var $ul = $("ul.items:visible");
        var move = (-offset * ($ul.outerWidth() - 960)) / ($("#sb_track .wrapper").width() - 914);
        $ul.css("marginLeft", -move);
    });

    // scroll buttons
    $("#sb_left a, #sb_right a").click(function(e) { e.preventDefault(); });
    $("#sb_left a, #sb_right a").mousedown(function(e) {
        if ($(this).parent().attr("id") == "sb_left")
            SCROLL.intervalId = setInterval("scrollLeft()", 50);
        else
            SCROLL.intervalId = setInterval("scrollRight()", 50);
    }).mouseup(function(e) {
        clearInterval(SCROLL.intervalId);
        SCROLL.carouselMoveSpeed = 1;
    }).mouseout(function(e) {
        clearInterval(SCROLL.intervalId);
        SCROLL.carouselMoveSpeed = 1;
    });
}

var SCROLL = {
    intervalId: function() { },
    carouselMoveBy: 0,
    carouselMoveSpeed: 0,
    carouselMoveSpeedModifier: 0.2,
    carouselMaxRight: 0,
    scrollBarWidth: 0,
    scrollBarMaxLeft: 0
}

function parseDate(xmlDate) {
    if (!/^[0-9]{4}\-[0-9]{2}\-[0-9]{2}/.test(xmlDate)) {
        throw new RangeError("xmlDate must be in ISO-8601 format YYYY-MM-DD.");
    }
    return new Date(Date.UTC(xmlDate.substring(0, 4), xmlDate.substring(5, 7) - 1, xmlDate.substring(8, 10), xmlDate.substring(11, 13)));
}


function scrollLeft() {
    var $ul = $("ul.items:visible");
    var marginLeft = $ul.css("marginLeft").split('px')[0];
    if (marginLeft > (-SCROLL.carouselMoveBy) * SCROLL.carouselMoveSpeed) {
        $ul.css("marginLeft", 0);
        $("#sb_track .wrapper").css("left", 0);
    } else {
        $ul.css("marginLeft", marginLeft - (-SCROLL.carouselMoveBy) * SCROLL.carouselMoveSpeed);
        $("#sb_track .wrapper").css("left", (-($ul.css("marginLeft").split('px')[0]) / SCROLL.carouselMaxRight) * SCROLL.scrollBarMaxLeft);
        SCROLL.carouselMoveSpeed = SCROLL.carouselMoveSpeed + SCROLL.carouselMoveSpeedModifier;
    }
}

function scrollRight() {
    var $ul = $("ul.items:visible");
    var marginLeft = $ul.css("marginLeft").split('px')[0];
    if (marginLeft < (-SCROLL.carouselMaxRight + SCROLL.carouselMoveBy * SCROLL.carouselMoveSpeed)) {
        $ul.css("marginLeft", (-SCROLL.carouselMaxRight));
        $("#sb_track .wrapper").css("left", SCROLL.scrollBarMaxLeft);
    } else {
        $ul.css("marginLeft", marginLeft - SCROLL.carouselMoveBy * SCROLL.carouselMoveSpeed);
        $("#sb_track .wrapper").css("left", (-($ul.css("marginLeft").split('px')[0]) / SCROLL.carouselMaxRight) * SCROLL.scrollBarMaxLeft);
        SCROLL.carouselMoveSpeed = SCROLL.carouselMoveSpeed + SCROLL.carouselMoveSpeedModifier;
    }
}

function scrollSetup() {
    SCROLL.carouselMoveBy = 10;
    SCROLL.carouselMoveSpeed = 1;
    SCROLL.carouselMaxRight = $("ul.items:visible").width() - 960 + 30;
    SCROLL.scrollBarWidth = $("#sb_track .wrapper").width();
    SCROLL.scrollBarMaxLeft = 914 - SCROLL.scrollBarWidth;
}

// ==========================================================================================================
// =============================== FORMAT SCROLLER ==========================================================
// ==========================================================================================================


var FORMATSCROLL = {
    intervalId: function() { },
    carouselMoveBy: 10,
    carouselMoveSpeed: 1,
    carouselMoveSpeedModifier: 0.1,
    carouselMaxRight: 0,
    tabsTotalWidth: 0
}

function formatScrollLeft() {
    if (!FORMATSCROLL.tabsTotalWidth) formatCarouselTabsTotalWidth();

    var $ul = $(".ui-tabs-nav-scrollable ul");
    var marginLeft = $ul.css("marginLeft").split('px')[0];
    if (marginLeft > (-FORMATSCROLL.carouselMoveBy) * FORMATSCROLL.carouselMoveSpeed) {
        $ul.css("marginLeft", 24);
    } else {
        $ul.css("marginLeft", marginLeft - (-FORMATSCROLL.carouselMoveBy) * FORMATSCROLL.carouselMoveSpeed);
        FORMATSCROLL.carouselMoveSpeed = FORMATSCROLL.carouselMoveSpeed + FORMATSCROLL.carouselMoveSpeedModifier;
    }
}

function formatScrollRight() {
    if (!FORMATSCROLL.tabsTotalWidth) formatCarouselTabsTotalWidth();

    var $ul = $(".ui-tabs-nav-scrollable ul");
    var marginLeft = $ul.css("marginLeft").split('px')[0];
    if (marginLeft < (-FORMATSCROLL.carouselMaxRight + FORMATSCROLL.carouselMoveBy * FORMATSCROLL.carouselMoveSpeed)) {
        $ul.css("marginLeft", (-FORMATSCROLL.carouselMaxRight));
    } else {
        $ul.css("marginLeft", marginLeft - FORMATSCROLL.carouselMoveBy * FORMATSCROLL.carouselMoveSpeed);
        FORMATSCROLL.carouselMoveSpeed = FORMATSCROLL.carouselMoveSpeed + FORMATSCROLL.carouselMoveSpeedModifier;
    }
}

function formatCarousel() {
    if ($('.ui-tabs-nav-scrollable').length == 0) return;

    var totalWidth = 0;
    $('.ui-tabs-nav-scrollable li').each(function() { totalWidth += $(this).width(); });
    if (totalWidth < 590) return;

    $('#formats').addClass('scrollable-active').find('.icon').remove();

    $(".ui-tabs-nav-scrollable a.prev, .ui-tabs-nav-scrollable a.next").click(function(e) {
        e.preventDefault();
    }).mousedown(function(e) {
        if ($(this).hasClass('prev'))
            FORMATSCROLL.intervalId = setInterval("formatScrollLeft()", 50);
        else
            FORMATSCROLL.intervalId = setInterval("formatScrollRight()", 50);
    }).mouseup(function(e) {
        clearInterval(FORMATSCROLL.intervalId);
        FORMATSCROLL.carouselMoveSpeed = 1;
    }).mouseout(function(e) {
        clearInterval(FORMATSCROLL.intervalId);
        FORMATSCROLL.carouselMoveSpeed = 1;
    });
}

function formatCarouselTabsTotalWidth() {
    var totalWidth = 0;
    $('.ui-tabs-nav-scrollable li').each(function() { totalWidth += $(this).width(); });
    FORMATSCROLL.tabsTotalWidth = totalWidth;
    FORMATSCROLL.carouselMaxRight = totalWidth - 618;
}

// ==========================================================================================================
// =============================== TEXT MASK ================================================================
// ==========================================================================================================

function textmask() {
    $("label.block").bind("click", function(e) {
        $label = $(e.target).parent();

        if ($label.find("input").val() == "") {
            $label.find("span").addClass("hide");
            $(this).find("input").focus();
        } else if ($label.find("input").val() != "") {
            $label.find("span").addClass("hide");
        } else {
            $label.find("span").removeClass("hide");
        }
    });
    $("label.block input").bind("focus", function() {
        $(this).parent().find("span").addClass("hide");
    }).bind("blur", function(e) {
        $label = $(e.target).parent();
        $this = $(this);

        if ($this.val() == "") {
            $label.find("span").removeClass("hide");
        } else {
            $label.find("span").addClass("hide");
        }
    }).each(function() {
        $(this).trigger('blur');
    });
}

// ==========================================================================================================
// =============================== USER BAR =================================================================
// ==========================================================================================================

var playlistPageNumber = 1;

function userbar() {
    $(".ub_tabimg").click(function() {
        var $this = $(this);
        var $tab = $this.closest(".ub_tab");
        $tab.slideTab();
        if (($tab.attr("id") == 'ub_playlist') && ($tab.find('.ub_tabimg').hasClass('active'))) {
            playlistShowPage(playlistPageNumber);
        }
    }).hoverClass("over");

    $('body').bind('click', function(e) {
        if ($(e.target).closest('#user_bar').length == 0)
            $('.ub_tabimg.active').click();
    });

    $("#ub_playlist #paging li a").click(function() {
        if ($(this).parent().hasClass('next')) {
            playlistShowPage(++playlistPageNumber);
        } else {
            playlistShowPage(--playlistPageNumber);
        }
    });

    //add to playlist functionality
    $(".actions_playlist").click(function(e) {
        e.preventDefault();
        var o = $(this);
        var productId = $("a", this).attr("id");
        var catalog = $("a", this).attr("href").replace("#", "");
        o.empty().addClass('working');
        if (o.hasClass('add')) {
            $.ajax(
            {
                type: "POST",
                url: "/services/playlist.asmx/AddToList",
                data: "catalogId=" + catalog + "&productId=" + productId,
                success: function() {
                    console.log(this.data);
                    o.removeClass('working').attr("class", "actions_playlist remove").html('Remove from playlist <a id=' + productId + ' title="Remove from playlist" href="#' + catalog + '">-</a>');
                }
            });
        }
        else {
            $.ajax(
            {
                type: "POST",
                url: "/services/playlist.asmx/RemoveFromList",
                data: "catalogId=" + catalog + "&productId=" + productId,
                success: function() {
                    console.log(this.data);
                    if ($('form').hasClass('playlist')) location.reload(true);
                    else o.removeClass('working').attr("class", "actions_playlist add").html('Add to playlist <a id=' + productId + ' title="Add to playlist" href="#' + catalog + '">-</a>');
                }
            });
        }
    });

    //    $('#login_site').click(function() {
    //        var username = $('#txtUsername').val();
    //        var password = $('#pwdPassword').val();
    //        var isPersistent = $('#chkRememberMe').is(':checked');
    //        var customInfo = null;
    //        var redirectUrl = null;
    //        
    //        // Log them in.
    //        ssa.login(username,
    //                  password,
    //                  isPersistent,
    //                  customInfo,
    //                  redirectUrl,
    //                  onLoginComplete,
    //                  onError);
    //        
    //    });

    //    $('#logout_site').click(function() {
    //        // if login successful then
    //        $('#user_bar').animate({ top: -36 }, 750, function() {
    //            $(this).addClass('public');
    //        }).animate({ top: 0 }, 750);
    //    });

    //    $('#ub_welcome .ub_welcome_anon a').click(function() {
    //        $('#ub_login .ub_tabimg').trigger('click');
    //    });
}

function playlistShowPage(i) {
    $("#playlist").removeClass('done').empty();
    $("#ub_playlist #paging li, #ub_playlist .rollover").hide();
    $.ajax({
        url: "/services/playlist.asmx/GetList",
        data: "pageNumber=" + i,
        type: "POST",
        success: function(data) {
            if ($(data).find('PlayListObject').length > 0) {
                $(data).find('PlayListObject').each(function() {
                    var displayName = $("DisplayName", this).text();
                    var img = $("ImageUrl", this).text();
                    var rating = $("Classification", this).text();
                    if (rating.length) rating = "(" + rating + ")";
                    var genre = $("Genre", this).text();
                    var link = $("ProductUrl", this).text();
                    $("#playlist", $tab).append('<li><a href="' + link + '"><img src="' + img + '" height="72" width="50" /></a><div class="info"><a href="' + link + '">' + displayName + '</a><br />' + genre + ' ' + rating + '</div></li>');
                });
                if (i > 1) $("#ub_playlist #paging .prev").show();
                if (i < $(data).find('PageSize').text()) $("#ub_playlist #paging .next").show();
                $("#ub_playlist .rollover").show();
            } else {
                $("#playlist", $tab).append('<li class=\"empty\">Your playlist is empty.</li>');
            }
            $("#playlist").addClass('done');
        }
    });
}

// ==========================================================================================================
// =============================== PAGE QUERY ===============================================================
// ==========================================================================================================

function PageQuery(q) {
    if (q.length > 1) this.q = q.substring(1, q.length);
    else this.q = null;
    this.keyValuePairs = new Array();
    if (q) {
        for (var i = 0; i < this.q.split("&").length; i++) {
            this.keyValuePairs[i] = this.q.split("&")[i];
        }
    }
    this.getKeyValuePairs = function() { return this.keyValuePairs; }
    this.getValue = function(s) {
        for (var j = 0; j < this.keyValuePairs.length; j++) {
            if (this.keyValuePairs[j].split("=")[0] == s)
                return this.keyValuePairs[j].split("=")[1];
        }
        return false;
    }
    this.getParameters = function() {
        var a = new Array(this.getLength());
        for (var j = 0; j < this.keyValuePairs.length; j++) {
            a[j] = this.keyValuePairs[j].split("=")[0];
        }
        return a;
    }
    this.getLength = function() { return this.keyValuePairs.length; }
}

// ==========================================================================================================
// =============================== PLAIN LIST ===============================================================
// ==========================================================================================================

function plainList() {
    $('#list > li, #watchlist > li .inner').hover(function() {
        if ($(this).hasClass('current_comp')) $(this).addClass('current_comp_over');
        else $(this).addClass('over');
    }, function() {
        if ($(this).hasClass('current_comp')) $(this).removeClass('current_comp_over');
        else $(this).removeClass('over');
    });
}

// ==========================================================================================================
// =============================== REMINDER =================================================================
// ==========================================================================================================

function reminder() {
    $('a#reminder').click(function() {
        $('#modal_info.reminder').show().find(".close").click(function() {
            $(this).parent().hide();
        });
    });
}

// ==========================================================================================================
// =============================== MUST WATCH LISTS =========================================================
// ==========================================================================================================

function watchList() {
    if (('#watchlist').length == 0) return;
    $('#watchlist .products').hide();
    $('#watchlist .toggle').click(function() {
        if ($('body').hasClass('msie')) $('#watchlist .products').hide();
        else $('#watchlist .products').slideUp();
        $('#watchlist > li .inner').removeClass('expanded').next().find('> li').removeClass('expanded');
        if ($(this).hasClass('collapse')) {
            $(this).removeClass('collapse');
        }
        else {
            $('#watchlist .toggle').removeClass('collapse');
            var expandthis = $(this).addClass('collapse').parent().addClass('expanded').next();
            if ($('body').hasClass('msie')) $(expandthis).show();
            else $(expandthis).slideDown();
            $(expandthis).find('> li').addClass('expanded');
        }
        if ($('body').hasClass('msie')) $('#main .pl, #main .pr').each(function() { $(this).hide().show(); });
    });
    $('#watchlist > li .inner').hover(function() {
        $(this).addClass('over');
    }, function() {
        $(this).removeClass('over');
    });
    if ($('body').hasClass('msie')) $('#main .pl, #main .pr').each(function() { $(this).hide().show(); });

    $('.print_watchlist').click(function(e) {
        $(this).attr('href', window.location + "?print=" + $(this).parent().parent().prevAll('h4').text() + "&auto=true");
        window.open($(this).attr('href'), '', 'width=100,height=100,left=0,location=no,menubar=no,resizable=yes,scrollbars=no,status=no,titlebar=no,toolbar=no,top=0');
        e.preventDefault();
    });

    if (window.location.hash == "#howto") {
        $('#watchlist a.toggle:eq(3)').click();
    }
}

// ==========================================================================================================
// ====================== USERNAME / E-MAIL / PASSWORD VALIDATION ===========================================
// ==========================================================================================================

function passwordValidation() {
    $(".registration .password").pstrength();
}

function ValidateUserName(source, args) {
    var usr = args.Value;
    if (usr.length >= 3) {
        $(".txtUserNameCheck").text('');
        $(".txtUserNameCheck").addClass('registrationChecking').text('Checking availability...');
        $.ajax({
            async: false,
            type: "POST",
            url: "/services/authentication.asmx/CheckIfUsernameExists",
            data: "userName=" + usr,
            success: function(data, textStatus) {
                var req;
                req = data.documentElement.firstChild.nodeValue;
                if (req == 'false') {
                    $('.txtUserNameCheck').removeClass('registrationChecking').html('<img class="margin-push" src="/common/images/icon_tick.gif"/><span style="color: #29b63a;">Available</span>');
                    args.IsValid = true;
                }
                else {
                    $('.txtUserNameCheck').removeClass('registrationChecking').html('<img class="margin-push" src="/common/images/icon_cross.png"/><span style="color: #ff0909;">Taken</span>');
                    args.IsValid = false;
                }
            }
        });
    }
    else {
        $(".txtUserNameCheck").removeClass('registrationChecking').html('<img class="margin-push" src="/common/images/icon_cross.png"/><span style="color: #ff0909;">Min 3 characters.</span>');
        args.IsValid = false;
    }
}

function ValidateEmail(source, args) {
    var email = args.Value;
    var re = new RegExp("^.+@[^\.].*\.[a-z]{2,}$");
    if (email.match(re)) {
        $(".txtEmailCheck").text('');
        $(".txtEmailCheck").addClass('registrationChecking').text('Checking availability...');
        $.ajax({
            async: false,
            type: "POST",
            url: "/services/authentication.asmx/CheckIfEmailExists",
            data: "email=" + email,
            success: function(data) {
                var req;
                req = data.documentElement.firstChild.nodeValue;
                if (req == 'false') {
                    $('.txtEmailCheck').removeClass('registrationChecking').html('<img class="margin-push" src="/common/images/icon_tick.gif"/><span style="color: #29b63a;">Available</span>');
                    args.IsValid = true;
                }
                else {
                    $('.txtEmailCheck').removeClass('registrationChecking').html('<img class="margin-push" src="/common/images/icon_cross.png"/><span style="color: #ff0909;">Taken</span>');
                    args.IsValid = false;
                }
            },
            error: function() {
                $('.txtEmailCheck').removeClass('registrationChecking').html('<img class="margin-push" src="/common/images/icon_cross.png"/><span style="color: #ff0909;">Sorry something broke</span>');
                args.IsValid = false;
            }
        });
    }
    else {
        $(".txtEmailCheck").removeClass('registrationChecking').html('<img class="margin-push" src="/common/images/icon_cross.png"/><span style="color: #ff0909;">Invalid e-mail.</span>');
        args.IsValid = false;
    }
}

// ==========================================================================================================
// ================================= COMPETITION TERMS ======================================================
// ==========================================================================================================

function competitionPopup() {
    $('.popup').click(function(e) {
        e.preventDefault();
        var href = $(this).attr('href');
        window.open(href, 'popup', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=600,height=400');
    });
}

// ==========================================================================================================
// =============================== FORMS ====================================================================
// ==========================================================================================================

function formatForms() {
    // registration form lines
    if ($('.contact_us, .registration, .comp-details, .rewards-club').length == 0) return;
    $("label span").each(function() {
        var $this = $(this);
        var w = $this.outerWidth();
        $this.parent().css("backgroundPosition", w + "px center");
    });

    // terms and conditions checkbox
    $('.chkTerms input').click(function() {
        if ($(this).attr('checked')) $('.chkTermsHidden').val('true');
        else $('.chkTermsHidden').val('');
    });

    // mobile number and SMS
    if (!$('.chkSMS input').attr('checked')) $('.chkSMS input').attr('disabled', true);
    $('.txtMobile').keyup(function() {
        if ($(this).val() == "") {
            $('.chkSMS input').attr('disabled', true).attr('checked', false);
        }
        else $('.chkSMS input').attr('disabled', false);
    });
    if ($('.txtMobile').val() != "") {
        $('.chkSMS input').attr('disabled', false);
    }

    // DOB
    $('.txtDOB').focus(function() {
        if ($(this).val() == "dd/mm/yyyy") $(this).removeClass('txtDOB_on').val("");
    }).blur(function() {
        if ($(this).val() == "") $(this).addClass('txtDOB_on').val("dd/mm/yyyy");
    });
    if ($('.txtDOB').val() == "") $('.txtDOB').addClass('txtDOB_on').val("dd/mm/yyyy");
}

// ==========================================================================================================
// ================================= RATINGS ================================================================
// ==========================================================================================================

function ratings() {
    var productId = $("#productId").val();
    var catalog = $("#catalog").val();
    $('.memberRating input, .userRating input').rating({
        callback: function(value, link) {
            $.ajax(
            {
                type: "POST",
                url: "/services/playlist.asmx/AddUserRating",
                data: "catalogId=" + catalog + "&productId=" + productId + "&rating=" + value,
                success: function() {
                    $(this).attr('disabled', true);

                }
            }
        );
        }
    });
}

// ==========================================================================================================
// ================================= POLL ======================================================
// ==========================================================================================================

function pollSubmit() {

    if ($("#PollId").val() == 0) {
        $('#surveyQuestions').empty();
        pollUpdateResults();
    }

    $('#surveySubmit').click(function(e) {
        e.preventDefault();

        var id = $(".survey input:checked").attr("value");

        if (id != null) {
            $.ajax({
                type: "POST",
                url: "/services/poll.asmx/Submit",
                data: "answer=" + id,
                success: function(data) {
                    $("#surveyQuestions").fadeOut("slow", function() {
                        pollUpdateResults();
                        $('#surveyAnswers').empty();
                    });
                }
            });
        } else {
            alert('Please, choose one answer.');
        }
    });

    $('#ViewPollResults').click(function(e) {
        e.preventDefault();
        $('#surveyQuestions').hide();
        $('#surveyAnswers').empty();
        pollUpdateResults();
    });

    $('#SkipPollQuestion').click(function(e) {
        e.preventDefault();
        pollGetNextQuestion();
    });
}

function pollGetNextQuestion() {
    $.ajax({
        type: "POST",
        url: "/services/poll.asmx/GetNextQuestion",
        data: "previousPollID=" + $("#PollId").val(),
        success: function(data) {
            $(data).find('PollQuestionEventArgs').each(function() {
                if ($("Id", this).text() != 0) {
                    $('#surveyQuestions').show();
                    $('#PollId').val($("Id", this).text());
                    $('#pollQuestion').empty();
                    $('#pollQuestion').append('<p>' + $("Question", this).text() + '</p>');

                    $('#surveyAnswers').empty();
                    $('#suveryResults ul').empty();

                    var answers = $(this).find('Answers').text().split('|');

                    $('#surveyAnswers').append(
                            '<div class=\'AspNet-RadioButtonList\'>'
                            + '<ul class=\'survey\'>'
                            + '<li class=\'AspNet-RadioButtonList-Item even\'><input type=\"radio\" value=\"1\" name=\"surveyOptions\"><label>' + answers[0] + '</label></input></li>'
                            + '<li class=\'AspNet-RadioButtonList-Item even\'><input type=\"radio\" value=\"2\" name=\"surveyOptions\"><label>' + answers[1] + '</label></input></li>'
                            + '<li class=\'AspNet-RadioButtonList-Item even\'><input type=\"radio\" value=\"3\" name=\"surveyOptions\"><label>' + answers[2] + '</label></input></li>'
                            + '<li class=\'AspNet-RadioButtonList-Item even\'><input type=\"radio\" value=\"4\" name=\"surveyOptions\"><label>' + answers[3] + '</label></input></li>'
                            + '</ul>'
                            + '</div>');

                } else {
                    // No more questions
                    $('#surveyQuestions').empty();
                    $('#SkipPollQuestion').hide();
                    pollUpdateResults();
                }
            });
        }
    });
}

function pollUpdateResults() {
    $.ajax({
        type: "POST",
        url: "/services/poll.asmx/GetResults",
        data: "id=" + $("#PollId").val(),
        success: function(data) {
            $(data).find('PollResultsEventArgs').each(function() {
                $('#pollQuestion').empty();
                $('#pollQuestion').append('<p>' + $("Question", this).text() + '</p>');
                $('#suveryResults ul').empty();
                var total = $("TotalResults", this).text();
                $('#surveryResults').fadeIn("slow");
                $(this).find('PollResult').each(function() {
                    var result = $("Total", this).text();
                    var answer = $("Answer", this).text();
                    var id = $("Id", this).text();
                    var percent = Math.round((parseInt(result) / parseInt(total)) * 100);
                    if (isNaN(percent)) percent = 0;
                    $('#suveryResults ul').append("<li><p>" + answer + "</p><div><div id=\"bar" + id + "\" class=\"bar\" style=\"width:0%;\" ></div><span>" + percent + "%</span></div></li>");
                    $('#bar' + id).css({ width: "0%" }).animate({ width: percent }, 'slow');
                });
            });
        }
    });
}

// ==========================================================================================================
// ================================= PRODUCT DETAILS ========================================================
// ==========================================================================================================

function productDetails() {
    if ($('.hidable').length == 0) return;
    $("ul.hidable > li:not(.image)").each(function() {
        if (($(this).text().split(":", 2).length == 1) || (jQuery.trim($(this).text().split(":", 2)[1]) == "") || (jQuery.trim($(this).text().split(":", 2)[1]) == "mins") || (jQuery.trim($(this).text().split(":", 2)[1]) == "0 mins")) {
            $(this).hide();
        }
    });
}

// ==========================================================================================================
// ================================= BANNER TAKEOVER ========================================================
// ==========================================================================================================

function bannerTakeOver() {
    if ($('#bannerTakeOver').length == 0) return;
    $('#aspnetForm').addClass('bannerTakeOver');
    $('#bannerTakeOver').addClass('js');
    $('.bannerTakeOver-close').click(function(e) {
        e.preventDefault();
        $('#bannerTakeOver').remove();
    });
    $(window).load(function() {
        var autoHide = setTimeout(function() {
            $('#bannerTakeOver').remove();
        }, 25000);
    });

}

// ==========================================================================================================
// ================================= JOIN NOW MEMBERSHIP ====================================================
// ==========================================================================================================

function joinNowClick() {
    $('#imgJoinNow').click(function(e) {
        e.preventDefault();

        window.location = "/Registration.aspx?email=" + $('#txtQuickRegistrationEmail').val();
    });
}

function joinNowEnter() {
    $('#txtQuickRegistrationEmail').keypress(function(e) {
        if (e.keyCode == '13') {
            e.preventDefault();

            $('#imgJoinNow').click();
        }
    });
}

// ==========================================================================================================
// ================================= READY ==================================================================
// ==========================================================================================================

$(document).ready(function() {
    //    login();
    browser();
    navigation();
    otherCufon();
    //autosuggest();
    videoplayer();
    carousel();
    formatCarousel();
    textmask();
    userbar();
    plainList();
    reminder();
    watchList();
    pollSubmit();
    if ($('form.registration').length) passwordValidation();
    competitionPopup();
    formatForms();
    ratings();
    productDetails();
    $(".rollover").rollover();
    bannerTakeOver();
    joinNowClick();
    joinNowEnter();
    partnerGallery();
});

// ==========================================================================================================
// ================================= REWARDS CLUB :: PayPal =================================================
// ==========================================================================================================

function payPalPostForm(url) {
    document.forms["aspnetForm"].action = url;
    document.forms["aspnetForm"].submit();
}

function partnerGallery() {
    if ($('#partner-gallery').length == 0) return;

    $('#partner-categories a').click(function(e) {
        e.preventDefault();
        e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();

        var $this = $(this),
            $icons = $('#partner-category-icon'),
            $logos = $('#partner-logos'),
            cat = $this.parent().attr('data-category');
        $('#partner-categories a').removeClass('current');
        $this.addClass('current');
        $icons.find('li').hide();
        $icons.find('li[data-category=' + cat + ']').show();
        $logos.find('li:not(.partner-logo-heading)').hide();
        $logos.find('li[data-category=' + cat + ']').show().eq(0).find('a').trigger('click');
        $logos.find('a').click(function() {
            $logos.find('a.current').removeClass('current');
            $(this).addClass('current');
        });
    });

    (function init() {
        // Fix styles if JS-enabled
        $('#partner-lists, #partner-offer, #partner-category-icon').addClass('hasJS');

        $('#partner-categories a:eq(0)').trigger('click');

        if (!$('#partner-gallery').hasClass('auto-scroll')) return;

        var delay = 5000; // Auto-scroll delay
        var interval; // Auto-scroll interval timer
        var timeout = null;

        var $categories = $('#partner-categories'),
            $logos = $('#partner-logos'),
            $offers = $('#partner-offer');

        // Show first offer
        $offers.find('li').hide().eq(0).show();

        // Replace partner links with index
        var partnerIndex = 0;
        $logos.find('a').each(function() {
            $(this).attr('href', '#').data('index', partnerIndex);
            partnerIndex++;
        });

        // Partner link click
        $logos.find('a').click(function(e) {
            e.preventDefault();
            e.cancelBubble = true;
            if (e.stopPropagation) e.stopPropagation();

            $logos.find('a.current').removeClass('current');
            $(this).addClass('current');

            // Show corresponding offer
            var offerIndex = $(this).data('index');
            $offers.find('li').hide().eq(offerIndex).show();
        });

        // Start auto scrolling
        interval = setInterval(autoScroll, delay);

        // Category and partner links' mouseup event delays auto-scroll interval
        $categories.find('a').mouseup(pauseAndResumeAutoScroll);
        $logos.find('a').mouseup(pauseAndResumeAutoScroll);

        function autoScroll() {
            // Get current and next items
            var $current = $logos.find('a.current').parent();
            var $next = $current.next();
            var currentDataCategory = $current.attr('data-category');
            var nextDataCategory = $next.attr('data-category');

            // Click next partner if it's in the same category
            if (currentDataCategory == nextDataCategory) {
                $next.find('a').trigger('click');
            } else {
                var $nextCategory = $categories.find('a.current').removeClass('current').parent().next();
                if ($nextCategory.length) $nextCategory.find('a').trigger('click');
                else $categories.find('a:eq(0)').trigger('click');
            }
        }

        function pauseAndResumeAutoScroll() {
            // If timeout is already set, clear it
            if (timeout) clearTimeout(timeout);

            // Clear auto-scrolling interval, then re-set it
            clearInterval(interval);
            timeout = setTimeout(function() {
                interval = setInterval(autoScroll, delay);
            }, delay * 2);
        }
    } ());
}

var numbers = '0123456789';
var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

function alpha(e, allow) {
    var k;
    k = document.all ? parseInt(e.keyCode) : parseInt(e.which);

    if (e.keyCode == 9) return true;

    return (allow.indexOf(String.fromCharCode(k)) != -1);
}

function autoTab(current, to) {
    if (current.getAttribute && current.value.length == current.getAttribute("maxlength")) {
        document.getElementById(to).focus();
    }
}
