﻿/// <reference path="../../jscripts/jquery/jquery-1.4.1-vsdoc.js" />
var phe = phe || {};
phe.aeod = phe.aeod || {};

//Lazyload Pattern
phe.aeod.user = (function () {
    var _userState = undefined;
    return {
        state: function (callback) {
            if (_userState == undefined) {
                $.ajax({
                    type: "POST",
                    url: "/ws/Ajax/Authentication.asmx/GetUserState",
                    contentType: "application/json; charset=utf-8",
                    data: "{PageID: ''}",
                    async: true,
                    //timeout: 100,
                    dataType: "json",
                    success: function (data) {
                        _userState = data;
                        callback(_userState);
                    }
                });
            }
            else {
                callback(_userState);
                return _userState;
            }
        }
    };
})();

//login base
function doLogin(form) {
    var Password = $("input[type='password']", form).val();
    var Email = $("input[type='text']", form).val();
    
    $("#LoginPassword", "#LoginForm").val(Password);
    $("#LoginEmail", "#LoginForm").val(Email);   
    $("#LoginForm").submit();
    return false;
}

//login logic
function doLoginLogic(form, RedirectURL, PlayProductID, SubSceneIndex, CommentProductID) {
    $("input[type='hidden'].SubSceneIndex", form).val("");
    //set play cookie if there was one
    if (PlayProductID) {
        //set cookie for after login to know what movie to play
        $.cookie("playproductid", PlayProductID);
    }
    
    //set play index if there is one
    if(SubSceneIndex){
        //set cookie for after login to know what movie to play
        $.cookie("subsceneindex", SubSceneIndex);
    }
    
    //set comment cookie if there was one
    if (CommentProductID) {
        //set cookie for after login to know what comment to show
        $.cookie("commentproductid", CommentProductID);
    }
        
    //use redirect url if there is one
    if (RedirectURL != undefined) {
        $("#ReturnURL", "#LoginForm").val(RedirectURL);
    }
    else { 
        $("#ReturnURL", "#LoginForm").val(document.location.href);
    }

    doLogin(form);
    return false;
}

phe.aeod.doUpdateMiniCart = function () {
    var data = $.toJSON({ foo: 1 });

    if ($("#MiniCart").hasClass('populated')) {
        return;
    }

    $('#MiniCart').addClass('populated');

    $.ajax({
        type: "Post",
        url: "/ws/Ajax/ShoppingCart.asmx/GetCartItems",
        data: data,
        async: true,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            $('#MiniCart').empty();
            var temp = $('#templates .MiniCartItem');
            if (data.d.CartItems.length == 0) {
                $('.Name', temp).text("Your cart is empty.");
                $('.Type', temp).empty();
                $('.Price', temp).empty();
                temp.clone().appendTo('#MiniCart');

            }
            else {
                $(data.d.CartItems).each(function () {
                    $('.Name', temp).text(this.Name);
                    $('.Type', temp).text(this.Type);
                    $('.Price', temp).text(this.PriceLocalizedAmountOnly);
                    temp.clone().appendTo('#MiniCart');
                });
            }
            $('.MiniCartItem:odd').css('background-color', '#F7F7F7');
            $('#headerLogout').attr('cartItemCount', data.d.CartItems.length);
        },
        error: function (data) {
            $('#MiniCart').removeClass('populated');
        }
    });
}


function loadPlayer(productID, subSceneIndex) {
    //get mms url
    if (!subSceneIndex) {
        subSceneIndex = 0;
    }
    $.ajax({
        type: "POST",
        url: "/ws/Ajax/StreamingURL.asmx/GetStreamingURL",
        data: "{subSceneIndex:" + subSceneIndex + ", productID:" + productID + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            var data = msg.d;
            if (data.Success && data.MediaPathURL) {
                //open viewing window
                if (data.PPM && (data.PPMMultiplier>1))
                {
                 $("#PPMMultiplier","#PPMPremiumConfirmationPopup").text(data.PPMMultiplier);
                 $(".button", "#PPMPremiumConfirmationPopup").unbind('click').click(function() {
                    var $this=$(this);
                    if($this.hasClass('yes')) {
                       window.location.href = data.MediaPathURL;
                    }
                   $.fancybox.close();
                   if ($this.hasClass('preview')) {
                       loadPreviewPlayer(productID);

                    }
                    return false;
                 });
                 $('<a href="#PPMPremiumConfirmationPopup" id="PPMPremiumConfirmationPopupLink" />').fancybox().click();
           

                }
                else
                {
                  window.location.href = data.MediaPathURL;
                }
                return false;
            }
            else {
                var errMsgHTML = '';
                var DisplayDiv = $('#ErrorDialog');
                if (DisplayDiv.length==0) {
                    $("<div id='ErrorDialog' style='display:none;'></div>").appendTo("body");
                    DisplayDiv = $('#ErrorDialog');               
                }

                //set inner text of error dialog - TODO: add functionality to display correct message instead of this default
                errMsgHTML += '<h3>Video Play Status</h3><hr/>';
                errMsgHTML += '<p>There was a problem loading your video: <br/></p>';

                //Possible status
                //0 None
                //1 NotAuthenticated
                //2 NotAgeVerified
                //3 CouldNotResolveProduct
                //4 NoTimeLeft
                //5 ServerError
                //6 PremiumNotAvailableForPPM

                if (data.ErrorType == '1') {
                    errMsgHTML += '<p>You must login before playing a video. Click here to <a href="/login.aspx?returnurl=' + document.location.href + '">login</a>. <br/></p>';
                }
                if (data.ErrorType == '2') {
                    errMsgHTML += '<p>You must be 18 or older to view a video. Click here to <a href="/verifyage.aspx?returnurl=' + document.location.href + '">verify your age</a>. <br/></p>';
                }
                if (data.ErrorType == '3') {
                    errMsgHTML += '<p>This video is not available at this time. Please try again or select another video. <br/></p>';
                }
                if (data.ErrorType == '4') {
                    errMsgHTML += '<p>You do not have enough minutes left to play this video. Click here to <a href="/buyminutes.aspx?returnurl=' + document.location.href + '">buy more minutes</a>. <br/></p>';
                }
                if (data.ErrorType == '5') {
                    errMsgHTML += '<p>The video could not be loaded. Please try again or <a href="/t-contactus.aspx?returnurl=' + document.location.href + '">contact customer service</a> if the problem persists. <br/></p>';
                }
                if (data.ErrorType == '6') {
                    errMsgHTML += '<p>This is a premium title and must be rented for viewing. Please close this dialog box and select a rental term to purchase. <br/></p>';
                }
                if (data.ErrorType == '7') {
                    errMsgHTML += '<p>You need to check out in order to be able to watch this video. Click here to <a href="/shoppingcart.aspx"> check out now<br/></p>';
                }

                //display message in fancybox
                DisplayDiv.fancybox({
                    'content': errMsgHTML
                }).click();
            }
        }
    });
}



$(document).ready(function () {

    if (window.joinRefresh != 'undefined' && window.joinRefresh) {
        window.joinRefresh = false;
        location.reload();
    }

    //boxcover display settings
    $('#ProductEnlargedImages').fancybox();
    $('.fancyboxCover').click(function () {
        $('#ProductEnlargedImages').fancybox().click();
        return false;
    });


    $('.fancyboxClose').bind('click', function () {
        $.fancybox.close();
        return false;
    });


    // KMB changed the word navSearchInput to searchbox  //
    // to reference the correct control  Bug 5436        //
    //------ Search box enter button capture //
    $('#searchbox').keypress(function (e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        var searchText = $("#searchbox").val();

        if (searchText != '') {
            if (code == 13) { //"Enter" keycode
                setupLoading({ mode: 'http' });
                window.location.href = '/search/?st=' + $("#searchbox").val();
                return false;
            }
        }
        else {
            $("#searchbox").focus();
        }
    });

    // KMB end                                           //

    //------ Header Login Overlay //
    $('#headerLogin').click(function () {
        $('#headerLoginPopup').fadeIn('normal');
        return false;
    });

    //------ Logins  //
    //disable submit
    $('form.phe-ui-loginform').attr('onsubmit', 'return false;');

    //handle "Enter" keypress in password field 
    $('.phe-ui-loginpassword').keypress(function (e) {
        var form = $(this).parents().filter('.phe-ui-loginform');
        var RedirectURL = $("input[type='hidden'].redirectURL", form).val();
        var PlayProductID = $("input[type='hidden'].PlayProductID", form).val();
        var SubSceneIndex = $("input[type='hidden'].SubSceneIndex", form).val();
        var CommentProductID = $("input[type='hidden'].CommentProductID", form).val();
        var code = (e.keyCode ? e.keyCode : e.which);

        if (code == 13) { //"Enter" keycode

            if ($('#commentsCollapse' + CommentProductID + ' .phe-ui-loginbutton').attr('hidecommentbox')) {
                CommentProductID = 0;
            }

            doLoginLogic(form, RedirectURL, PlayProductID, SubSceneIndex, CommentProductID);
            return false;
        }
    });

    //general login function
    $('.phe-ui-loginbutton', this).bind("click", function () {
        var form = $(this).parents().filter('.phe-ui-loginform');
        var RedirectURL = $("input[type='hidden'].redirectURL", form).val();
        var PlayProductID = $("input[type='hidden'].PlayProductID", form).val();
        var SubSceneIndex = $("input[type='hidden'].SubSceneIndex", form).val();
        var CommentProductID = $("input[type='hidden'].CommentProductID", form).val();

        if ($('#commentsCollapse' + CommentProductID + ' .phe-ui-loginbutton').attr('hidecommentbox')) {
            CommentProductID = 0;
        }

        doLoginLogic(form, RedirectURL, PlayProductID, SubSceneIndex, CommentProductID);
        return false;
    });



    $('#headerLogout').click(function () {
        var $this = $(this);
        if ($this.attr("cartItemCount")) {
            if ($this.attr("cartItemCount") > 0) {
                $('<a href="#LogoutItemsInCartPopup" id="LogoutItemsInCartPopupLink" />').fancybox().click();
                //                $("#LogoutItemsInCartPopup").dialog({
                //                    buttons: { "Check Out Now": function() {
                //                        $(this).dialog("destroy");
                //                         $("#CheckOutNow").click();
                //                   },
                //                    "Save For Next Time and Logout": function() {
                //                        $(this).dialog("destroy");
                //                         $("#LogoutSave").click();
                //                   },
                //                    "Discard Items and Logout": function() {
                //                        $(this).dialog("destroy");
                //                        $("#LogoutDiscard").click();
                //                    }

                //                    },
                //                    modal: true,
                //                    width: "700px"
                //                }).dialog("open");

                return false;
            }
        }
    });
    //----- Cart Tool Tip -----//
    var CartToolTip = $("#CartLink").tooltip({
        effect: 'slide',
        tip: '#MiniCart',
        position: 'bottom center',
        offset: [-1, -120],
        direction: 'down',
        slideFade: 'true',
        slideOffset: 0,
        onBeforeShow: function () {
            //if (!($("#MiniCart").hasClass("populated"))) {
            phe.aeod.doUpdateMiniCart();
            //}
            //if ($("#MiniCart .MiniCartItem").length > 0)
            //return false;
            $('#CartLink').addClass('CartLinkShowTooltip');
        },
        onHide: function () {
            $('#CartLink').removeClass('CartLinkShowTooltip');
        }
    });

    //----- Simulate Post-Back -----//
    $('form.phe-ui-postback').attr('action', document.location.href).attr('method', 'post');

    $(".rating-cancel").bind("click", function () {
        var ProductID = $(this).parent().parent().attr("productID");
        var Rating = 0;
        var data = "{ProductID:" + ProductID + ",Rating:" + Rating + "}";
        $.ajax({
            type: "POST",
            url: "/ws/Ajax/Ratings.asmx/UpdateRating",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: ApplyProductRating(ProductID, Rating)
        });
    });
    //----- Apply User Ratings -----//
    var ProductIDs = new Array();
    $(".phe-ui-starcontainer").each(function (i) {
        ProductIDs[i] = $(this).attr("productID");
    });
    if (ProductIDs.length > 0)
        $.ajax({
            type: "POST",
            url: "/ws/Ajax/Ratings.asmx/GetUserRatings",
            data: "{ProductIDList:'" + ProductIDs.join("-") + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                $.each(data.d, function (i, item) {
                    ApplyProductRating(item.ItemID, item.Rating);
                });
            }
        });

    //----- Grid -----//
    $("td", "div.phe-ui-grid table tbody tr:odd").addClass("alt");

    //----- Spec Star Ratings -----//
    $(".phe-ui-spec-star").rating();
    $(".star-rating-live").bind("click", function () {
        var SpecID = $(this).parent().parent().attr("specID");
        var Rating = $("a", this).text();
        var data = "{SpecID:" + SpecID + ",Rating:" + Rating + "}";
        $.ajax({
            type: "POST",
            url: "/ws/Ajax/Ratings.asmx/UpdateSpecRating",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: ApplySpecRating(SpecID, Rating)
        });
    });
    $(".rating-cancel").bind("click", function () {
        var SpecID = $(this).parent().parent().attr("specID");
        var Rating = 0;
        var data = "{SpecID:" + SpecID + ",Rating:" + Rating + "}";
        $.ajax({
            type: "POST",
            url: "/ws/Ajax/Ratings.asmx/UpdateSpecRating",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: ApplySpecRating(SpecID, Rating)
        });
    });
    //----- Apply User Spec Ratings -----//
    var SpecIDs = new Array();
    $(".phe-ui-spec-starcontainer").each(function (i) {
        SpecIDs[i] = $(this).attr("specID");
    });
    if (SpecIDs.length > 0)
        $.ajax({
            type: "POST",
            url: "/ws/Ajax/Ratings.asmx/GetUserSpecRatings",
            data: "{SpecIDList:'" + SpecIDs.join("-") + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                $.each(data.d, function (i, item) {
                    ApplySpecRating(item.ItemID, item.Rating);
                });
            }
        });

    /*QUEUE TOOLTIPS BELOW*/
    //go to queue button
    $("#GoToQueue").bind("click", function () { window.location = "/videoqueue.aspx"; return false; });

    //add movie to queue (1)
    $('.phe-ui-addMovietoQ1').bind("click", function (e) {
        var ProductID = $(this).attr("productid");
        var data = "{ProductID:" + ProductID + "}";
        $.ajax({
            type: "POST",
            url: "/ws/Ajax/VideoQueue.asmx/AddItemToQueue",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                //HANDLE SUCCESS
                handleMovieSuccess('1', ProductID)
            }
        });
        return false;
    });

    //add movie to queue (2)
    $('.phe-ui-addMovietoQ2').bind("click", function (e) {
        var ProductID = $(this).attr("productid");
        var data = "{ProductID:" + ProductID + "}";
        $.ajax({
            type: "POST",
            url: "/ws/Ajax/VideoQueue.asmx/AddItemToQueue",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                //HANDLE SUCCESS
                handleMovieSuccess('2', ProductID)
            }
        });
        return false;
    });

    //add movie to queue (3)
    $('.phe-ui-addMovietoQ3').bind("click", function (e) {
        var ProductID = $(this).attr("productid");
        var data = "{ProductID:" + ProductID + "}";
        $.ajax({
            type: "POST",
            url: "/ws/Ajax/VideoQueue.asmx/AddItemToQueue",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                //HANDLE SUCCESS
                handleMovieSuccess('3', ProductID)
            }
        });
        return false;
    });

    //add movie to queue (4)
    $('.phe-ui-addMovietoQ1').bind("click", function (e) {
        var ProductID = $(this).attr("productid");
        var data = "{ProductID:" + ProductID + "}";
        $.ajax({
            type: "POST",
            url: "/ws/Ajax/VideoQueue.asmx/AddItemToQueue",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                //HANDLE SUCCESS
                handleMovieSuccess('4', ProductID)
            }
        });
        return false;
    });

    //add movie to queue ('')
    $('.phe-ui-addMovietoQ').bind("click", function (e) {
        var ProductID = $(this).attr("productid");
        var data = "{ProductID:" + ProductID + "}";
        $.ajax({
            type: "POST",
            url: "/ws/Ajax/VideoQueue.asmx/AddItemToQueue",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                //HANDLE SUCCESS
                handleMovieSuccess('', ProductID)
            }
        });
        return false;
    });

    //add Movie Series to queue (1)
    $('.phe-ui-addMovieSeriestoQ1').bind("click", function (e) {
        var ProductID = $(this).attr("productid");
        var data = "{ProductID:" + ProductID + "}";
        $.ajax({
            type: "POST",
            url: "/ws/Ajax/VideoQueue.asmx/AddSeriesToQueue",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                //HANDLE SUCCESS
                handleMovieSuccess('1', ProductID)
            }
        });
        return false;
    });

    //add Movie Series to queue (2)
    $('.phe-ui-addMovieSeriestoQ2').bind("click", function (e) {
        var ProductID = $(this).attr("productid");
        var data = "{ProductID:" + ProductID + "}";
        $.ajax({
            type: "POST",
            url: "/ws/Ajax/VideoQueue.asmx/AddSeriesToQueue",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                //HANDLE SUCCESS
                handleMovieSuccess('2', ProductID)
            }
        });
        return false;
    });

    //add Movie Series to queue (3)
    $('.phe-ui-addMovieSeriestoQ3').bind("click", function (e) {
        var ProductID = $(this).attr("productid");
        var data = "{ProductID:" + ProductID + "}";
        $.ajax({
            type: "POST",
            url: "/ws/Ajax/VideoQueue.asmx/AddSeriesToQueue",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                //HANDLE SUCCESS
                handleMovieSuccess('3', ProductID)
            }
        });
        return false;
    });

    //add Movie Series to queue (4)
    $('.phe-ui-addMovieSeriestoQ4').bind("click", function (e) {
        var ProductID = $(this).attr("productid");
        var data = "{ProductID:" + ProductID + "}";
        $.ajax({
            type: "POST",
            url: "/ws/Ajax/VideoQueue.asmx/AddSeriesToQueue",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                //HANDLE SUCCESS
                handleMovieSuccess('4', ProductID)
            }
        });
        return false;
    });

    //add Movie Series to queue ('')
    $('.phe-ui-addMovieSeriestoQ').bind("click", function (e) {
        var ProductID = $(this).attr("productid");
        var data = "{ProductID:" + ProductID + "}";
        $.ajax({
            type: "POST",
            url: "/ws/Ajax/VideoQueue.asmx/AddSeriesToQueue",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                //HANDLE SUCCESS
                handleMovieSuccess('', ProductID)
            }
        });
        return false;
    });

    //add scene to queue
    $('.phe-ui-addScenetoQ').bind("click", function (e) {
        var ProductID = $(this).attr("productid");
        var data = "{ProductID:" + ProductID + "}";
        $.ajax({
            type: "POST",
            url: "/ws/Ajax/VideoQueue.asmx/AddSceneToQueue",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                //HANDLE SUCCESS
                handleSceneSuccess('', ProductID);
            }
        });
        return false;
    });

    //add scene Series to queue
    $('.phe-ui-addSceneSeriestoQ').bind("click", function (e) {
        var ProductID = $(this).attr("productid");
        var data = "{ProductID:" + ProductID + "}";
        $.ajax({
            type: "POST",
            url: "/ws/Ajax/VideoQueue.asmx/AddSceneSeriesToQueue",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                //HANDLE SUCCESS
                handleSceneSuccess('', ProductID);
            }
        });
        return false;
    });

    //Common functions to handle add to Queue Success
    function handleMovieSuccess(sectionName, ProductID) {
        $('#addMovietoQ' + sectionName + ProductID).hide();
        $('#addMovieSeriestoQ' + sectionName + ProductID).hide();
        $('#tooltipConfirmQ' + sectionName + ProductID).css({ visibility: 'visible' });
        $('#ToolTipContainerQ' + sectionName + ProductID).addClass("tooltipRent");
        $('#addMovieQPlus' + sectionName + ProductID).hide();
        $('#addMovieQCheck' + sectionName + ProductID).css({ visibility: 'visible', float: 'left', clear: 'left' });
    }

    function handleSceneSuccess(sectionName, ProductID) {
        $('#addScenetoQ' + sectionName + ProductID).hide();
        $('#addSceneSeriestoQ' + sectionName + ProductID).hide();
        $('#tooltipConfirmQ' + sectionName + ProductID).css({ visibility: 'visible' });
        $('#ToolTipContainerQ' + sectionName + ProductID).addClass("tooltipRent");
        $('#addSceneQPlus' + sectionName + ProductID).hide();
        $('#addSceneQCheck' + sectionName + ProductID).css({ visibility: 'visible', float: 'left', clear: 'left' });
    }
    /*QUEUE TOOLTIPS ABOVE*/

    setupRentTips();
    setupRatingPlugins();
});


//------ Genres Dropdown //
$(document).ready(function() {
    $('.navItemGenres').mouseover(function() {
        // Make the id overview show
        $('#genresDropdown').fadeIn(0);
    });
    $('#genresDropdown').mouseover(function() {
        // Make the id overview show
        $('#genresDropdown').fadeIn(0);
        //$('#ere').css({'background-color':'yellow'});

    });
    $('.navItemGenres, #genresDropdown').mouseleave(function() {
        // Make the id overview hide
        $('#genresDropdown').fadeOut(0);
    });
});


//Init Boxcover Scroller JS
//------ Initiate Carousel W/ Params Requires jcarousellite.js //
$(document).ready(function() {
    $(function() {
        $(".heroScroller").jCarouselLite({
            visible: 12,
            mouseWheel: false,
            btnNext: ".scrollerNext",
            btnPrev: ".scrollerPrev",
            auto: 7000,
            speed: 1000,
            scroll: 6
        });
    });
});

//------ Initiate Carousel Reflection W/ Params Requires reflections.js //
$(document).ready(function() {
    $(".scrollerReflect").reflect({
        height: .25,
        opacity: .25
    });
});

//------ Initiate Carousel Reflection W/ Params Requires reflections.js //
$(document).ready(function() {
    $(".scrollerReflectSmall").reflect({
        height: .15,
        opacity: .35
    });
});

//------ Initiate Carousel W/ Params Requires jcarousellite.js //
$(document).ready(function() {
    $(function() {
        $(".smallScroller").jCarouselLite({
            visible: 6,
            mouseWheel: false,
            btnNext: ".smallScrollerNext",
            btnPrev: ".smallScrollerPrev",
            auto: 7000,
            speed: 1000,
            scroll: 6
        });
    });
});



// JavaScript Document

$(document).ready(function() {
    // Category Dump
    $(".tooltipDescription").text().substr(0, 100);

    // Index & Header Tooltips
    $(".worksButton").tooltip({ position: "bottom center", effect: "slide", lazy: "false", offset: [7, 0], events: { def: "click,mouseout"} });
    $(".addQueue").tooltip({ position: "bottom center", effect: "slide", lazy: "false", offset: [0, 70], predelay: 100, events: { def: "mouseover,mouseout"} });
    $(".boxcoverTip").tooltip({ position: "center right", effect: "slide", direction: "left", lazy: "false", predelay: 500, offset: [-82, 6], events: { def: "mouseover,mouseout"} });
    $(".boxcoverTipRelated").tooltip({ position: "top right", effect: "slide", direction: "left", lazy: "false", predelay: 500, offset: [188, 6], events: { def: "mouseover,mouseout"} });
    $(".forgotPasswordTip").tooltip({ position: "bottom center", effect: "slide", lazy: "true", offset: [5, 0], events: { def: "click,mouseout"} });

});



//------ Carousel - jcarousellite.js //
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(6($){$.1g.1w=6(o){o=$.1f({r:n,x:n,N:n,17:q,J:n,L:1a,16:n,y:q,u:12,H:3,B:0,k:1,K:n,I:n},o||{});8 G.R(6(){p b=q,A=o.y?"15":"w",P=o.y?"t":"s";p c=$(G),9=$("9",c),E=$("10",9),W=E.Y(),v=o.H;7(o.u){9.1h(E.D(W-v-1+1).V()).1d(E.D(0,v).V());o.B+=v}p f=$("10",9),l=f.Y(),4=o.B;c.5("1c","H");f.5({U:"T",1b:o.y?"S":"w"});9.5({19:"0",18:"0",Q:"13","1v-1s-1r":"S","z-14":"1"});c.5({U:"T",Q:"13","z-14":"2",w:"1q"});p g=o.y?t(f):s(f);p h=g*l;p j=g*v;f.5({s:f.s(),t:f.t()});9.5(P,h+"C").5(A,-(4*g));c.5(P,j+"C");7(o.r)$(o.r).O(6(){8 m(4-o.k)});7(o.x)$(o.x).O(6(){8 m(4+o.k)});7(o.N)$.R(o.N,6(i,a){$(a).O(6(){8 m(o.u?o.H+i:i)})});7(o.17&&c.11)c.11(6(e,d){8 d>0?m(4-o.k):m(4+o.k)});7(o.J)1p(6(){m(4+o.k)},o.J+o.L);6 M(){8 f.D(4).D(0,v)};6 m(a){7(!b){7(o.K)o.K.Z(G,M());7(o.u){7(a<=o.B-v-1){9.5(A,-((l-(v*2))*g)+"C");4=a==o.B-v-1?l-(v*2)-1:l-(v*2)-o.k}F 7(a>=l-v+1){9.5(A,-((v)*g)+"C");4=a==l-v+1?v+1:v+o.k}F 4=a}F{7(a<0||a>l-v)8;F 4=a}b=12;9.1o(A=="w"?{w:-(4*g)}:{15:-(4*g)},o.L,o.16,6(){7(o.I)o.I.Z(G,M());b=q});7(!o.u){$(o.r+","+o.x).1n("X");$((4-o.k<0&&o.r)||(4+o.k>l-v&&o.x)||[]).1m("X")}}8 q}})};6 5(a,b){8 1l($.5(a[0],b))||0};6 s(a){8 a[0].1k+5(a,\'1j\')+5(a,\'1i\')};6 t(a){8 a[0].1t+5(a,\'1u\')+5(a,\'1e\')}})(1x);',62,96,'||||curr|css|function|if|return|ul|||||||||||scroll|itemLength|go|null||var|false|btnPrev|width|height|circular||left|btnNext|vertical||animCss|start|px|slice|tLi|else|this|visible|afterEnd|auto|beforeStart|speed|vis|btnGo|click|sizeCss|position|each|none|hidden|overflow|clone|tl|disabled|size|call|li|mousewheel|true|relative|index|top|easing|mouseWheel|padding|margin|200|float|visibility|append|marginBottom|extend|fn|prepend|marginRight|marginLeft|offsetWidth|parseInt|addClass|removeClass|animate|setInterval|0px|type|style|offsetHeight|marginTop|list|jCarouselLite|jQuery'.split('|'),0,{}))
//------ Star Rating - starrating.js - http://www.fyneworks.com/jquery/star-rating/ //
; if (window.jQuery) (function($) { if ($.browser.msie) try { document.execCommand("BackgroundImageCache", false, true) } catch (e) { }; $.fn.rating = function(options) { if (this.length == 0) return this; if (typeof arguments[0] == 'string') { if (this.length > 1) { var args = arguments; return this.each(function() { $.fn.rating.apply($(this), args) }) }; $.fn.rating[arguments[0]].apply(this, $.makeArray(arguments).slice(1) || []); return this }; var options = $.extend({}, $.fn.rating.options, options || {}); $.fn.rating.calls++; this.not('.star-rating-applied').addClass('star-rating-applied').each(function() { var control, input = $(this); var eid = (this.name || 'unnamed-rating').replace(/\[|\]/g, '_').replace(/^\_+|\_+$/g, ''); var context = $(this.form || document.body); var raters = context.data('rating'); if (!raters || raters.call != $.fn.rating.calls) raters = { count: 0, call: $.fn.rating.calls }; var rater = raters[eid]; if (rater) control = rater.data('rating'); if (rater && control) control.count++; else { control = $.extend({}, options || {}, ($.metadata ? input.metadata() : ($.meta ? input.data() : null)) || {}, { count: 0, stars: [], inputs: [] }); control.serial = raters.count++; rater = $('<span class="star-rating-control"/>'); input.before(rater); rater.addClass('rating-to-be-drawn'); if (input.attr('disabled')) control.readOnly = true; rater.append(control.cancel = $('<div class="rating-cancel"><a class="movieDelete" title="' + control.cancel + '">' + control.cancelValue + '</a></div>').mouseover(function() { $(this).rating('drain'); $(this).addClass('star-rating-hover') }).mouseout(function() { $(this).rating('draw'); $(this).removeClass('star-rating-hover') }).click(function() { $(this).rating('select'); $(this).parents('.starCollapse').slideUp('slow') }).data('rating', control)) }; var star = $('<div class="star-rating rater-' + control.serial + '"><a title="' + (this.title || this.value) + '">' + this.value + '</a></div>'); rater.append(star); if (this.id) star.attr('id', this.id); if (this.className) star.addClass(this.className); if (control.half) control.split = 2; if (typeof control.split == 'number' && control.split > 0) { var stw = ($.fn.width ? star.width() : 0) || control.starWidth; var spi = (control.count % control.split), spw = Math.floor(stw / control.split); star.width(spw).find('a').css({ 'margin-left': '-' + (spi * spw) + 'px' }) }; if (control.readOnly) star.addClass('star-rating-readonly'); else star.addClass('star-rating-live').mouseover(function() { $(this).rating('fill'); $(this).rating('focus') }).mouseout(function() { $(this).rating('draw'); $(this).rating('blur') }).click(function() { $(this).rating('select') }); if (this.checked) control.current = star; input.hide(); input.change(function() { $(this).rating('select') }); star.data('rating.input', input.data('rating.star', star)); control.stars[control.stars.length] = star[0]; control.inputs[control.inputs.length] = input[0]; control.rater = raters[eid] = rater; control.context = context; input.data('rating', control); rater.data('rating', control); star.data('rating', control); context.data('rating', raters) }); $('.rating-to-be-drawn').rating('draw').removeClass('rating-to-be-drawn'); return this }; $.extend($.fn.rating, { calls: 0, focus: function() { var control = this.data('rating'); if (!control) return this; if (!control.focus) return this; var input = $(this).data('rating.input') || $(this.tagName == 'INPUT' ? this : null); if (control.focus) control.focus.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]) }, blur: function() { var control = this.data('rating'); if (!control) return this; if (!control.blur) return this; var input = $(this).data('rating.input') || $(this.tagName == 'INPUT' ? this : null); if (control.blur) control.blur.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]) }, fill: function() { var control = this.data('rating'); if (!control) return this; if (control.readOnly) return; this.rating('drain'); this.prevAll().andSelf().filter('.rater-' + control.serial).addClass('star-rating-hover') }, drain: function() { var control = this.data('rating'); if (!control) return this; if (control.readOnly) return; control.rater.children().filter('.rater-' + control.serial).removeClass('star-rating-on').removeClass('star-rating-hover') }, draw: function() { var control = this.data('rating'); if (!control) return this; this.rating('drain'); if (control.current) { control.current.data('rating.input').attr('checked', 'checked'); control.current.prevAll().andSelf().filter('.rater-' + control.serial).addClass('star-rating-on') } else $(control.inputs).removeAttr('checked'); control.cancel[control.readOnly || control.required ? 'hide' : 'show'](); this.siblings()[control.readOnly ? 'addClass' : 'removeClass']('star-rating-readonly') }, select: function(value) { var control = this.data('rating'); if (!control) return this; if (control.readOnly) return; control.current = null; if (typeof value != 'undefined') { if (typeof value == 'number') return $(control.stars[value]).rating('select'); if (typeof value == 'string') $.each(control.stars, function() { if ($(this).data('rating.input').val() == value) $(this).rating('select') }) } else control.current = this[0].tagName == 'INPUT' ? this.data('rating.star') : (this.is('.rater-' + control.serial) ? this : null); this.data('rating', control); this.rating('draw'); var input = $(control.current ? control.current.data('rating.input') : null); if (control.callback) control.callback.apply(input[0], [input.val(), $('a', control.current)[0]]) }, readOnly: function(toggle, disable) { var control = this.data('rating'); if (!control) return this; control.readOnly = toggle || toggle == undefined ? true : false; if (disable) $(control.inputs).attr("disabled", "disabled"); else $(control.inputs).removeAttr("disabled"); this.data('rating', control); this.rating('draw') }, disable: function() { this.rating('readOnly', true, true) }, enable: function() { this.rating('readOnly', false, false) } }); $.fn.rating.options = { cancel: 'Remove Rating', cancelValue: '', split: 0, starWidth: 16 }; $(function() { $('input[type=radio].star').rating() }) })(jQuery);

/*
* jquery.tools 1.1.2 - The missing UI library for the Web
* 
* [tools.tooltip-1.1.2, tools.tooltip.slide-1.0.0]
* 
* Copyright (c) 2009 Tero Piirainen
* http://flowplayer.org/tools/
*
* Dual licensed under MIT and GPL 2+ licenses
* http://www.opensource.org/licenses
* 
* -----
* 
* File generated: Wed Oct 07 19:01:26 GMT+00:00 2009
*/
(function(c) { var d = []; c.tools = c.tools || {}; c.tools.tooltip = { version: "1.1.2", conf: { effect: "toggle", fadeOutSpeed: "fast", tip: null, predelay: 0, delay: 30, opacity: 1, lazy: undefined, position: ["top", "center"], offset: [0, 0], cancelDefault: true, relative: false, oneInstance: true, events: { def: "mouseover,mouseout", input: "focus,blur", widget: "focus mouseover,blur mouseout", tooltip: "mouseover,mouseout" }, api: false }, addEffect: function(e, g, f) { b[e] = [g, f] } }; var b = { toggle: [function(e) { var f = this.getConf(), g = this.getTip(), h = f.opacity; if (h < 1) { g.css({ opacity: h }) } g.show(); e.call() }, function(e) { this.getTip().hide(); e.call() } ], fade: [function(e) { this.getTip().fadeIn(this.getConf().fadeInSpeed, e) }, function(e) { this.getTip().fadeOut(this.getConf().fadeOutSpeed, e) } ] }; function a(f, g) { var p = this, k = c(this); f.data("tooltip", p); var l = f.next(); if (g.tip) { l = c(g.tip); if (l.length > 1) { l = f.nextAll(g.tip).eq(0); if (!l.length) { l = f.parent().nextAll(g.tip).eq(0) } } } function o(u) { var t = g.relative ? f.position().top : f.offset().top, s = g.relative ? f.position().left : f.offset().left, v = g.position[0]; t -= l.outerHeight() - g.offset[0]; s += f.outerWidth() + g.offset[1]; var q = l.outerHeight() + f.outerHeight(); if (v == "center") { t += q / 2 } if (v == "bottom") { t += q } v = g.position[1]; var r = l.outerWidth() + f.outerWidth(); if (v == "center") { s -= r / 2 } if (v == "left") { s -= r } return { top: t, left: s} } var i = f.is(":input"), e = i && f.is(":checkbox, :radio, select, :button"), h = f.attr("type"), n = g.events[h] || g.events[i ? (e ? "widget" : "input") : "def"]; n = n.split(/,\s*/); if (n.length != 2) { throw "Tooltip: bad events configuration for " + h } f.bind(n[0], function(r) { if (g.oneInstance) { c.each(d, function() { this.hide() }) } var q = l.data("trigger"); if (q && q[0] != this) { l.hide().stop(true, true) } r.target = this; p.show(r); n = g.events.tooltip.split(/,\s*/); l.bind(n[0], function() { p.show(r) }); if (n[1]) { l.bind(n[1], function() { p.hide(r) }) } }); f.bind(n[1], function(q) { p.hide(q) }); if (!c.browser.msie && !i && !g.predelay) { f.mousemove(function() { if (!p.isShown()) { f.triggerHandler("mouseover") } }) } if (g.opacity < 1) { l.css("opacity", g.opacity) } var m = 0, j = f.attr("title"); if (j && g.cancelDefault) { f.removeAttr("title"); f.data("title", j) } c.extend(p, { show: function(r) { if (r) { f = c(r.target) } clearTimeout(l.data("timer")); if (l.is(":animated") || l.is(":visible")) { return p } function q() { l.data("trigger", f); var t = o(r); if (g.tip && j) { l.html(f.data("title")) } r = r || c.Event(); r.type = "onBeforeShow"; k.trigger(r, [t]); if (r.isDefaultPrevented()) { return p } t = o(r); l.css({ position: "absolute", top: t.top, left: t.left }); var s = b[g.effect]; if (!s) { throw 'Nonexistent effect "' + g.effect + '"' } s[0].call(p, function() { r.type = "onShow"; k.trigger(r) }) } if (g.predelay) { clearTimeout(m); m = setTimeout(q, g.predelay) } else { q() } return p }, hide: function(r) { clearTimeout(l.data("timer")); clearTimeout(m); if (!l.is(":visible")) { return } function q() { r = r || c.Event(); r.type = "onBeforeHide"; k.trigger(r); if (r.isDefaultPrevented()) { return } b[g.effect][1].call(p, function() { r.type = "onHide"; k.trigger(r) }) } if (g.delay && r) { l.data("timer", setTimeout(q, g.delay)) } else { q() } return p }, isShown: function() { return l.is(":visible, :animated") }, getConf: function() { return g }, getTip: function() { return l }, getTrigger: function() { return f }, bind: function(q, r) { k.bind(q, r); return p }, onHide: function(q) { return this.bind("onHide", q) }, onBeforeShow: function(q) { return this.bind("onBeforeShow", q) }, onShow: function(q) { return this.bind("onShow", q) }, onBeforeHide: function(q) { return this.bind("onBeforeHide", q) }, unbind: function(q) { k.unbind(q); return p } }); c.each(g, function(q, r) { if (c.isFunction(r)) { p.bind(q, r) } }) } c.prototype.tooltip = function(e) { var f = this.eq(typeof e == "number" ? e : 0).data("tooltip"); if (f) { return f } var g = c.extend(true, {}, c.tools.tooltip.conf); if (c.isFunction(e)) { e = { onBeforeShow: e} } else { if (typeof e == "string") { e = { tip: e} } } e = c.extend(true, g, e); if (typeof e.position == "string") { e.position = e.position.split(/,?\s/) } { this.each(function() { f = new a(c(this), e); d.push(f) }) } return e.api ? f : this } })(jQuery);
(function(b) { var a = b.tools.tooltip; a.effects = a.effects || {}; a.effects.slide = { version: "1.0.0" }; b.extend(a.conf, { direction: "up", bounce: false, slideOffset: 10, slideInSpeed: 200, slideOutSpeed: 200, slideFade: !b.browser.msie }); var c = { up: ["-", "top"], down: ["+", "top"], left: ["-", "left"], right: ["+", "left"] }; b.tools.tooltip.addEffect("slide", function(d) { var f = this.getConf(), g = this.getTip(), h = f.slideFade ? { opacity: f.opacity} : {}, e = c[f.direction] || c.up; h[e[1]] = e[0] + "=" + f.slideOffset; if (f.slideFade) { g.css({ opacity: 0 }) } g.show().animate(h, f.slideInSpeed, d) }, function(e) { var g = this.getConf(), i = g.slideOffset, h = g.slideFade ? { opacity: 0} : {}, f = c[g.direction] || c.up; var d = "" + f[0]; if (g.bounce) { d = d == "+" ? "-" : "+" } h[f[1]] = d + "=" + i; this.getTip().animate(h, g.slideOutSpeed, function() { b(this).hide(); e.call() }) }) })(jQuery);



/*
reflection.js for jQuery v1.02
(c) 2006-2008 Christophe Beyls <http://www.digitalia.be>
MIT-style license.
*/
(function(a) { a.fn.extend({ reflect: function(b) { b = a.extend({ height: 0.33, opacity: 0.5 }, b); return this.unreflect().each(function() { var c = this; if (/^img$/i.test(c.tagName)) { function d() { var j, g = Math.floor(c.height * b.height), k, f, i; if (a.browser.msie) { j = a("<img />").attr("src", c.src).css({ width: c.width, height: c.height, marginBottom: -c.height + g, filter: "flipv progid:DXImageTransform.Microsoft.Alpha(opacity=" + (b.opacity * 100) + ", style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy=" + (b.height * 100) + ")" })[0] } else { j = a("<canvas />")[0]; if (!j.getContext) { return } f = j.getContext("2d"); try { a(j).attr({ width: c.width, height: g }); f.save(); f.translate(0, c.height - 1); f.scale(1, -1); f.drawImage(c, 0, 0, c.width, c.height); f.restore(); f.globalCompositeOperation = "destination-out"; i = f.createLinearGradient(0, 0, 0, g); i.addColorStop(0, "rgba(255, 255, 255, " + (1 - b.opacity) + ")"); i.addColorStop(1, "rgba(255, 255, 255, 1.0)"); f.fillStyle = i; f.rect(0, 0, c.width, g); f.fill() } catch (h) { return } } a(j).css({ display: "block", border: 0 }); k = a(/^a$/i.test(c.parentNode.tagName) ? "<span />" : "<div />").insertAfter(c).append([c, j])[0]; k.className = c.className; a.data(c, "reflected", k.style.cssText = c.style.cssText); a(k).css({ width: c.width, height: c.height + g, overflow: "hidden" }); c.style.cssText = "display: block; border: 0px"; c.className = "reflected" } if (c.complete) { d() } else { a(c).load(d) } } }) }, unreflect: function() { return this.unbind("load").each(function() { var c = this, b = a.data(this, "reflected"), d; if (b !== undefined) { d = c.parentNode; c.className = d.className; c.style.cssText = b; a.removeData(c, "reflected"); d.parentNode.replaceChild(c, d) } }) } }) })(jQuery);

// AUTOLOAD CODE BLOCK (MAY BE CHANGED OR REMOVED)
jQuery(function($) {
    $("img.reflect").reflect({/* Put custom options here */
});
});


// Delay Plugin for jQuery
// - http://www.evanbot.com
// - © 2008 Evan Byrne

jQuery.fn.delay = function(time, func) {
    this.each(function() {
        setTimeout(func, time);
    });

    return this;
};

/** 
* Cookie plugin 
* 
* Copyright (c) 2006 Klaus Hartl (stilbuero.de) 
* Dual licensed under the MIT and GPL licenses: 
* http://www.opensource.org/licenses/mit-license.php 
* http://www.gnu.org/licenses/gpl.html 
* 
*/
jQuery.cookie = function(name, value, options) { if (typeof value != 'undefined') { options = options || {}; if (value === null) { value = ''; options = $.extend({}, options); options.expires = -1; } var expires = ''; if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { var date; if (typeof options.expires == 'number') { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); } else { date = options.expires; } expires = '; expires=' + date.toUTCString(); } var path = options.path ? '; path=' + (options.path) : ''; var domain = options.domain ? '; domain=' + (options.domain) : ''; var secure = options.secure ? '; secure' : ''; document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); } else { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } };

function QueryStringParameter(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];
}

// post-fancybox load functions.
$(function () {
    phe.aeod.user.state(function (data) {
        if (data.d.Authenticated && data.d.ItemsInCartReminder) {
            $('<a href="#LoginItemsInCartPopup" id="LoginItemsInCartPopupLink" />').fancybox().click();
        }
        setupLoading();
    });
    
});


// reusable ajax pagination control setup
function setupPager(data, pager) {

    // make sure we have reason to show the pager
    if (data.PageCount == 1) {
        pager.hide();
        return;
    }

    // setup the previous button
    $('.pagerPrevious', pager).unbind('click');
    if (data.PageNumber == 1) {
        $('.pagerPrevious', pager).addClass('disabled');
        $('.pagerPrevious span', pager).removeClass('paginationActiveSpan');
    }
    else {
        $('.pagerPrevious', pager).removeClass('disabled');
        $('.pagerPrevious span', pager).addClass('paginationActiveSpan');
        $('.pagerPrevious', pager).click(function () { loadViewingHistory(data.PageNumber - 1); });
    }

    // setup next button
    $('.pagerNext', pager).unbind('click');
    if (data.PageNumber == data.PageCount) {
        $('.pagerNext', pager).addClass('disabled');
        $('.pagerNext span', pager).removeClass('paginationActiveSpan');
    }
    else {
        $('.pagerNext', pager).removeClass('disabled');
        $('.pagerNext span', pager).addClass('paginationActiveSpan');
        $('.pagerNext', pager).click(function () { loadViewingHistory(data.PageNumber + 1); });
    }

    // setup jump to page options
    $('.pagerPages option', pager).remove();
    for (var i = 1; i <= data.PageCount; i++) {
        if (i != data.PageNumber) {
            $('.pagerPages', pager).append('<option value="' + i + '">' + i + '</option>');
        }
        else {
            $('.pagerPages', pager).append('<option value="0" selected="selected">' + i + '</option>');
        }
    }
    $('.pagerPages', pager).unbind('change');
    $('.pagerPages', pager).change(function () { loadViewingHistory($('.pagerPages', pager).val()); });
}

//---- Star Ratings ----//
function ApplyProductRating(ProductID, Rating) {
    var stargroup = $(".phe-ui-starcontainer[productID=" + ProductID + "]");
    $(stargroup).each(function () {

        var stars = $(".star-rating", this);
        $(stars).removeClass("star-rating-selected");

        for (i = 0; i < Rating; i++) {
            $(stars[i]).addClass("star-rating-selected");
        }
    });
}

function setupRentTips() {
    $(".rentTip").each(function (index) {
        setupRentTip(this)
    });
}

function setupRentTip(element) {
    var $this = $(element);
    var productID = $this.attr("productID");
    var uniqueID = $this.attr("uniqueid"); // extension when more than one of a product exists
    $this.tooltip({ position: "bottom center", effect: "slide", lazy: "true", offset: [5, 0], delay: 10000, events: { def: "click,mouseout" },
        onBeforeShow: function () {
            //tooltipRent[productID=" + productID + "]").empty().append("<div>this is a test</div>");
            var tip = this.getTip();
            $.ajax({
                type: "POST",
                url: "/ws/Ajax/ShoppingCart.asmx/GetRentTip",
                data: "{ProductID:" + productID + "}",
                contentType: "application/json; charset=utf-8",
                async: true,
                dataType: "json",
                success: function (msg) {
                    var data = msg.d;
                    if (data.Success) {
                        tip.html(data.Content);
                        // need to wire it here
                        wireRentTip(tip, productID, uniqueID);
                    }
                }
            }); //ajax
        } //onBeforeShow
    }); //tooltip
}

function wireRentTip(element, productID, uniqueID) {
    // handle the unique identifer
    if (uniqueID == undefined) { uniqueID = ""; }

    if (!element)
        element = $(document);
    $(".tooltipConfirm", element).hide();
    $(".tooltipMessage", element).each(function () {
        $(".tooltipSubmit", element).hide();
        $(".GoToWatch", element).click(function () {
            //play movie
            $(".tooltip").fadeOut("fast");
            loadPlayer(ProductID);

            return false;
        });
        $(".GoToRent", element).bind("click", function () {
            $(".tooltipMessage", element).hide();
            $(".tooltipSubmit", element).show();

        });

    });
    $(".GoToCart", element).bind("click", function () { window.location = "/shoppingcart.aspx"; return false; });
    $(".CloseToolTip", element).bind("click", function () { $(".tooltip").fadeOut("fast"); return false; });

    $('.phe-ui-rent', element).bind("click", function (e) {
        var VariantID = $("input[name='" + productID + "VariantID']:checked").val();
        if (VariantID) {
            var data = "{ProductID:" + productID + ",VariantID:" + VariantID + ",Quantity:1}";
            var url = "/ws/Ajax/ShoppingCart.asmx/AddItem";
            if ($(this).attr("rentalextension") != undefined) {
                url = "/ws/Ajax/ShoppingCart.asmx/AddRentalExtensionItem";
            }
            $.ajax({
                type: "POST",
                url: url,
                data: data,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    $(".tooltipSubmit", element).hide();
                    $(".tooltipConfirm", element).show();

                    //doUpdateMiniCart();
                    $('#MiniCart').removeClass('populated');

                }
            });
        }
        return false;
    });
}

//----Spec Star Ratings ----//
function ApplySpecRating(SpecID, Rating) {
    var stargroup = $(".phe-ui-spec-starcontainer[specID=" + SpecID + "]");
    $(stargroup).each(function () {

        var stars = $(".star-rating", this);
        $(stars).removeClass("star-rating-selected");

        for (i = 0; i < Rating; i++) {
            $(stars[i]).addClass("star-rating-selected");
        }
    });

}

function renderStarsRating(productId, averageRating, sectionName) {

    var result = '';

    result += '<div class="phe-ui-starcontainer" productID="' + productId + '">';

    for (var i = 1; i <= 5; i++) {
        result += '<input name="StarRating' + sectionName + productId + '" type="radio" ';
        result += 'title="' + i + ' Star" value="' + i + '" class="phe-ui-star" ';
        result += '';

        if (i == averageRating) {
            result += ' checked="checked"';
        }

        result += ' />';
    }

    result += '</div>';
    return result;
}

function setupRatingPlugins() {
    $(".phe-ui-star").rating();
    $(".star-rating-live").bind("click", function () {
        var ProductID = $(this).parent().parent().attr("productID");
        var Rating = $("a", this).text();
        var data = "{ProductID:" + ProductID + ",Rating:" + Rating + "}";
        $.ajax({
            type: "POST",
            url: "/ws/Ajax/Ratings.asmx/UpdateRating",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: ApplyProductRating(ProductID, Rating)
        });
    });
}

function setupLoading(opts) {
    if (!opts)
       opts = {}; 
    if ($.loading) {
        if (!opts.img) {
            opts.img = window.location.protocol + "//" + window.location.hostname + '/App_Themes/AdamEveVOD/images/loading2.gif';
        }

        var $target = $;
        if (opts.selector) {
            $target = $(opts.selector);
        }

        if (!opts.mode)
           opts.mode = 'ajax';
       if (opts.mode == 'ajax') {
           $(window).unbind("ajaxStop").bind("ajaxStop", function (event, request, options) {
               $target.loading(false);
           });

           $(window).unbind("ajaxStart").bind("ajaxStart", function (event, request, options) {
               $target.loading(true, {
                   img: opts.img,
                   align: 'center'
               });

           });

       }
       else {
           $target.loading(true, {
               img: opts.img,
               align: 'center'
           });

       }
    }

}

var rootUrl = location.href.substring(0, location.href.lastIndexOf('/'));

$(document).ready(function () {

    $('#contactMethod').bind('change', function () {
        if ($(this).val() == 'Phone') {
            $('#phoneNumber').removeClass('ignore');
            $('#phoneRequired').show();
            $('#phoneNotRequired').hide();
        } else {
            $('#phoneNumber').removeClass('error');
            $('#phoneRequired').hide();
            $('#phoneNotRequired').show();
            if (!$('#phoneNumber').hasClass('ignore')) {
                $('#phoneNumber').addClass('ignore');
            }
        }
    });

    var checkExistsContactUsForm = $('#ContactUsForm').length > 0;
    
    if (checkExistsContactUsForm) {
        // validation
        $("#ContactUsForm").validate({
            rules: {
                firstName: "required",
                lastName: "required",
                emailAddress: {
                    required: true,
                    email: true
                },
                requestType: "required",
                phoneNumber: "required",
                comments: "required"
            },
            messages: {
                firstName: "Please enter your First Name.",
                lastName: "Please enter your Last Name.",
                emailAddress: {
                    required: "Please enter your e-mail address.",
                    email: "Please enter a valid e-mail address."
                },
                requestType: "Please let us know how we can help you.",
                phoneNumber: "Please enter your Phone Number.",
                comments: "Please enter your Comments so we can better assist you."
            },
            errorLabelContainer: "#messageBox",
            wrapper: "li",
            submitHandler: function () { sendForm(); return false; },
            onfocusout: false,
            ignore: '.ignore'
        });

        // get the customer information, if any, to initialize the form with 
        $.ajax({
            type: "POST",
            url: rootUrl + "/ws/Ajax/Authentication.asmx/GetBasicUserInfo",
            contentType: "application/json; charset=utf-8",
            data: "{_val:'spoof'}",
            dataType: "json",
            success: function (data) {
                $("#firstName").val(data.d.FirstName);
                $("#lastName").val(data.d.LastName);
                $("#emailAddress").val(data.d.EmailAddress);
                $("#phoneNumber").val(data.d.PhoneNumber);
            }
        });

        $("#SubmitComment").click(function (event) {
            $("#ContactUsForm").submit();
            return false;
        });
    }

});

function sendForm() {
    var paramArray = buildParameterArray();
    var webService = rootUrl + "/ws/Ajax/Mailer.asmx/SubmitForm";
    var data = JSON.stringify({ params: paramArray, pageName: "ContactUs" });

    $.ajax({
        type: "POST",
        url: webService,
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function() { showThankYou(); }
    });
}

function showThankYou() {
    $("#thankYouFirstName").text($("#firstName").val());
    $("#thankYouLastName").text($("#lastName").val());
    $("#thankYouEmailAddress").text($("#emailAddress").val());
    $("#thankYouPhoneNumber").text($("#phoneNumber").val());
    $("#thankYouRequestType").text($("#requestType").val());
    $("#thankYouComments").text($("#comments").val());
    $("#thankYouContactMethod").text($("#contactMethod").val());
    $("#thankYouContactTime").text($("#contactTime").val());

    $("#thankYou").css("display", "block");
    $("#contactForm").css("display", "none");
}

function buildParameterArray() {
    var params = Array();
    
    var pFirstName = new Object();
    pFirstName.Name = "firstName";
    pFirstName.Type = "string";
    pFirstName.Value = $("#firstName").val();
    pFirstName.Required = true;
    params.push(pFirstName);

    var pLastName = new Object();
    pLastName.Name = "lastName";
    pLastName.Type = "string";
    pLastName.Value = $("#lastName").val();
    pLastName.Required = true;
    params.push(pLastName);

    var pEmail = new Object();
    pEmail.Name = "emailAddress";
    pEmail.Type = "email";
    pEmail.Value = $("#emailAddress").val();
    pEmail.Required = true;
    params.push(pEmail);

    var pPhone = new Object();
    pPhone.Name = "phoneNumber";
    pPhone.Type = "phonenumber";
    pPhone.Value = $("#phoneNumber").val();
    pPhone.Required = false;
    params.push(pPhone);

    var pRequestType = new Object();
    pRequestType.Name = "requestType";
    pRequestType.Type = "string";
    pRequestType.Value = $("#requestType").val();
    pRequestType.Required = true;
    params.push(pRequestType);

    var pComments = new Object();
    pComments.Name = "comments";
    pComments.Type = "string";
    pComments.Value = $("#comments").val();
    pComments.Required = false;
    params.push(pComments);

    var pContactMethod = new Object();
    pContactMethod.Name = "contactMethod";
    pContactMethod.Type = "string";
    pContactMethod.Value = $("#contactMethod").val();
    pContactMethod.Required = false;
    params.push(pContactMethod);

    var pContactTime = new Object();
    pContactTime.Name = "contactTime";
    pContactTime.Type = "string";
    pContactTime.Value = $("#contactTime").val();
    pContactTime.Required = false;
    params.push(pContactTime);
    
    return params;
}



$(document).ready(function () {
    var ContactAdURL = '/handlers/legacyadvertisements.ashx?adType=VOD_ContactUs&catID=0';
    $('.ContactUsAd').load(ContactAdURL);
});

