// Constants
FEATURE_DOUBLECHECK_ONPURCHASE = false;
DEFAULT_DATE_FORMAT = "dd mmm yyyy"

// Global Variables
userIsAuthenticated = false;
isSeasonAsset = false;
var chRadioLanguage;
var chRadioLanguageValue;
AVS_WATCHMOVIE = 1
AVS_PURCHASEMOVIE = 2
var isChangeLanguageCalled;

//***************************************************
//*************CHANGES BY RAJIV**************************************

var EndIndex = 1;
var StartIndex = 0;
var ToshIndex;
var IndexOfEqual;
var Toshtemp = ' ';
var Toshvalue;
var ToshURLvalue = '';
var ToshUSERID = '';
var keyArray;
var chContentID;
var chOfferID;
var chPurchaseID;
var chAction = 'updatelanguage';
var chOfferType;
var iFlag = false;
var chNewofferid;
var chEpisode;
var mobileLocation;

/* Variable added by sumit on 16/09/2011 for checking HD */
var isHD = false;

/* Variable added by sumit on 19/01/2012 for checking mobile offer */
var isMobileOffer = false;
var mo_vaid = '';

//RN-Changes on 24th july -Satur

function DisableLangugeChange() {


}
//RN -Changes on 20th July 
function getParamCL(key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return default_;
    else
        return qs[1];
}

function regCompleteBrowse()
{
window.location.href = "/Generic.aspx?type=Browsing";
return false;
}
function regCompleteAddCredit()
{
window.location.href = "/Generic.aspx?type=Myinfo&tab=2";
return false;
}
//SG - for validating email
function CheckEmail(email) {
    var emailregex = /^\w+([-+.\']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
    //var emailregex =  /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; // very simple but safe
        
        var regex = email.match(emailregex);

        if (regex == null) return false;
        if (regex[0] != email) return false;

        return true;
    }

function GetQueryParameters() {

    //debugger;
    var UserIDIndex = 1;
    var strQueryParameter = window.location.search;
    var spQrStr = strQueryParameter.substring(EndIndex);
    var arrQrStr = new Array();
    var arr = spQrStr.split('&');

    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    if (arr.length > 4) {
        for (var count = 1; count < arr.length; count++) {
            Toshtemp = unescape(arr[count].toString());
            IndexOfEqual = Toshtemp.indexOf('=');
            keyArray = Toshtemp.substring(StartIndex, IndexOfEqual);
            switch (keyArray) {
                case 'Action':
                    Toshvalue = Toshtemp.substring(IndexOfEqual + EndIndex);

                    if (Toshvalue == "ChangeLanguage") {

                        iFlag = true;
                        var movieLangArray = new Array();
                        var LangNameArray = new Array("IT", "DE", "EN", "FR");

                        $(".floatClear", document).css('visibility', 'hidden');

                        //*************changes on 15th june
                        $("#btnPayMovie").css("visibility", "hidden");


                        //SN on 6th July to make dvvisible
                        $("#dvChangeLanguage").css("display", "block");
                        $("#dvChangeLanguage").css("visibility", "visible");

                        $("#dvCLAccount").css("display", "none");

                        //***********************
                        $("#btnChangeLanguage").css("visibility", "visible");
                        $("#detbox_pay_method").css("visibility", "hidden");

                        //****************************************************************                                

                        //$("div.detbox_price_box_buy_price").html("<span>MovieLanguageEN</span>")
                        // TO CHECK THE LANGUAGES OF MOVIES FROM DIV  BELOW MAY RETURN COLLECTION OF LANGUAGES

                        //movieLangArray = $(".detbox_price_box_buy_price").html();
                        var tempMvType = $("#dvMovieLangType").html();
                        movieLangArray = $(".detbox_price_box_buy_price");
                        var ictr = 0;
                        movieLangArray.each(function () {
                            var tempDiv = this; var tempLang = ''; $(LangNameArray).each(function () {
                                tempLang = this; if (tempDiv.innerHTML.indexOf(tempLang) != -1) {
                                    var id = '';
                                    //alert(tempDiv.innerHTML.toLowerCase());
                                    //if (tempDiv.innerHTML.toLowerCase().indexOf("buy") > -1)
                                    if (tempDiv.id.toLowerCase().indexOf("buy") > -1)
                                        id = "spnCLbuy";
                                    //if (tempDiv.innerHTML.toLowerCase().indexOf("rent") > -1)
                                    if (tempDiv.id.toLowerCase().indexOf("rent") > -1)
                                        id = "spnCLrent";
                                    $(tempDiv).empty();
                                    //$(tempDiv).html('<span id="' + id + '">MovieLanguage' + tempLang + '</span>');
                                    $(tempDiv).html('<span id="' + id + '">' + tempMvType + " " + tempLang + '</span>');

                                }
                            });
                        });

                    }

                    break;
                case 'contentId':
                    ToshURLvalue = Toshtemp.substring(IndexOfEqual + EndIndex);
                    //document.getElementById('URLToRedirect').value = ToshURLvalue;
                    chContentID = $.trim(ToshURLvalue);
                    break;
                case 'purchaseId':
                    ToshUSERID = Toshtemp.substring(IndexOfEqual + EndIndex);
                    //document.getElementById('Toshiba').value = ToshUSERID;
                    chPurchaseID = $.trim(ToshUSERID);
                    break;
                case 'offerId':
                    ToshUSERID = Toshtemp.substring(IndexOfEqual + EndIndex);
                    chOfferID = $.trim(ToshUSERID);
                    break;
                case 'OfferType':
                    ToshUSERID = Toshtemp.substring(IndexOfEqual + EndIndex);
                    chOfferType = ToshUSERID;
                    break;
                case 'Ep':
                    ToshUSERID = Toshtemp.substring(IndexOfEqual + EndIndex);
                    chEpisode = $.trim(ToshUSERID);
                    break;
                default:
                    break;
            }
            //XXXXXXXXXXXXXXXXXXXX  End Switch Case XXXXXXXXXXXXXXXXXXX
        }
        //XXXXXXXXXXXXXXXXXXXXXXX End For Loop XXXXXXXXXXXXXXXXXXXXXXXX

        if (chOfferID != undefined && chOfferType == "Rental" && iFlag == true) {

            // Disable the radio button againts the existing offer Id           

            // $('#detbox_price_box input[type="radio"]').each(function () { if (this.value == chOfferID) { this.checked; } })
            $("input[name='buy']").each(function (i) {
                if ($(this).val() == chOfferID) {
                    //Disable the radio button againts the existing offer Id                    
                    this.checked = true;
                    $(this).css('visibility', 'visible');
                    $(this).css("display", "block");
                    $(this).show();
                    $("input.detbox_radio_buy:radio").css("display", "block");
                }

            });

            //disable the radio button for Purchase,check if coming from episode
            if (chEpisode == 'false') {
                $("input[alt='buy']").css("display", "none");
            }
            // changes on 16th june to hide the text Price(Vat)


            $(".detbox_price_box_title").css("visibility", "hidden");
            $(".detbox_price_box_title").css("display", "none");
            $(".detbox_price_box_title").hide();
            //***************************
            // changes on 22nd june to hide voucher div
            //$("#detbox_vouchers_list").css("display", "none");
            $("#detbox_vouchers_list").css("visibility", "hidden");
            $("#detbox_vouchers_list").css("display", "none");
            // RN changes on 7th July
            $("#detbox_vouchers_list_box").css("visibility", "hidden");
            $("#detbox_vouchers_list_box").css("display", "none");

            $(".detbox_price_box_title_language").css('visibility', 'visible');
            $(".detbox_price_box_title_language").css("display", "block");

            //RN -Changes on 5th July to reduce space 
            //detbox_login_user_div  floatClear
            //$("div.detbox_login_user_div").css("display", "none");
            $(".floatClear").css("display", "none");
            //RN -Changes on 7th july to hide MovieLanguage EN text
            //RN -Changes on 19th July to Episode
            if (chEpisode == 'false') {
                $("#spnCLbuy", document).each(function () { $(this).hide() });
            }

            //RN-Changes on 23rd July to Select Default Radio Button-when no offer available
            var isOfferPresentCL = document.body.innerHTML.indexOf(chOfferID) > -1;
            if (isOfferPresentCL == false) {

                //Get the count of Radio                                              

                $("#dvChangeLanguage").hide();
                $("input[alt='rent']").css("display", "none");

                $(".detbox_price_box_title_language").css("display", "none");

                $(".detbox_price_box_OfferNotAvailble").css('visibility', 'visible');
                $(".detbox_price_box_OfferNotAvailble").css("display", "block");
                $(".detbox_price_box_OfferNotAvailble").show();

                if (chEpisode == 'false') {
                    $("#spnCLrent", document).each(function () { $(this).hide() });
                }
                var ictr = 0;
                var row_selector = $('#tblPriceDetails tbody tr');
                if (row_selector.length > 0) {
                    row_selector.each(function () {
                        if (ictr > 0)
                            $(this).hide();
                        ictr++;
                    });
                }

            }
            else {
                var vCL = 1;
            }

            //RN-Changes on 23rd July ends
            // Below end of If condition            

        }

        //XXXXXXXXXXXXXXXXX End for Rental If XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
        else if (chOfferID != undefined && chOfferType == "Purchase" && iFlag == true) {
            $("input[name='buy']").each(function (i) {
                if ($(this).val() == chOfferID) {
                    //Disable the radio button againts the existing offer Id
                    // $(this).attr('disabled', 'disabled');
                    this.checked = true;
                    $(this).css("display", "block");
                    $(this).css('visibility', 'visible');
                    $(this).css("display", "block");
                    $(this).show();
                    $("input.detbox_radio_buy:radio").css("display", "block");
                }

            });
            // disable the radio button for Rent,check if coming from episode

            if (chEpisode == 'false') {
                $("input[alt='rent']").css("display", "none");
            }
            //RN-changes on 16th june rajiv,to hide the text Price(Vat)

            $(".detbox_price_box_title").css("visibility", "hidden");
            $(".detbox_price_box_title").css("display", "none");
            $(".detbox_price_box_title").hide();

            // RN-changes on 22nd june to hide voucher div

            $("#detbox_vouchers_list").css("visibility", "hidden");
            $('#detbox_vouchers_list').css('display', 'none');
            // RN changes on 7th July
            $("#detbox_vouchers_list_box").css("visibility", "hidden");
            $("#detbox_vouchers_list_box").css("display", "none");
            //RN changes on 24th june to hide voucher div and dsiplay "Choose New Language"

            $(".detbox_price_box_title_language").css('visibility', 'visible');
            $(".detbox_price_box_title_language").css("display", "block");

            //RN -Changes on 5th July to reduce space

            $(".floatClear").css("display", "none");

            //RN -Changes on 7th july to hide MovieLanguage EN text
            //RN -Changes on 19th July to Episode
            if (chEpisode == 'false') {
                $("#spnCLrent", document).each(function () { $(this).hide() });
            }

            //RN-Changes on 23rd July to Select Default Radio Button-when no offer available
            var isOfferPresentCL = document.body.innerHTML.indexOf(chOfferID) > -1;
            if (isOfferPresentCL == false) {

                $("#dvChangeLanguage").hide();
                $("input[alt='buy']").css("display", "none");
                //to display the message Offer not available

                $(".detbox_price_box_title_language").css('visibility', 'hidden');
                $(".detbox_price_box_title_language").css('display', 'none');
                //to display the new message
                $(".detbox_price_box_OfferNotAvailble").css('visibility', 'visible');
                $(".detbox_price_box_OfferNotAvailble").css("display", "block");
                $(".detbox_price_box_OfferNotAvailble").show();

                if (chEpisode == 'false') {
                    $("#spnCLbuy", document).each(function () { $(this).hide() });
                }
                var ictr = 0;
                var row_selector = $('#tblPriceDetails tbody tr');
                if (row_selector.length > 0) {
                    row_selector.each(function () {
                        if (ictr > 0)
                            $(this).hide();
                        ictr++;
                    });
                }

            }
            else {
                var vCL = 1;
            }

            //Below end of if condition for Purchase
        }

        //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    }
    //XXXXXXXXXXXXXXXXXXXXXX End for IF condition   
    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
}

//************************************cHANGES RAJIV ENDS*********************

$(document).ready(function () {

    //RN-Changes on 20th July to handle space

    isChangeLanguageCalled = getParamCL('Action');
    if (isChangeLanguageCalled)
        isChangeLanguageCalled = true;
    else
        isChangeLanguageCalled = false;


    //RN-Changes to display MyMovies button

    $("#btnCLMyMovies").click(function () {

        //MB- Change from MyMoviesTV to MyMoviesTVHP
        window.location.href = "MyMovies.aspx?type=MyMoviesTVHP&filter=valid&mo=false";
    });

    //Changes ends

    //RN- Changes to update movie language
    $("#btnChangeLanguage").click(function () {
        //alert("Select Radio");
        GetLanguageRadioSelected();
        // MAKE AJAX CALL TO CHANGE LANGUAGE PAGE
        $.ajax({
            type: "POST",
            url: "UpdateLanguage.aspx",

            data: { offerid: chOfferID, newofferid: chNewofferid, purchaseid: chPurchaseID, contentid: chContentID, action: chAction },
            success: function (data) {

                // check the response from server visible the div true
                if (data == "Yes") {
                    // Make div visible 
                    //dvLangChanged
                    //style = "display:none;visibility:hidden;">                

                    $("#dvLangChanged").css('visibility', 'visible');
                    $("#dvLangChanged").css('display', 'block');
                    $("#dvLangNotChanged").hide();
                    //Disable button ChangeLanguage on June-13
                    $("#btnChangeLanguage").attr("disabled", "true");
                    //RN -Changes on 5th July to display MyMovies button
                    $("#btnCLMyMovies").css("visibility", "visible");
                    $("#btnCLMyMovies").css("display", "block");
                    $("#btnChangeLanguage").css("display", "none");


                }
                else if (data == "No") {

                    //dvLangNotChanged
                    $("#dvLangNotChanged").css('visibility', 'visible');
                    $("#dvLangNotChanged").css('display', 'block');

                    $("#dvLangChanged").hide();
                    $("#btnChangeLanguage").attr("disabled", "true");
                    //RN -Changes on 5th July to display MyMovies button
                    $("#btnCLMyMovies").css("visibility", "visible");
                    $("#btnCLMyMovies").css("display", "block");
                    $("#btnChangeLanguage").css("display", "none");


                }
                $('#detbox_vouchers_list').css('display', 'none');
            },
            complete: function (xhr) {
            }


        });
    });
    //$("#lang_selector a").click(function () {


    //RN************************************Rajiv June 11 changes  

    function GetLanguageRadioSelected() {
        var count = 0;

        for (count = 0; count < $("input.detbox_radio_buy:radio").length; count++) {
            if ($("input.detbox_radio_buy:radio")[count].checked) {
                //alert($("input.detbox_radio_buy:radio")[count].defaultValue);
                chNewofferid = $("input.detbox_radio_buy:radio")[count].defaultValue;
            }
        }
    }


    //***************************Rajiv June 11 changes ends*******************



    //$("body").prepend("<div class='WOOOT'></div>");
    //CLEAR CACHE FROM AJAX
    $.ajaxSetup({ cache: false })

    userIsAuthenticated = ($(".login_div .username span").css("display") != "none");

    // ******************************* MENU SELECT ****************************** //

    var page_id = $("#page_id").text();

    switch (page_id) {

        case "eded5ec1-cf91-4c2c-a6c2-8e87dfa8a258": // Home
            break;
        case "9a591e65-86d9-42fc-ba96-a558e162de8f": //Browse
            $("#nav li#nav-01 a").addClass("active");
            $("#page_id").text("Browse");
            break;
        case "c5af0c85-1627-47c5-91a4-a9aef8ccac46": //My Movies
            $("#nav li#nav-02 a").addClass("active");
            break;
        case "aea39bf0-34ef-4fcd-b80e-144d0b0b62e8": //My Account and My Devices
            if ($.getURLParam("tab") == "0" || $.getURLParam("tab") == "3" || $.getURLParam("tab") == '') {
                $("#nav li#nav-05 a:eq(0)").addClass("active");
                $("#page_id").text("My Account");
            } else if ($.getURLParam("tab") == "1") {
                $("#nav li#nav-03 a:eq(0)").addClass("active");
                $("#page_id").text("My Devices");
                $(".mydown_title5").text(varTitle);
            } else if ($.getURLParam("tab") == "2") {
                $("#nav li#nav-06 a:eq(0)").addClass("active");
                $("#page_id").text("Top-Up Credit");
            }
            break
        case "70699ddc-3c56-41c2-99e1-12dfd212b74e": //Voucher
            $("#nav li#nav-04 a").addClass("active");
            $("#page_id").text("Voucher");
            break
            //deles 2  
        case "2dbfaf21-01c9-4526-bae9-e55186a9866e": //New Releases
            $("#page_id").text("New Releases");
            break
        case "b292bb7b-f2b1-4a02-8993-716afb19dbde": //Most Popular
            $("#page_id").text("Most Popular");
            break





        case "d684617e-79ac-4766-9400-6d3f2c9d354d": //BrowseTVSeries
            $("#page_id").text("Browse");
            break
        case "469b3337-a395-4d44-b921-486194d3ebcc": //BrowseTVSeries Prod
            $("#page_id").text("Browse");
            break





        case "b92ce3fc-1030-4d3f-b481-544becc96e44": //Login
            $("#page_id").text("Login");
            break
        case "96757cc4-5a2b-43ad-8812-a1ec0db595d9": //Create Account
            $("#page_id").text("CreateAccount");
            break
        case "09e3e18f-5f4f-4bae-b9a9-448418d2e477": //Facebook Registration
            $("#page_id").text("FacebookRegistration");
            break

        case "fd5dd128-6e5f-4d02-b181-ef8cb46e7bea": //Details
            $("#page_id").text("Details");
            break
        case "3e1b3303-2922-41a6-85ba-1a9717f9f185": //My Downloads
            $("#nav li#nav-03 a").addClass("active");
            $("#page_id").text("My Downloads");
            break
        case "566a785e-ac86-4a72-9557-641c3edae5d2": //My Downloads - TV HP
            $("#nav li#nav-03 a").addClass("active");
            $("#page_id").text("My Downloads");
            break

        case "44f76939-61a1-4a61-b499-dd700b347245": //My Downloads Test- TV HP
            $("#nav li#nav-03 a").addClass("active");
            $("#page_id").text("My Downloads");
            break

        case "412b117a-b245-4f91-a89b-bfdaaf81338c": //Category Browsing
            $("#nav li#nav-01 a").addClass("active");
            $("#page_id").text("Category Browsing");
            break












        case "d8d6c75a-d22b-404e-8033-75aafbb63e37": //Register Device
        case "75d94769-5925-45c4-b6bc-0a9c76dbc5f2": //Register Device (Prod?)       
        case "7187eed0-de45-4dc1-8c86-57498cb4f1e2": // Register Device (Dev and Prod)
            //$("#nav li#nav-04 a:eq(0)").addClass("active");
            $("#page_id").text("Register Device");
            break
        case "8a3a632e-6e06-423f-b58b-39bc9adf24ff": //Edit Device
        case "c9bc4703-d7c9-4ddd-997e-44dd07317355": //Edit Device (Prod?)
        case "fd64cdca-d8e9-4f6c-ab9d-8d8eb2d237b1": //  Edit Device (Dev)
            $("#nav li#nav-04 a:eq(0)").addClass("active");
            $("#page_id").text("Edit Device");
            break
        case "12d462a6-6f05-47b7-9cee-54581f87561a": //Contact Us
            $("#page_id").text("Contact Us");
            addContactCustomerCareFormValidator();
            break

    }


    // ******************************* MENU SELECT ****************************** //


    // ******************************* HOME ******************************* //

    //workaround to speed the reSkin
    $(".land_cont:eq(1)").attr("class", "land_cont_2");
    $(".land_cont:eq(1)").attr("class", "land_cont_3");

    //dropdown menu 
    $("li#nav-05 a").hover(function () {
        $(this).parent().find("ul.subnav").slideDown('fast').show('fast');

        $(this).parent().hover(function () {
        }, function () {
            $(this).parent().find("ul.subnav").slideUp('50').hide('fast');
        });
    });

    /*$("li#nav-03 a").hover(function() {
    //Remove TV-Series
    //if($(this).parent().find("ul.subnav").find("li").length > 1)
    //$(this).parent().find("ul.subnav").find("li:last").remove();
    $(this).parent().find("ul.subnav").slideDown('fast').show('fast');

    $(this).parent().hover(function() {
    }, function() {
    $(this).parent().find("ul.subnav").slideUp('50').hide('fast');
    });
    });*/

    //RN-Changes on 20th July
    //if (userIsAuthenticated && !isChangeLanguageCalled) { //done for Rajeev 
    if (userIsAuthenticated) {
        getVouchersSumary();
    }


    // ******************************* /HOME ******************************* //




    // ******************************* GLOBAL LOGIN DIV ******************************* //

    //workaround to speed the reSkin
    toRemove = $(".login_div");
    $(".header_left").append("<div class='login_div'>" + $(".login_div").html() + "</div>");
    $(toRemove).remove();

    // ******************************* /GLOBAL LOGIN DIV ******************************* //



    // ******************************* LANGUAGE SELECT  ******************************* //

    var lang_timeout = 500;
    var lang_closetimer = 0;
    var lang_ddmenuitem = 0;

    function lang_open() {
        // cancel close timer
        lang_cancelclosetime();

        // close old layer
        if (lang_ddmenuitem) lang_ddmenuitem.style.visibility = 'hidden';

        // get new layer and show it
        lang_ddmenuitem = document.getElementById('lang_selector');
        lang_ddmenuitem.style.visibility = 'visible';

    }

    function lang_close() {
        if (lang_ddmenuitem) lang_ddmenuitem.style.visibility = 'hidden';
    }

    function lang_closetime() {
        lang_closetimer = window.setTimeout(lang_close, lang_timeout);
    }

    function lang_cancelclosetime() {
        if (lang_closetimer) {
            window.clearTimeout(lang_closetimer);
            closetimer = null;
        }
    }

    document.onclick = lang_close;

    //hover effects
    $(".header_left .lang, #lang_selector").mouseout(function () {
        lang_close();
    });

    $(".header_left .lang, #lang_selector").mouseover(function () {
        lang_open();
    });

    //Replace current selection
    $("#lang_selector a").click(function () {
        $(".lang").html($(this).html());
        var pickedLang = $(this).attr("title");
        $("#page_id").load("SetUserLang.aspx?lang=" + pickedLang, function () {
            window.location.reload(true);
        });
    });

    //Current choosen language TO CHANGE
    $(".lang").html($(".lang_selector a[title=" + $(".lang_selected").text() + "]").text());

    //Clear sepbar in bottom
    $(".footer_marketDetails span[title=" + $(".currentMarket").text() + "]").remove();
    $(".vertSepbar:last").remove();

    //Adds a border to the current Market country img
    $(".countryList img[alt=" + $(".currentMarket").text() + "]").parent().addClass('countrySelected');


    // ******************************* /LANGUAGE SELECT  ******************************* //


    // ******************************* IMG SLIDER ******************************* //

    $(".imgslider").each(function (index) {
        if (index != 0) {
            $(".imgslider:eq(0)").append($(this).html());
            $(this).remove();
        }
    });

    $(".infoslider").each(function (index) {
        if (index != 0) {
            $(this).children(".infoslider_bt").remove();
            $(".infoslider:eq(0)").append($(this).html());
            $(this).remove();
        }
    });

    $(".infoslider").append("<div class='controllslides'></div>")

    $(".imgslider img").each(function (index) {
        $(".controllslides").append('<a id="btn_slide_' + (index + 1) + '"><img height="21" border="0" width="21" alt="" src="acetrax/system/img/black_dot.png"/></a>');
    });

    $(".imgslider").attr("id", "imgslider");
    $(".infoslider").attr("id", "infoslider");


    //counts number of childs
    num_childs = $('#imgslider').children("img").size();
    //timer in ms
    timer = 4000;
    //truncate the descriptions for 160 characters
    $($($('#infoslider').children(".infoslider_txt")).children("div")).truncate(160);
    //show the first childs
    $($('#imgslider').children("img")).css("display", "none");
    $($('#imgslider').children("img")[0]).css("display", "block");
    $($('#infoslider').children(".infoslider_txt")[0]).css("display", "block");
    $($($('.controllslides').children("a")[0])).children("img").attr("src", "acetrax/system/img/red_dot.png");

    $('.controllslides a').bind("click", click_slide_bts);

    if ($('.infoslider_txt:eq(0)').attr("link") == "") {
        $(".infoslider_bt a").css("visibility", "hidden");
    } else {
        $(".infoslider_bt a").css("visibility", "visible");
        $(".infoslider_bt a").attr("href", $('.infoslider_txt:eq(0)').attr("link"));
    }

    $('#timmer').animate({ opacity: 1 }, timer, function () {
        click_slide_bts(1)
    });

    //on click btn_slide
    function click_slide_bts(auto) {
        $('.controllslides a').unbind("click", click_slide_bts);
        isto = this;

        $(".controllslides img").each(function () {
            if ($(this).attr("src") == "acetrax/system/img/red_dot.png") {
                child_to_hide = $($(this).parent()).attr("id").split("_");
            }
        });

        //		child_to_hide = $($(".controllslides img[src='acetrax/system/img/red_dot.png']").parent()).attr("id").split("_");

        child_to_hide = child_to_hide[2];

        if (auto != 1) {
            child_num = $(isto).attr("id").split("_"); //get the child number to apear
            child_num[2] = child_num[2];
        } else {
            $(".controllslides img").each(function () {
                if ($(this).attr("src") == "acetrax/system/img/red_dot.png") {
                    child_num = $($(this).parent()).attr("id").split("_");
                }
            });
            if (child_to_hide == num_childs) {
                child_num[2] = 1;
                child_to_hide = num_childs;
            } else {
                child_num[2] = parseInt(child_to_hide) + 1;
            }
        }

        //turn off everything
        $($('#imgslider').children("img")[child_to_hide - 1]).fadeOut("fast", function () {
            //turn on the equivalent child number
            $($('#imgslider').children("img")[child_num[2] - 1]).fadeIn("fast");
        });

        $($('#infoslider').children(".infoslider_txt")[child_to_hide - 1]).fadeOut("fast", function () {
            //turn on the equivalent child number
            $($('#infoslider').children(".infoslider_txt")[child_num[2] - 1]).fadeIn("fast", function () {
                $('.controllslides a').bind("click", click_slide_bts);
                $('#timmer').animate({ opacity: 1 }, timer, function () {
                    click_slide_bts(1)
                });
            });
        });
        $($($('.controllslides').children("a"))).children("img").attr("src", "acetrax/system/img/black_dot.png");

        //turn on the equivalent child number
        $($($('.controllslides').children("a")[child_num[2] - 1])).children("img").attr("src", "acetrax/system/img/red_dot.png");

        //add link to the player button
        if ($($('#infoslider').children(".infoslider_txt")[child_num[2] - 1]).attr("link") == "") {
            $(".infoslider_bt a").css("visibility", "hidden");
        } else {
            $(".infoslider_bt a").css("visibility", "visible");
            $(".infoslider_bt a").attr("href", $($('#infoslider').children(".infoslider_txt")[child_num[2] - 1]).attr("link"));
        }

    }


    // ******************************* /IMG SLIDER ****************************** //


    // ******************************* POPUPER ******************************* //

    // MYDOWNLOADS //

    $("a.dyn").mouseover(function (e) {
        //$(".coverall").width($(document).width()).height($(document).height()).show();
        $(".boxes .replace_content").empty();
        $(".boxes .replace_content").html($(this).next().html());
        $(".boxes .replace_content .box_details").show();
        if (e.pageX > ($(".boxes").width() * 1.1)) {
            // Left Side
            $(".boxes").css("left", (e.pageX - ($(".boxes").width() * 1.1)))
					   .css("top", (e.pageY - ($(".boxes").height() / 2)));
        } else {
            // Right Side
            $(".boxes").css("left", (e.pageX + ($(".boxes").width() * 0.1)))
					   .css("top", (e.pageY - ($(".boxes").height() / 2)));

        }
        //$(".boxes").fadeIn("slow");
        $(".boxes").show();
    }).mouseout(function () {
        $(".boxes").hide();
    });

    $("a.dyn1").click(function () {

        $.confirmPopup({
            'title': varLincensePopupTitle,
            'message': varLincensePopupText,
            'buttons': {
                Ok: {
                    'class': 'no_btns',
                    'action': function () {
                        $(".detbox_processing").addClass('hidden');
                        $('.detbox_btn').html('<input type="submit" class="detbox_btn_bg" value="Ok" id="btnOk" />');
                    }
                }
            }
        });
    });

    //created by sumit gupta on 15th sep. 2011 function for show popup for mymovie hd changes
    $("a#a_title").click(function () {
        isHD = true;
        $.playHdBox({
            'title': varPlayHDPopupTitle,
            'message': varPlayHDPopupText,
            'buttons': {
                Ok: {
                    'class': 'no_btns',
                    'action': function () {

                    }
                }
            }
        });
    });

    $("td#td_download").click(function () {
        isHD = true;
        //alert(isHD);
        $.playHdBox({
            'title': varPlayHDPopupTitle,
            'message': varPlayHDPopupText,
            'buttons': {
                Ok: {
                    'class': 'no_btns',
                    'action': function () {


                    }
                }
            }
        });
    });



    $("td#td_downloading .mobileOffer").click(function () {
        isMobileOffer = true;
        var classNames = $(this).parent().attr('class').split(' ');
        $.mobileOfferBox({
            'title': varMOPopupTitle,
            'message': varMOPopupText,
            'rowno': classNames[1],
            'buttons': {                
                Cancel: {
                    'class': 'no_btns',
                    'action': function () {
                        isMobileOffer = false;                      
                    }
                },
                Ok: {
                    'class': 'yes_btns',
                    'action': function () {
                        isMobileOffer = false;
                        mo_vaid = $('#version_select_' + classNames[1]).val(); //video asset id
                        downloadMovieforMobile();
                    }
                }
            }
        });
    });

    $("td#td_downloading").click(function () {
        isHD = false;
        //alert(isHD);
    });
    //end

    //tooltip quando download
    $(".td_last div").mouseover(function () {
        $(".boxes2 .replace_content").empty();
        $(".boxes2 .replace_content").html($(this).attr("tooltiptxt"));
        $(".boxes2").show();
    }).mousemove(function (e) {
        $(".boxes2").css("left", (e.pageX) + 10)
					    .css("top", (e.pageY - $(".boxes2").height() - 5));
    }).mouseout(function () {
        $(".boxes2").hide();
    }).click(function () {
        window.download_PID = $(this).attr("pid");
        window.download_COID = $(this).attr("coid");
        window.download_CHID = $(this).attr("chid");

        $(".mymovies_ajax_dummy").text(1);

        avsCheck(window.download_COID, AVS_WATCHMOVIE, function () {
            /* checked HD flag so that progress bar will not appear if movie is HD by sumit*/
            
            if (isMobileOffer == false) {
                if (isHD == false) {

                var checkif = setInterval(function () {

                    if (parseInt($(".mymovies_ajax_dummy").text()) == 0) {
                        clearInterval(checkif);
                    } else {
                        var getmoviersp = $.ajax({
                            url: "GetMovie.aspx",
                            data: { purchaseId: window.download_PID },
                            type: "POST",
                            async: false,
                            complete: function () {
                                var contentDownloadPopup = '<div class="container_close"><div class="close_tooltip" onclick="closeTooltp()"></div></div><div class="tooltip_text"></div><div class="tooltip_btn"></div>';
                                $(".coverall").width($(document).width()).height($(document).height()).show().css({ "opacity": "0.3", "background": "black" });
                                $(".boxes .replace_content").empty();
                                $(".boxes .replace_content").html(contentDownloadPopup);
                                $(".boxes .replace_content .box_details").show();
                            }
                        }).responseText;

                        getmovierspaux = getmoviersp.split(" ");
                        if (getmoviersp.substr(0, 7) == "PENDING") {
                            $(".mymovies_ajax_dummy").text(1);
                            $(".tooltip_text").text(varDownloadPending);
                            $(".tooltip_btn").empty();
                            $(".tooltip_btn").html('<img src="acetrax/system/img/ajax-loader.gif" />');
                            //$(".tooltip_text a").attr("href","Generic.aspx?type=SilverlightPlayer&InitParams=CH,"+window.download_CHID+";CO,"+window.download_COID);
                            marginTop = parseInt($('.boxes').height()) / 2 * -1 + "px";
                            marginLeft = parseInt($('.boxes').width()) / 2 * -1 + "px";
                            $(".boxes").show().css({ "top": "50%", "left": "50%", "marginTop": marginTop, "marginLeft": marginLeft });
                        } else if (getmovierspaux[0] == "FILE") {
                            $(".mymovies_ajax_dummy").text(0);
                            $(".tooltip_text").text(varDownloadReady);
                            $(".tooltip_btn").empty();
                            $(".tooltip_btn").append('<form action="' + getmovierspaux[1] + '"><input type="submit" class="acetrax_btn_bg" value="' + varDownloadBtn + '"/></form>');
                            marginTop = parseInt($('.boxes').height()) / 2 * -1 + "px";
                            marginLeft = parseInt($('.boxes').width()) / 2 * -1 + "px";
                            $(".boxes").show().css({ "top": "50%", "left": "50%", "marginTop": marginTop, "marginLeft": marginLeft });
                        } else {
                            $(".mymovies_ajax_dummy").text(0);
                            $(".tooltip_text").text(varDownloadError);
                            $(".tooltip_btn").empty();
                            marginTop = parseInt($('.boxes').height()) / 2 * -1 + "px";
                            marginLeft = parseInt($('.boxes').width()) / 2 * -1 + "px";
                            $(".boxes").show().css({ "top": "50%", "left": "50%", "marginTop": marginTop, "marginLeft": marginLeft });
                        }
                    }
                }, 3000);
            }
            }
        });
    });

    $(".coverall").click(function () {
        closeTooltp();
    })


    function downloadMovieforMobile() {

        //        window.download_PID = $(this).attr("pid");
        //        window.download_COID = $(this).attr("coid");
        //        window.download_CHID = $(this).attr("chid");

        $(".mymovies_ajax_dummy").text(1);

        avsCheck(window.download_COID, AVS_WATCHMOVIE, function () {
            /* checked HD flag so that progress bar will not appear if movie is HD by sumit*/
            //alert('s'+isMobileOffer);
            if (isMobileOffer == false) {
                if (isHD == false) {

                    var checkif = setInterval(function () {

                        if (parseInt($(".mymovies_ajax_dummy").text()) == 0) {
                            clearInterval(checkif);
                        } else {
                            var getmoviersp = $.ajax({
                                url: "GetMovie.aspx",
                                data: { purchaseId: window.download_PID, VideoAssetId: mo_vaid },
                                type: "POST",
                                async: false,
                                complete: function () {
                                    var contentDownloadPopup = '<div class="container_close"><div class="close_tooltip" onclick="closeTooltp()"></div></div><div class="tooltip_text"></div><div class="tooltip_btn"></div>';
                                    $(".coverall").width($(document).width()).height($(document).height()).show().css({ "opacity": "0.3", "background": "black" });
                                    $(".boxes .replace_content").empty();
                                    $(".boxes .replace_content").html(contentDownloadPopup);
                                    $(".boxes .replace_content .box_details").show();
                                }
                            }).responseText;

                            getmovierspaux = getmoviersp.split(" ");
                            if (getmoviersp.substr(0, 7) == "PENDING") {
                                $(".mymovies_ajax_dummy").text(1);
                                $(".tooltip_text").text(varDownloadPending);
                                $(".tooltip_btn").empty();
                                $(".tooltip_btn").html('<img src="acetrax/system/img/ajax-loader.gif" />');
                                //$(".tooltip_text a").attr("href","Generic.aspx?type=SilverlightPlayer&InitParams=CH,"+window.download_CHID+";CO,"+window.download_COID);
                                marginTop = parseInt($('.boxes').height()) / 2 * -1 + "px";
                                marginLeft = parseInt($('.boxes').width()) / 2 * -1 + "px";
                                $(".boxes").show().css({ "top": "50%", "left": "50%", "marginTop": marginTop, "marginLeft": marginLeft });
                            } else if (getmovierspaux[0] == "FILE") {
                                $(".mymovies_ajax_dummy").text(0);
                                $(".tooltip_text").text(varDownloadReady);
                                $(".tooltip_btn").empty();
                                $(".tooltip_btn").append('<form action="' + getmovierspaux[1] + '"><input type="submit" class="acetrax_btn_bg" value="' + varDownloadBtn + '"/></form>');
                                marginTop = parseInt($('.boxes').height()) / 2 * -1 + "px";
                                marginLeft = parseInt($('.boxes').width()) / 2 * -1 + "px";
                                $(".boxes").show().css({ "top": "50%", "left": "50%", "marginTop": marginTop, "marginLeft": marginLeft });
                            } else {
                                $(".mymovies_ajax_dummy").text(0);
                                $(".tooltip_text").text(varDownloadError);
                                $(".tooltip_btn").empty();
                                marginTop = parseInt($('.boxes').height()) / 2 * -1 + "px";
                                marginLeft = parseInt($('.boxes').width()) / 2 * -1 + "px";
                                $(".boxes").show().css({ "top": "50%", "left": "50%", "marginTop": marginTop, "marginLeft": marginLeft });
                            }
                        }
                    }, 3000);
                }
            }
        });

    }

    // /MYDOWNLOADS //

    // DETAILS //

    $(".detbox_under_movie_img, .episode_number").mouseover(function (e) {
        $(".boxes2 .replace_content").empty();
        $(".boxes2 .replace_content").html($(this).parent().find(".box_details").html());
        $(".boxes2 .replace_content .box_details").show();
        $(".boxes2").show();
    }).mousemove(function (e) {
        $(".boxes2").css("left", (e.pageX) + 10)
					   .css("top", (e.pageY - $(".boxes2").height() - 5));
    }).mouseout(function () {
        $(".boxes2").hide();
    });


    //Price Model Description ToolTip
    $(".detbox_price_box_buy_price").mouseover(function () {
        $(".boxes2 .replace_content").empty();
        $(".boxes2 .replace_content").html($(this).attr("tooltiptxt"));
        var arg = $(this)[0];
        var curTop = 0, curLeft = 0, curWidth = 0;
        if (arg.offsetParent) {
            do {
                curLeft += arg.offsetLeft;
                curTop += arg.offsetTop;
            } while (arg = arg.offsetParent)
        }
        curTop -= 45;
        $(".boxes2").css("left", curLeft - 20)
					    .css("top", curTop);
        $(".boxes2").show();
        /*}).mousemove(function(e) {
        $(".boxes2").css("left", (e.pageX) + 10)
        .css("top", (e.pageY - $(".boxes2").height() - 5));*/
    }).mouseout(function () {
        $(".boxes2").hide();
    });



    // /DETAILS //

    // ******************************* /POPUPER ******************************* //




    // ******************************* CATEGORY BROWSING ******************************* //

    if ($("#page_id").text() == "Category Browsing") {

        $("#banner_right a:eq(1) img").css("marginBottom", 0);
        $(".pagination a").each(function () {
            url_catbrow = $(this).attr('href').split("&showBundles");
            url_catbrow = url_catbrow[0] + "&showBundles=" + $.getURLParam("showBundles");
            $(this).attr('href', url_catbrow);
        });

        tab2Content = $(".retailAsset_tab_2").html();
        $(".retailAsset_tab_2").remove();

        $(".skin2_cb").append("<div class='retailAsset_tab_2'>" + tab2Content + "</div>")

        $("#nav_tab-02").click(function () {
            $(".retailAsset_tab_2").hide();
            $("#nav_tab-01 a").removeClass("current");
            $(".pagination").show();
            $(".retailAsset_tab_1").show();
            $("#nav_tab-02 a").addClass("current");
        });

        $("#nav_tab-01").click(function () {
            $(".retailAsset_tab_1").hide();
            $("#nav_tab-02 a").removeClass("current");
            $(".pagination").hide();
            $(".retailAsset_tab_2").show()
            $("#nav_tab-01 a").addClass("current");
        });

        // Use the class in to HTML to preselect nav-tab
        if ($("#nav_tab-01 a").attr("class") == "current") $("#nav_tab-01").click();
        if ($("#nav_tab-02 a").attr("class") == "current") $("#nav_tab-02").click();
    }

    // ******************************* /CATEGORY BROWSING ****************************** //




    // ******************************* BROWSING ******************************* //

    if ($("#page_id").text() == "Browse") {
        num_list_box_cont = $('.list_box_cont img').size();

        //for (i=0;i<num_list_box_cont;i++) {
        //	category_name = $(".list_box_cont:eq("+i+") .list_box_title").text();
        //	$(".list_box_cont:eq("+i+") .list_box img:eq(0)").attr("src",$(".js_aux_img[title='"+category_name+"']:eq(0)").text());
        //	$(".list_box_cont:eq("+i+") .list_box img:eq(1)").attr("src",$(".js_aux_img[title='"+category_name+"']:eq(1)").text());
        //}
        for (i = 0; i < num_list_box_cont; i++) {
            $(".list_box_cont img:eq(" + i + ")").attr("src", $(".js_aux_img:eq(" + i + ")").text());
        }
        $(".js_aux_img").remove();
    }

    // ******************************* /BROWSING ****************************** //





    // ******************************* BOXSET DETAIL ******************************* //

    //(PG-MD-20110721)
    if ($("#page_id").text() == "Details") {

        //erase the password field
        $(".detbox_textbox[name=password]").val("");
        //number of episodes
        bs_num_childs = $('.detbox_under_movie_box').size();
        //get Bundle Movie offer numbers
        if (bs_num_childs == 0)
            bs_num_childs = $('.detbox_under_bundle_movie_box').size();

        //delete values with 0.00 in price
        /*$('.detbox_price_box_buy_price span').each(function() {
        if ($(this).text() == "0.00") {
        $($(this).parent().parent().prev()).remove();
        $($(this).parent().parent()).remove();
        }
        });*/

        //select the buy option
        noBuys = 1;
        $(".detbox_price_box:eq(0)").find('.detbox_radio_buy').each(function (index) {
            if ($(this).attr("alt").toLowerCase() == "rent") {
                $(this).click();
                noBuys = 0;
            }
            if (($(".detbox_price_box:eq(0)").find('.detbox_radio_buy').size() == index + 1) && (noBuys == 1)) {

                $(this).click();
            }
        });

        if (chRadioLanguageValue) {
            chRadioLanguage.get(0).checked = true;
        }
        else {
            //select the option if clicking on the associated text
            $(".detbox_price_box_buy_price").click(function () {
                $(this).parent().prev().children().attr("checked", "checked");
            });
            $(".detbox_pay").click(function () {
                $(this).parent().prev().children().attr("checked", "checked");
            });

            //select the voucher options
            $(".detbox_radio_pay[value=voucher]").attr("checked", "checked");
        }
        //when Click&Buy is selected
        $("#detbox_pay_method *[value=clickbuy]").click(function () {

            $("#detbox_vouchers_list").slideUp("slow", function () {
                $(this).empty();
            });
        });

        //when paypal is selected
        $("#detbox_pay_method *[value=paypal]").click(function () {
            $("#detbox_vouchers_list").slideUp("slow", function () {
                $(this).empty();
            });
        });

        //when Vouchers is selected
        $("#detbox_pay_method *[value=voucher]").click(function () {
            //Get Vouchers if the user is logged in
            if ($(".login_div .username span").css("display") != "none")
                getDetailsVouchers();



        });

        //when a Payment Method is selected and Voucher's is selected
        $(".detbox_radio_buy").click(function () {

            // handle free offer
            if (!freeOffer() && !iFlag) {
                if ($("#detbox_pay_method *[value=voucher]").is(":checked")) {
                    $("#detbox_vouchers_list").slideUp("slow", function () {
                        $(this).empty();
                        //Get Vouchers if the user is logged in
                        if ($(".login_div .username span").css("display") != "none")
                            getDetailsVouchers();
                    });
                }
                if ($(".detbox_btn > .buyMovie").text() != "") {
                    $(".detbox_btn input[type=submit]").val($(".detbox_btn > .buyMovie").text());
                }
                else {
                    $(".detbox_btn input[type=submit]").val("Pay for movie");
                }
                //alert($(".detbox_btn > .buyMovie").text());
                // alert($(".detbox_btn input[type=submit]").text());
            } else
            //  $(".detbox_btn input[type=submit]").val($(".detbox_btn > .tryMovie").text());
                if ($(".detbox_btn > .buyMovie").text() != "") {
                    $(".detbox_btn input[type=submit]").val($(".detbox_btn > .tryMovie").text());
                }
                else {
                    $(".detbox_btn input[type=submit]").val("Pay for movie");
                }
        });


        Detail_RefreshGUI();

        initOfferDisplay();

        //
        var ep_buy_price = new Array();
        var serie_selected = false;

        for (i = 0; i < bs_num_childs; i++) {
            ep_buy_price[i] = parseFloat($(".detbox_selected:eq(" + i + ") .detbox_price").text());
        }

        //Define epsiodes box width
        if (bs_num_childs > 0) {
            //Force Display, required for dimension functions
            $('#wrap').css('display', 'block');

            //assign "Select episodes" box iner container width
            $(".detbox_under_box_box_box").width(83 * bs_num_childs);

        }

        //TV-SERIES

        //check if this is a TV-Serie
        if ($("#detbox_offer_type").html().toLowerCase() == "series season") {
            //global. Diff between bundle and ep
            isSeasonAsset = true;

            //Define Episode blocker dimensions
            $("#detbox_under_box_blocker").width($(".detbox_under_box").width() + 'px');
            $("#detbox_under_box_blocker").height($(".detbox_under_box").height() + 'px');
            //IE7 Fix
            //if (BrowserDetect.browser == "Explorer" && BrowserDetect.version == "7")
            //  $("#detbox_under_box_blocker").css('bottom', '25px');

            //Define episodes price value
            $(".detbox_price_box:eq(1)").find(".detbox_price_box_buy_price span").text('0.00');

            //Check the default selection
            if ($(".detbox_price_box:eq(0)").find('.detbox_radio_buy').attr('checked') == true)
                $("#detbox_under_box_blocker").css('display', 'block');

            //TV-Series when Buy/Rent season is selected
            $(".detbox_price_box:eq(0)").find(".detbox_radio_buy").click(function () {
                isSeasonAsset = true;
                if ($("#detbox_under_box_blocker").css('display') == 'none')
                    $("#detbox_under_box_blocker").css('display', 'block');

                //remove all selected episodes
                /*if($(".detbox_right_title").css('display') == 'block')
                $(".detbox_selected_close").click();*/
                $("#detbox_right_episode_info").hide();
                $("#detbox_right_details").show();
                if ($(".detbox_btn input").attr('disabled') == true) {
                    $(".detbox_btn input").attr('disabled', false);
                    $(".detbox_btn").animate({ opacity: 1 }, 100);
                }
            });

            //TV-Series when Buy/Rent episodes is selected
            $(".detbox_price_box:eq(1)").find(".detbox_radio_buy").click(function () {
                isSeasonAsset = false;
                $("#detbox_under_box_blocker").css('display', 'none');
                if ($("#detbox_right_details").height() == 0) {
                    var heightEpDetail = $(".detbox_right_rating").height() + $(".detbox_right_runtime").height() + $(".detbox_right_released").height() + $(".detbox_right_country").height() + $(".detbox_right_filesize").height() + $(".detbox_right_genre").height() + 'px';
                    $("#detbox_right_episode_info").css('height', heightEpDetail);
                    $("#detbox_right_episode_info").css('width', $(".detbox_right_rating").width() + 15 + 'px');
                    $("#detbox_right_episode_info").css('margin-bottom', ((5 * 6) + 16)/*padding and margin bottom*/ + 'px');
                }
                $("#detbox_right_details").hide();
                $("#detbox_right_episode_info").show();
                //Disable Buy button if price = 0.00
                if ($(".detbox_price_box:eq(1)").find(".detbox_price_box_buy_price span").text() == '0.00') {
                    $(".detbox_btn input").attr('disabled', true);
                    $(".detbox_btn").animate({ opacity: 0.5 }, 100);
                } else {
                    $(".detbox_btn input").attr('disabled', false);
                    $(".detbox_btn").animate({ opacity: 1 }, 100);
                }
            });

            //when clicking on an episode
            //and his episode number
            //$(".episode_number").click(function(){
            //   $(this).parent().click(); 
            //});
            $(".detbox_under_movie_box").click(function () {
                var total = 0;
                var serie_selected = false;
                //get the number of the clicked episode
                num_ep_click = $(".detbox_under_movie_box").index(this);
                //check if the episode is not on chart
                if ($(".detbox_selected:eq(" + num_ep_click + ")").css("display") == "none") {
                    serie_selected = true;
                    //if it is add episode to cart
                    $(".detbox_selected:eq(" + num_ep_click + ")").fadeIn("fast", function () {
                        onlyEpisodesAreBuyable();
                    });
                    num_selected_ep = 0;
                    for (i = 0; i < bs_num_childs; i++) {
                        if ($(".detbox_selected:eq(" + i + ")").css("display") != "none") {
                            total = total + ep_buy_price[i];
                            num_selected_ep++;
                        }
                    }
                    $(".detbox_price_box:eq(1)").find(".detbox_price_box_buy_price span").text(Math.round(total * 100) / 100);
                    //Check if all episodes were selected, and update price
                    if (num_selected_ep == bs_num_childs)
                        $(".detbox_price_box:eq(1)").find(".detbox_price_box_buy_price span").text($(".detbox_title").attr("title"));
                    //add white border
                    $(".detbox_under_movie_box:eq(" + num_ep_click + ") .detbox_under_movie_img").addClass("setbox_under_selected");
                    $(".detbox_under_movie_box:eq(" + num_ep_click + ") .detbox_under_movie_btns").text("remove");
                    //enable buy button
                    $(".detbox_btn input").attr('disabled', false);
                    $(".detbox_btn").animate({ opacity: 1 }, 100);
                } else {
                    //if its not remove episode from cart
                    $(".detbox_selected:eq(" + num_ep_click + ")").fadeOut("fast", function () {
                        for (i = 0; i < bs_num_childs; i++) {
                            if ($(".detbox_selected:eq(" + i + ")").css("display") != "none") {
                                serie_selected = true;
                                total = total + ep_buy_price[i]
                            }
                        }
                        $(".detbox_price_box:eq(1)").find(".detbox_price_box_buy_price span").text(Math.round(total * 100) / 100);
                        if (serie_selected == false) {
                            //No episode selected
                            $(".detbox_price_box:eq(1)").find(".detbox_price_box_buy_price span").text('0.00');
                            //Disable buy button
                            $(".detbox_btn input").attr('disabled', true);
                            $(".detbox_btn").animate({ opacity: 0.5 }, 100);
                        }
                        onlyEpisodesAreBuyable();
                    });
                    //remove white border
                    $(".detbox_under_movie_box:eq(" + num_ep_click + ") .detbox_under_movie_img").removeClass("setbox_under_selected");
                    $(".detbox_under_movie_box:eq(" + num_ep_click + ") .detbox_under_movie_btns").text("add");
                }
            });

            //when red X is clicked
            $(".detbox_selected_close").click(function () {
                var total = 0;
                var serie_selected = false;
                num_ep_close = $(".detbox_selected_close").index(this);
                $(".detbox_selected:eq(" + num_ep_close + ")").fadeOut("slow", function () {
                    for (i = 0; i < bs_num_childs; i++) {
                        if ($(".detbox_selected:eq(" + i + ")").css("display") != "none") {
                            serie_selected = true;
                            total = total + ep_buy_price[i]
                        }
                    }
                    $(".detbox_price_box:eq(1)").find(".detbox_price_box_buy_price span").text(Math.round(total * 100) / 100);
                    if (serie_selected == false) {
                        $(".detbox_price_box:eq(1)").find(".detbox_price_box_buy_price span").text('0.00');
                        //Disable buy button
                        $(".detbox_btn input").attr('disabled', true);
                        $(".detbox_btn").animate({ opacity: 0.5 }, 100);
                    } else {
                        //enable buy button
                        $(".detbox_btn input").attr('disabled', false);
                        $(".detbox_btn").animate({ opacity: 1 }, 100);
                    }
                    onlyEpisodesAreBuyable();
                });
                //remove white border
                $(".detbox_under_movie_box:eq(" + num_ep_close + ") .detbox_under_movie_img").removeClass("setbox_under_selected");
                $(".detbox_under_movie_box:eq(" + num_ep_close + ") .detbox_under_movie_btns").text("add");
            });
        }

        //Payment form validation
        sjcap("altTextField");

        if (FEATURE_DOUBLECHECK_ONPURCHASE) {
            $(".detbox_textbox[name=password]").focus();

            $("#detbox_form").validate({
                rules: {
                    username: {
                        required: true,
                        minlength: 4
                    },
                    password: {
                        required: true,
                        minlength: 4
                    },
                    pay: "required",
                    buy: "required"
                },
                submitHandler: function () {
                    /*if ($("input[name='terms']").attr("checked")) {*/
                    if ($("input[name='pay']:checked").val() == 'voucher') {
                        if (typeof ($("input[name='voucher']:checked").val()) != 'undefined')
                            itsPayTime();
                        else
                            $(".detbox_each_voucher_head > td:first").addClass('detbox_error');
                    } else
                        itsPayTime();
                    /*} else {
                    $(".detbox_terms").addClass("detbox_error");
                    }*/
                }
            });
        } else {
            $(".detbox_textbox[name=username]").focus();

            $("#detbox_form").validate({
                rules: {
                    username: {
                        required: false
                    },
                    password: {
                        required: false
                    },
                    //pay: "required",
                    buy: "required"
                },
                submitHandler: function () {
                    /*if ($("input[name='terms']").attr("checked")) {*/
                    if (userIsAuthenticated) {
                        if ($("input[name='pay']:checked").val() == 'voucher') {
                            var voucher = new Number();
                            var price = GetTotalPriceDetail();
                            if ($(".detbox_each_voucher_head").is(':visible')) {
                                if ($(".detbox_each_voucher").is(':visible')) {
                                    voucher = $("#detbox_vouchers_list_box").find("input:radio:checked").parent().next().attr("value");
                                    voucher = voucher.replace(",", ".");
                                    voucher = parseFloat(voucher);
                                }
                            }
                            else {
                                voucher = 0;
                            }
                            if (typeof ($("input[name='voucher']:checked").val()) != 'undefined') {
                                if (parseFloat(price) <= parseFloat(voucher)) {
                                    itsPayTime();
                                }
                                else {
                                    $("#detbox_vouchers_list_box").empty();
                                    $(".detbox_radio_pay[value=voucher]").removeAttr('checked');
                                    $("#detbox_vouchers_list_box").prepend("<tr class='detbox_each_voucher_head'><td colspan='3'>" + valueOnError + "</td></tr>");
                                    $(".detbox_each_voucher_head > td:first").addClass('detbox_error');

                                }
                            }
                            else {
                                if (!freeOffer())
                                    $(".detbox_each_voucher_head > td:first").addClass('detbox_error');
                                else
                                    itsPayTime();
                            }
                        } else if ($("input[name='pay']:checked").val() != null)
                            itsPayTime();
                        /*} else {
                        $(".detbox_terms").addClass("detbox_error");
                        }*/
                    } else {
                        itsPayTime();
                    }
                }
            });
        }
        /*$("input[name='terms']").click(function() {
        if ($(this).attr("checked"))
        $(this).parent().removeClass("detbox_error");
        });*/

    }


    // ******************************* /BOXSET DETAIL ******************************* //




    // ******************************* ACTIVATE VOUCHER ******************************* //

    if ($("#page_id").text() == "Voucher") {

        $(".voucher_sbox_cont .acetrax_btn_voucher_signin *").click(function () {
            isto = this;
            disableClick(isto);
            $.ajax({
                type: "POST",
                url: "RedeemVoucher.aspx",
                data: { voucherRef: $('.sbox_voucherinput').attr('value') },
                success: function () {
                    $(".voucher_exmp_box table").fadeOut("slow", function () {
                        getYourVouchers();
                        getVouchersSumary();
                    })
                },
                complete: function () {
                    enableClick(isto);
                }
            });
        });

        getYourVouchers();
        //dropVouchers(); 
    }

    // ******************************* /ACTIVATE VOUCHER ******************************* //




    // ******************************* LOGIN/LOGOUT ******************************* //

    Header_RefreshGUI("");

    if (userIsAuthenticated == false) {
        $("#nav-04 a").removeAttr("href");
        $("#nav-05 a").removeAttr("href");
    }

    if ($("#page_id").text() == "Login") {
        $("#wrap").fadeIn(300);
        $(".footer").fadeIn(300);
        $(".sbox_input[name=pw]").focus();

    }

    // ******************************* /LOGIN/LOGOUT ******************************* //




    // ******************************* CONTACT US ****************************** //

    if ($("#page_id").text() == "Contact Us") {

        //Validate if user is logged in by checked if his eMail was passed to the HTML
        if ($("#email_hidden").html() != '' && $("#email_hidden").html() != null) {
            $("#emailadress").val($("#email_hidden").html());
            $("#username").val($(".login_div .username span").text());
        }

        $("#browser").val(BrowserDetect.browser + " " + BrowserDetect.version);
        $("#opsystem").val(BrowserDetect.OS);

    }

    // ******************************* /CONTACT US ****************************** //


    // (PG-20110605)
    //******************************** Password Recovery *****************************//
    if ($("#page_id").text() == "Login") {
        var useremailToCheck;
        var usernameToCheck
        var multipleUser;
        var invalidEmailID;
        var invalidUserName
        //Trigger checknames funcionality
        $(".create_acc_box_form_line_pwd input[name='emailInput']").blur(function () {

            $(".sbox_label_Messagebox").addClass('hidden');
            useremailToCheck = $(this).val();
            if (useremailToCheck.length > 3) {
                $(".create_acc_check_name1").removeClass('hidden');
                $.ajax({
                    url: "CheckEmails.aspx",
                    type: "POST",
                    dataType: "json",
                    data: { emailInput: useremailToCheck },
                    success: function (resp) {
                        $(".create_acc_check_name1").addClass('hidden');
                        if (resp.result == "notexists") {
                            invalidEmailID = true;
                            $(".sbox_label_Messagebox").removeClass('hidden');
                            $(".sbox_label_Messagebox").html('<label id="lblErrorMessage"   class="sbox_label_Message_invalid">' + InValidEmailID + '</label>')

                        }
                        else if (resp.result == "existswith_oneuser") {
                            invalidEmailID = false;
                            $(".sbox_label_Messagebox").removeClass('hidden');
                            $(".sbox_label_Messagebox").html('<label id="lblErrorMessage" class="sbox_label_Message_valid">' + ValidEmailID + '</label>')
                        }
                        else if (resp.result == "existswith_moreuser") {
                            multipleUser = true;
                            $(".sbox_label_Messagebox").removeClass('hidden');
                            $(".sbox_label_Messagebox").html('<label id="lblErrorMessage" class="sbox_label_Message_valid" >' + MoreUsers + '</label>')
                            $(".create_acc_box_form_line_user").removeClass('hidden');
                        }
                        else if (resp.result == "blocked") {
                            $(".sbox_label_Messagebox").removeClass('hidden');
                            $(".sbox_label_Messagebox").html('<label id="lblErrorMessage" class="sbox_label_Message_invalid" >' + varBlocked_user + '</label>')
                        }
                        else {
                            $(".sbox_label_Messagebox").removeClass('hidden');
                            $(".sbox_label_Messagebox").html('<label id="lblErrorMessage" class="sbox_label_Message_invalid" >' + varError_user + '</label>')
                        }
                    },

                    error: function () {
                        $(".create_acc_check_name1").addClass('hidden');
                    },
                    complete: function () {
                        $(".create_acc_msg_box").removeClass('hidden');
                    }
                });
            }
        });
        $(".sbox_label_email input[name='emailInput']").focus(function () {
            $(".create_acc_msg_box").addClass('hidden');
            $(".sbox_label_Messagebox").addClass('hidden');
            $(".create_acc_msg_box").removeClass('detbox_error');
            $(".create_acc_msg_box").removeClass('detbox_correct');
        });

        $(".create_acc_box_form_line_user input[name='userInput']").blur(function () {
            $(".create_acc_check_name1").addClass('hidden');
            $(".create_acc_check_name2").removeClass('hidden');
            $(".sbox_label_Messagebox").addClass('hidden');
            usernameToCheck = $(this).val();
            if (usernameToCheck == null || usernameToCheck == "") {
                $(".sbox_label_Messagebox").removeClass('hidden');
                $(".sbox_label_Messagebox").html('<label id="lblErrorMessage"   class="sbox_label_Message_invalid">' + UserName + '</label>')
                $(".create_acc_check_name2").addClass('hidden');
            }
            else {
                $.ajax({
                    url: "CheckEmails.aspx",
                    type: "POST",
                    dataType: "json",
                    data: { emailInput: useremailToCheck, username: usernameToCheck },
                    success: function (resp) {
                        if (resp.result == "matchfound") {
                            invalidUserName = false;
                            $(".sbox_label_Messagebox").removeClass('hidden');
                            $(".sbox_label_Messagebox").html('<label id="lblErrorMessage"   class="sbox_label_Message_valid">' + ValidUserName + '</label>')
                            $(".create_acc_check_name2").addClass('hidden');
                        }
                        else if (resp.result == "nomatchfound") {
                            invalidUserName = true;
                            $(".sbox_label_Messagebox").removeClass('hidden');
                            $(".sbox_label_Messagebox").html('<label id="lblErrorMessage"   class="sbox_label_Message_invalid">' + InvalidUserName + '</label>')
                            $(".create_acc_check_name2").addClass('hidden');
                        }
                        else if (resp.result == "blocked") {
                            $(".sbox_label_Messagebox").removeClass('hidden');
                            $(".sbox_label_Messagebox").html('<label id="lblErrorMessage"   class="sbox_label_Message_invalid">' + varBlocked_user + '</label>')
                        }
                        else {
                            $(".sbox_label_Messagebox").removeClass('hidden');
                            $(".sbox_label_Messagebox").html('<label id="lblErrorMessage"   class="sbox_label_Message_invalid">' + varError_user + '</label>')
                        }
                    },

                    error: function () {
                        $(".create_acc_check_name1").addClass('hidden');
                        $(".create_acc_msg_box").html(varError_user);
                    },
                    complete: function () {
                        $(".create_acc_msg_box").removeClass('hidden');
                    }

                });
            }
        });


        $(".sbox_label_email input[name='emailInput']").focus(function () {
            $(".create_acc_msg_box").addClass('hidden');
            $(".create_acc_msg_box").removeClass('detbox_error');
            $(".create_acc_msg_box").removeClass('detbox_correct');
        });

        $(".acetrax_btn_password_retrieve .acetrax_btn_pwdRetrieve").click(function () {

            $(".create_acc_check_name1").addClass('hidden');
            $(".sbox_label_Messagebox").addClass('hidden');
            if (multipleUser == true && (usernameToCheck == null || usernameToCheck == undefined)) {
                $(".sbox_label_Messagebox").removeClass('hidden');
                $(".sbox_label_Messagebox").html('<label id="lblErrorMessage"   class="sbox_label_Message_invalid">' + UserName + '</label>')
            }
            else {
                if (useremailToCheck == null || useremailToCheck == undefined || useremailToCheck == "" || flag == false) {
                    $(".sbox_label_Messagebox").removeClass('hidden');
                    $(".sbox_label_Messagebox").html('<label id="lblErrorMessage"   class="sbox_label_Message_invalid">' + BlankEmailID + '</label>')
                }
                else if (invalidEmailID == true && (usernameToCheck == null || useremailToCheck == undefined)) {
                    $(".sbox_label_Messagebox").removeClass('hidden');
                    $(".sbox_label_Messagebox").html('<label id="lblErrorMessage"   class="sbox_label_Message_invalid">' + InValidEmailID + '</label>')
                    $(".capd1 input[name='uword']").val('');
                }
                else if (invalidUserName == true) {
                    $(".sbox_label_Messagebox").removeClass('hidden');
                    $(".sbox_label_Messagebox").html('<label id="lblErrorMessage"   class="sbox_label_Message_invalid">' + InvalidUserName + '</label>')
                    $(".capd1 input[name='uword']").val('');
                }
                else {
                    var flag = validateCaptchaForPassword();
                    if (flag == true) {
                        // $('.acetrax_btn_password_retrieve').html('<div class="create_acc_check_name_pass"><img src="/acetrax/system/img/ajax-loader.gif"></div>');
                        $('.acetrax_btn_password_retrieve').addClass('hidden');
                        $('.create_acc_check_name_pass').removeClass('hidden');
                        $.ajax({
                            url: "PasswordRetrieve.aspx",
                            type: "POST",
                            dataType: "json",
                            data: { emailInput: useremailToCheck, username: usernameToCheck },
                            success: function (resp) {
                                $(".create_acc_check_name1").addClass('hidden');
                                if (resp.result == "done") {
                                    $(".sbox_label_Messagebox").removeClass('hidden');
                                    $(".sbox_label_Messagebox").html('<label id="lblErrorMessage"   class="sbox_label_Message_valid">' + SuccessfulMail + '</label>')
                                    $(".create_acc_check_name_pass").addClass('hidden');
                                    $(".acetrax_btn_password_retrieve").removeClass('hidden');
                                    $("emailInput").val('');
                                    $(".create_acc_box_form_line_pwd input[name='emailInput']").val('');
                                    $(".create_acc_box_form_line_user input[name='userInput']").val('');
                                    $(".capd1 input[name='uword']").val('');
                                    $(".create_acc_box_form_line_user").addClass('hidden');
                                }
                            }
                        });
                    }
                }
            }
        }
        );

        $("input[name='pw']").focus(function () {

            $(".sbox_label_Messagebox").addClass('hidden');
        });
        $("input[name='new_pw']").focus(function () {

            $(".sbox_label_Messagebox").addClass('hidden');
        });
        $("input[name='emailInput']").focus(function () {

            $(".sbox_label_Messagebox").addClass('hidden');
        });
        $("input[name='userInput']").focus(function () {

            $(".sbox_label_Messagebox").addClass('hidden');
        });
        $("input[name='uword']").focus(function () {

            $(".sbox_label_Messagebox").addClass('hidden');
        });
    }
    //******************************* //Password Recovery****************************************//

    //********************************ValidateCaptchaForPasswordRecovery***********************//
    function validateCaptchaForPassword() {
        var uword = hex_md5(document.getElementById(jfldid).value);
        if (uword == cword[anum - 1]) {
            isto = ".acetrax_btn_pwdRetrieve";
            disableClick(isto);
            $(".capd1 .error_captcha").css("display", "none");
            return true;
        }
        else {
            if ($(".capd1 div.error").css("display") == "none") {

                $(".capd1 .error_captcha").css("display", "block");
            }
            document.getElementById(jfldid).focus();
            return false;
        }
    }
    //*********************************/ValidateCaptchaForPasswordRecovery***************************//
    

    // ******************************* CREATE ACCOUNT ****************************** //
    /* SG - 03/11/2011 made change for email using as username for simplified account creation */
    if ($("#page_id").text() == "CreateAccount") {
        //        $(".acc_input_bxs input[name='mail1']").keypress(function () {
        //            $(".create_acc_msg_box").addClass('hidden');
        //        });
        //Trigger checknames funcionality
        $(".acc_input_bxs input[name='mail1']").blur(function () {
            $(".create_acc_msg_box").addClass('hidden');
            var usernameToCheck = $(this).val();
            if (usernameToCheck.length > 3 && CheckEmail(usernameToCheck) == true) {
                $(".create_acc_check_name").removeClass('hidden');
                $.ajax({
                    url: "CheckEmails.aspx",
                    type: "POST",
                    dataType: "json",
                    data: { emailInput: usernameToCheck },
                    success: function (resp) {
                        $(".create_acc_check_name").addClass('hidden');
                        if (resp.result == "notexists") {
                            $(".create_acc_msg_box").html('<img src="acetrax/system/img/valid_icon.png" alt=""/><span class="create_acc_message">' + varValid_user + '</span>');
                            $(".create_acc_msg_box").addClass('detbox_correct');
                            $("input[name='userValidation']").val('ok');
                        }
                        else if (resp.result == "existswith_oneuser" || resp.result == "existswith_moreuser") {
                            $(".create_acc_msg_box").html('<img src="acetrax/system/img/invalid_icon.png" alt=""/><span class="create_acc_message">' + varExists_user + '</span>');
                            $(".create_acc_msg_box").removeClass('detbox_correct');
                            $(".create_acc_msg_box").addClass('detbox_error');
                            $("input[name='userValidation']").val('');
                        }
                        else if (resp.result == "blocked") {
                            $(".create_acc_msg_box").html('<img src="acetrax/system/img/invalid_icon.png" alt=""/><span class="create_acc_message">' + varBlocked_user + '</span>');
                            $(".create_acc_msg_box").removeClass('detbox_correct');
                            $(".create_acc_msg_box").addClass('detbox_error');
                            $("input[name='userValidation']").val('');
                        }
                        else {
                            $(".create_acc_msg_box").html('<img src="acetrax/system/img/invalid_icon.png" alt=""/><span class="create_acc_message">' + varError_user + '</span>');
                            $(".create_acc_msg_box").removeClass('detbox_correct');
                            $(".create_acc_msg_box").addClass('detbox_error');
                            $("input[name='userValidation']").val('');
                        }
                    },
                    error: function () {
                        $(".create_acc_check_name").addClass('hidden');
                        $(".create_acc_msg_box").html(varError_user);
                        //SG to show error msg in red color
                        $(".create_acc_msg_box").removeClass('detbox_correct');
                        $(".create_acc_msg_box").addClass('detbox_error');
                        $("input[name='userValidation']").val('');
                    },
                    complete: function () {
                        $(".create_acc_msg_box").removeClass('hidden');
                    }
                });
            } else {
                $(".create_acc_msg_box").addClass('hidden');
            }
        });
        $(".create_acc_box_form_line input[name='mail1']").focus(function () {
            $(".create_acc_msg_box").addClass('hidden');
            $(".create_acc_msg_box").removeClass('detbox_error');
            $(".create_acc_msg_box").removeClass('detbox_correct');
        });

        //Avoid user pass over checknames validation
        $('.acc_create_btn input').mousedown(function () {
            var usernameToCheck = $("input[name='mail1']").val();
            $.ajax({
                url: "CheckEmails.aspx",
                type: "POST",
                dataType: "json",
                data: { emailInput: usernameToCheck },
                success: function (resp) {
                    if (resp.result != "notexists")
                        $(".create_acc_box_form_line input[name='mail1']").blur();
                }
            });
        });
    }
    /*end*/
    // ******************************* /CREATE ACCOUNT ****************************** //



    // ******************************* MY DOWNLOADS ******************************* //

    if ($("#page_id").text() == "My Downloads" || $("#page_id").text() == "c5af0c85-1627-47c5-91a4-a9aef8ccac46") { //For My Movies) 

        $(".css-tabs a:eq(0)").addClass("current");

        $(".dropthisdown").click(function () {
            $($(this).next("div")).toggle("slow");
        });

        $(".tr_1 #rowdiv .td_1").each(function () {
            isto = this;
            a_md_dp = $(isto).next().text().split(" ");
            $(isto).next().text("" + a_md_dp[0]);
        });

        if ($.getURLParam("PagingSize")) {
            $(".myMovies_pagingSize div b").text($.getURLParam("PagingSize"));
            //Pagination Fix for A-Z and Date Purchased sorts
            $(".sort_inact").attr('href', $(".sort_inact").attr('href') + "&PagingSize=" + $.getURLParam("PagingSize"))
            $(".sort_act").attr('href', $(".sort_act").attr('href') + "&PagingSize=" + $.getURLParam("PagingSize"))
        }

        $(".myMovies_pagingSize").click(function () {
            if ($(".myMovies_pagingSize span div").css("display") == "none") {
                $(".myMovies_pagingSize > div").css("background-image", "url(acetrax/system/img/dropArrowDown.gif)");
                $(".myMovies_pagingSize span div").slideDown("slow");
            } else {
                $(".myMovies_pagingSize > div").css("background-image", "url(acetrax/system/img/dropArrowRight.gif)");
                $(".myMovies_pagingSize span div").slideUp("slow");
            }
        });

        $(".myMovies_pagingSize span div").mouseover(function () { $(this).css("color", "red") })
										  .mouseout(function () { $(this).css("color", "#CFCFCF") })
										  .click(function () {
										      $(".myMovies_pagingSize div b").text($(this).text())
										      window.location.href = "MyMovies.aspx?type=MyMoviesTVHP&filter=" + $.getURLParam("filter") + "&mo=" + $.getURLParam("mo") +"&sort=" + $.getURLParam("sort") + "&PagingSize=" + $(this).text();
										  })

        if ($.getURLParam("sort") == "Title") {
            $(".sort_inact").css("color", "#CE1126");
            $(".sort_act").css("color", "#CFCFCF");
        } else {
            $(".sort_inact").css("color", "#CFCFCF");
            $(".sort_act").css("color", "#CE1126");
        }

        $(".pagination a").each(function () {
            url_pag = "";
            url_pag = $(this).attr("href");
            url_pag = url_pag.split("&PagingSize");
            if ($.getURLParam("sort") == "Title") {
                url_pag = url_pag[0] + "&filter=" + $.getURLParam("filter") + "&sort=Title&PagingSize=" + $(".myMovies_pagingSize div b").text();
            } else {
                url_pag = url_pag[0] + "&filter=" + $.getURLParam("filter") + "&PagingSize=" + $(".myMovies_pagingSize div b").text();
            }
            $(this).attr("href", url_pag);
        })

        //$("a.dyn").truncate(10);

        if ($.getURLParam("filter") == "valid") {
            $("#sort_inactive a:eq(0)").removeClass("hidden");
            $("#sort_inactive a:eq(1)").addClass("hidden");
            if ($("#sort_inactive a")[0] != null || $("#sort_inactive a")[0] != undefined) {
                mobileLocation = location.href.replace("valid", "all");
                $("#sort_inactive a")[0].href = location.href.replace("valid", "all");
                $("#sort_inactive a")[0].href = $("#sort_inactive a")[0].href.replace("pos=" + $.getURLParam("pos") + "&", "");
            }
        } else {
            $("#sort_inactive a:eq(1)").removeClass("hidden");
            $("#sort_inactive a:eq(0)").addClass("hidden");
            $("#sort_inactive a")[1].href = location.href.replace("all", "valid");
            $("#sort_inactive a")[1].href = $("#sort_inactive a")[1].href.replace("pos=" + $.getURLParam("pos") + "&", "");
            for (var i = 0, leng = $(".pagination ul li a").length; i < leng; i++) {
                $(".pagination ul li a")[i].href = $(".pagination ul li a")[i].href.replace("?filter=all&", "?");
            }
            for (var i = 0, leng = $(".sort a").length; i < leng; i++) {
                $(".sort a")[i].href = $(".sort a")[i].href.replace("valid", "all");
            }
        }

        //Ellipsis efect on firefox
        if (BrowserDetect.browser == "Firefox") {
            //FORCE page display
            $("#wrap").css('display', 'block');
            for (var i = 0, len = $(".td_1").length; i < len; i++) {
                selectorStrA = ".td_1:eq(" + i + ") a";
                selectorStrSpan = ".td_1:eq(" + i + ") span";
                if ($(selectorStrSpan)[0] == undefined)
                    $(selectorStrA).ellipsis();
                else {
                    $(selectorStrSpan).ellipsis();
                }
            }
        }

        //Tooltip popup re-styling
        if ($(".boxes .cantos").parent().size() > 0)
            $(".boxes .cantos").parent().remove();

        //Fix offers in bundles that already had expired and were shown as active
        if ($.getURLParam('filter') == 'valid') {
            $(".dropthisdown").next("div").find(".status_exp").each(function () {
                $(this).parent().remove();
            });

            var flagData = true;
            $(".dropthisdown").next("div").find(".td_1").next().each(function () {
                if (($(this).text() != $(this).parent().next().find(".td_1").next().text()) && $(this).parent().next().find(".td_1").next().text() != "")
                    flagData = false;
            });

            var flagLicType = true;
            $(".dropthisdown").next("div").find(".license_status").prev().each(function () {
                if (($(this).text() != $(this).parent().next().find(".license_status").prev().text()) && $(this).parent().next().find(".license_status").prev().text() != "")
                    flagLicType = false;
            });

            var flagLicense = true;
            $(".dropthisdown").next("div").find(".license_status").each(function () {
                if (($(this).text() != $(this).parent().next().find(".license_status").text()) && $(this).parent().next().find(".license_status").text() != "")
                    flagLicense = false;
            });

            if (flagData)
                $(".dropthisdown .td_1").next().text($(".dropthisdown").next("div").find(".td_1").next(":eq(0)").text());
            if (flagLicType)
                $(".dropthisdown .license_status").prev().text($(".dropthisdown").next("div").find(".license_status").prev(":eq(0)").text());
            if (flagLicense) {
                $(".dropthisdown .license_status").each(function () {
                    $(this).text($(this).parent().parent().parent().next("div").find(".license_status:eq(0)").text());
                    $(this).addClass("status_act");
                });
            }
            //remove bundles if his child offers have all expired
            $(".dropthisdown").each(function () {
                if ($(this).next("div").find(".td_1").next().length == 0)
                    $(this).parent().remove()
            });
        }


    }

    // ******************************* /MY DOWNLOADS ******************************* //
    //(PG-MD-20110707)
    //(PG-MD-20110714)
    //(PG-MD-20110726)
    function userCheck(contentId, varConfmMessageBuy, successCallback) {
        $.ajax({
            url: "userMovies.aspx",
            type: "POST",
            datatype: "xml",
            data: {
                assetId: contentId,
                type: "usermovies"

            },
            success: function (data) {

                var hasMovie = $(data).find('UserMovie').attr('hasmovie');
                var result = $(data).find('UserMovie').attr('result');
                var purchaseType = $(data).find('UserMovie').attr('purchaseType');
                var purchasedate = $(data).find('UserMovie').attr('purchasedate');
                var movielanguage = $(data).find('UserMovie').attr('movielanguage');
                var licenseexpirydate = $(data).find('UserMovie').attr('licenseexpirydate');
                var licenseissueingcount = $(data).find('UserMovie').attr('licenseissueingcount');
                if (hasMovie == "True") {
                    //This needs to change to JS pop and Yes/no option
                    //and if Yes is selected then it should call sucesscallback again
                    //or if no is selected it should stay on the same page.
                    //showModalPopup('Generic.aspx?type=UserMoviesMessage&retrunVal=' + result, 'frameId_UserMoviesMessage', '645', '330', '', this);
                    // var dialogresult = confirm(result);
                    if (purchaseType == "Buy") {
                        var Message = varConfmMessageBuy.replace("{0}", purchaseType).replace("{1}", movielanguage).replace("{2}", purchasedate);
                    }
                    else {
                        var Message = varConfmMessageRent.replace("{0}", purchaseType).replace("{1}", purchasedate).replace("{2}", movielanguage).replace("{3}", licenseexpirydate).replace("{4}", licenseissueingcount);
                    }
                    var result = $.confirm({
                        'title': varConfirmPurchase,
                        'message': Message,
                        'buttons': {
                            No: {
                                'class': 'no_btns',
                                'action': function () {
                                    $(".detbox_processing").addClass('hidden');
                                    $('.detbox_btn').html('<input type="submit" class="detbox_btn_bg" value="Pay for movie" id="btnPayMovie" />');
                                }
                            },
                            Yes: {
                                'class': 'yes_btns',
                                'action': function () {
                                    // elem.slideUp();
                                    successCallback();
                                    return true;
                                }

                            }

                        }
                    });
                }
                else {
                    successCallback();
                }
            }
        })
    };

    (function ($) {

        $.confirm = function (params) {

            if ($('#confirmOverlay').length) {
                // A confirm is already shown on the page:
                return false;
            }

            var buttonHTML = '';
            $.each(params.buttons, function (name, obj) {
                var Yes = varMultipleYes;
                var No = varMultipleNo;
                // Generating the markup for the buttons:
                if (obj['class'] == 'yes_btns') {
                    buttonHTML += '<a href="#" class="button ' + obj['class'] + '">' + Yes + '</a>';
                }
                else {
                    buttonHTML += '<a href="#" class="button ' + obj['class'] + '">' + No + '</a>';
                }

                if (!obj.action) {
                    obj.action = function () { };
                }
            });

            var markup = [
			'<div id="confirmOverlay">',
			'<div id="confirmBox">',
			'<h1>', params.title, '</h1>',
			'<p>', params.message, '</p>',
			'<div id="confirmButtons">',
			buttonHTML,
			'</div></div></div>'
		].join('');

            $(markup).hide().appendTo('body').fadeIn();

            var buttons = $('#confirmBox .button'),
			i = 0;

            $.each(params.buttons, function (name, obj) {
                buttons.eq(i++).click(function () {

                    // Calling the action attribute when a
                    // click occurs, and hiding the confirm.

                    obj.action();
                    $.confirm.hide();
                    return false;
                });
            });
        }

        $.confirm.hide = function () {
            $('#confirmOverlay').fadeOut(function () {
                $(this).remove();
            });
        }

    })(jQuery);
    //aman starts
    (function ($) {

        $.confirmPopup = function (params) {

            if ($('#confirmOverlay').length) {
                // A confirm is already shown on the page:
                return false;
            }

            var buttonHTML = '';
            $.each(params.buttons, function (name, obj) {
                var Ok = varLincensePopupButtonText;
                // Generating the markup for the buttons:

                buttonHTML += '<a href="#" class="button ' + obj['class'] + '">' + Ok + '</a>';

                if (!obj.action) {
                    obj.action = function () { };
                }
            });

            var markup = [
			'<div id="confirmOverlay">',
			'<div id="confirmBox">',
			'<h1>', params.title, '</h1>',
			'<p>', params.message, '</p>',
			'<div id="confirmButtons">',
            '</BR></BR>',
			buttonHTML,
			'</div></div></div>'
		].join('');

            $(markup).hide().appendTo('body').fadeIn();

            var buttons = $('#confirmBox .button'),
			i = 0;

            $.each(params.buttons, function (name, obj) {
                buttons.eq(i++).click(function () {

                    // Calling the action attribute when a
                    // click occurs, and hiding the confirm.

                    obj.action();
                    $.confirmPopup.hide();
                    return false;
                });
            });
        }

        $.confirmPopup.hide = function () {
            $('#confirmOverlay').fadeOut(function () {
                $(this).remove();
            });
        }

    })(jQuery);
    //aman ends


    //created by sumit on 16/09/2011 for Play HD movie
    //starts
    (function ($) {

        $.playHdBox = function (params) {

            if ($('#confirmOverlay').length) {
                // A confirm is already shown on the page:
                return false;
            }

            var buttonHTML = '';
            $.each(params.buttons, function (name, obj) {
                var Ok = varLincensePopupButtonText;
                // Generating the markup for the buttons:

                buttonHTML += '<a href="#" class="button ' + obj['class'] + '">' + Ok + '</a>';

                if (!obj.action) {
                    obj.action = function () { };
                }
            });

            var markup = [
			'<div id="confirmOverlay">',
			'<div id="playHdBox">',
			'<h1>', params.title, '</h1>',
			'<p>', params.message, '</p>',
			'<div id="playHDButtons">',
			buttonHTML,
			'</div></div></div>'
		].join('');

            $(markup).hide().appendTo('body').fadeIn();

            var buttons = $('#playHdBox .button'),
			i = 0;

            $.each(params.buttons, function (name, obj) {
                buttons.eq(i++).click(function () {

                    // Calling the action attribute when a
                    // click occurs, and hiding the confirm.

                    obj.action();
                    $.playHdBox.hide();
                    return false;
                });
            });
        }

        $.playHdBox.hide = function () {
            $('#confirmOverlay').fadeOut(function () {
                $(this).remove();
            });
        }

    })(jQuery);
    //end by sumit 

    //SG popup for mobile offers

    (function ($) {

        $.mobileOfferBox = function (params) {

            if ($('#confirmOverlay').length) {
                // A confirm is already shown on the page:
                return false;
            }
            var buttonHTML = '';


            var selectBox = $('#dvmo_' + params.rowno).html();
            $.each(params.buttons, function (name, obj) {
                var Ok = varLincensePopupButtonText;
                var Cancel = varLincenseCancelButton;
                // Generating the markup for the buttons:

                buttonHTML = '<a href="#" class="button ' + obj['class'] + '">' + Cancel + '</a>';
                buttonHTML += '<a href="#" class="button ' + obj['class'] + '">' + Ok + '</a>';                

                if (!obj.action) {
                    obj.action = function () { };
                }
            });

            var markup = [
			'<div id="confirmOverlay">',
			'<div id="mobileOfferBox">',
			'<h1>', params.title, '</h1>',
			'<p>', params.message, '</p>',
             selectBox,
			'<div id="mobileOfferButtons"><br/><br/>',
			buttonHTML,
			'</div></div></div>'
		].join('');

            $(markup).hide().appendTo('body').fadeIn();

            var buttons = $('#mobileOfferBox .button'),
			i = 0;

            $.each(params.buttons, function (name, obj) {
                buttons.eq(i++).click(function () {

                    // Calling the action attribute when a
                    // click occurs, and hiding the confirm.

                    obj.action();
                    $.mobileOfferBox.hide();
                    return false;
                });
            });
        }

        $.mobileOfferBox.hide = function () {
            $('#confirmOverlay').fadeOut(function () {
                $(this).remove();
            });
        }

    })(jQuery);

    function userPurchase(offerId, currency, totalPrice, voucherId, varProcessing, varError, varConfmMessage) {
        $(".detbox_btn").empty();
        //$(".detbox_btn_bg").addClass('hidden');
        $(".detbox_btn").append("<div class='detbox_processing'>" + varProcessing + "</div>");

        var contentId = $(this).find('contentId').text();
        if (contentId == "") contentId = $.getURLParam("contentID");
        userCheck(contentId, varConfmMessage, function () {

            submitPurchase(offerId, currency, totalPrice, voucherId, varProcessing, varError);
        });

    }

    function itsPayTime() {

        //check if there's at least one of the options (rent or buy) selected
        if ($(".detbox_price_box input:checked").attr('checked') != true) {
            alert("You must select an episode");
        } else {
            isto = $(".detbox_btn_bg");
            disableClick(isto);

            //check if it's an episode/bundle
            if ($(".detbox_right_title").attr("class")) {
                offerId = "";
                first = 0;
                //get all the offerId from the ep/bu
                $('.detbox_selected').each(function () {
                    if ($(this).css("display") != "none" && !isSeasonAsset) {
                        if (first == 0) {
                            offerId = offerId + "" + $(this).attr("value");
                        } else {
                            offerId = offerId + "," + $(this).attr("value");
                        }
                        first = 1;
                    }
                });

                //if ther's no ep/bu selected selects the entire serie/bundle
                if (offerId == "") {
                    offerId = $(".detbox_radio_buy:checked").val();
                }
            } else {
                offerId = $(".detbox_radio_buy:checked").val();
            }

            if (freeOffer()) {
                // use dummy voucher
                voucherId = "00000000-0000-0000-0000-000000000000";
            } else {
                voucherId = $("#detbox_vouchers_list_box input:checked").val();
            }
            /*http://local.acetrax.viatecla.com:1896/Detail.aspx?channelId=&contentID=047B74D3-F262-4956-9A9C-CD5AF0D02F64*/

            //currency = $(".detbox_price_box_title").attr("title");
            //totalPrice = $(".detbox_radio_buy:checked").parent().next().children().children().text();
            currency = $("#detbox_form").find("input:eq(0)").attr('value');
            totalPrice = GetTotalPriceDetail();
            //= $('#' + offerId).val();
            //if (totalPrice === undefined)
            //{ totalPrice = $(".detbox_radio_buy:checked").parent().next().children().children().text(); }
            buy_username = $('.detbox_login_user').parent().next().children().val();
            buy_password = $('.detbox_login_pass').parent().next().children().val();

            if (FEATURE_DOUBLECHECK_ONPURCHASE == true || userIsAuthenticated == false) {
                //if not logedIn
                if (hex_md5($(".username span").text().toLowerCase()) == "230a091930a82c5ae47e29610ee98ceb") {
                    ajaxLogin(buy_username,
                      buy_password,
                      {
                          success: function () {
                              $(".detbox_login_invalid").slideUp("slow");
                              //simulate login
                              Header_RefreshGUI(buy_username);
                              Detail_RefreshGUI();
                              initOfferDisplay();
                              enableClick(isto);
                          },
                          failure: function () {
                              $(".detbox_login_invalid").slideDown("slow");
                              enableClick(isto);
                          }
                      }
			);
                    //if logedIn
                } else {
                    ajaxLogin(
				buy_username,
				buy_password,
				{
				    success: function () {
				        $(".detbox_login_invalid").slideUp("slow");
				        //if trying to confirm with a diferent user
				        if ($(".username span").text() != buy_username) {
				            //simulate login
				            Header_RefreshGUI(buy_username);
				            getDetailsVouchers();
				            enableClick(isto);
				        } else {
				            // all good to go
				            alert("good");
				            userPurchase(offerId, currency, totalPrice, voucherId, varProcessing, varError, varConfmMessage);
				            //submitPurchase(offerId, currency, totalPrice, voucherId, varProcessing, varError);
				        }
				    },
				    failure: function () {
				        $(".detbox_login_invalid").slideDown("slow");
				        enableClick(isto);
				    }
				}
			);
                }
            } else {
                // all good to go
                //Manoj
                userPurchase(offerId, currency, totalPrice, voucherId, varProcessing, varError, varConfmMessageBuy);
                //submitPurchase(offerId, currency, totalPrice, voucherId, varProcessing, varError);
            }
        }
    }
    // ******************************* My Account and Devices ******************************* //

    if ($("#page_id").text() == "My Account" || $("#page_id").text() == "My Devices" || $("#page_id").text() == "Top-Up Credit") {

        $(".acc_label_user").text($(".username span").text());
        getYourVouchers();

        //getUserInfo();

        if ($.getURLParam("tab") == 0 || $.getURLParam("tab") == "") {
            $(".css-tabs a:eq(1)").addClass("current");
            $('.my_account').show()
        } if ($.getURLParam("tab") == 1) {
            $(".css-tabs a:eq(2)").addClass("current");
            $('.my_devices').show()
        } if ($.getURLParam("tab") == 2) {
            $(".css-tabs a:eq(3)").addClass("current");
            $('.my_topupcredit').show()
        } if ($.getURLParam("tab") == 3) {
            $(".css-tabs a:eq(1)").addClass("current");
            $(".my_accountadult_loader").show();
            avsMyAccountAdult(function () {
                $(".my_accountadult").show();
                $(".my_accountadult_loader").hide();
            });
        }

        $.ajax({
            type: "GET",
            url: "GetUser.aspx",
            dataType: "xml",
            success: function (xml) {
                $(xml).find("UserInfo").each(function () {
                    var email = $(xml).find("Email").text();
                    if (email == "") email = "dummy";
                    $(".acc_input[name='email']").attr("value", email);
                });
                $(xml).find("set_top_box").each(function () {
                    deviceName = $(this).attr("manufacturer") + " - " + $(this).attr("model");
                    uniqueId = $(this).attr("unique_id");
                    deviceId = uniqueId; //deviceId = $(this).attr("mac_address");
                    settopboxid = $(this).attr("id");
                    //$(".my_devices_box").append('<div class="deviceRow"><span>'+deviceName+' ('+deviceId+')</span><a href="Generic.aspx?type=EditDevice&uniqueId='+uniqueId+'">Edit</a><a href="#" class="remove_device" onclick="removeDevice(\''+settopboxid+'\')">Remove</a></div>');
                    $(".my_devices_box").append('<div class="deviceRow"><span><div>' + deviceName + '</div> <a class="infoDeviceId" info="' + deviceId + '" href="javascript:void(0)"><img width="20" height="20" src="acetrax/system/img/info.png" alt=""/></a></span><a href="javascript:void(0)" class="remove_device" onclick="removeDevice(\'' + settopboxid + '\')">' + varDownloadRemove + '</a></div>');
                });
                $(".devices_loader").remove();
                $(".my_devices_box").show("slow");

                $('.deviceRow .infoDeviceId')
					.bind('mouseover', function () {
					    $(".boxes2 .replace_content").empty();
					    $(".boxes2 .replace_content").html($(this).attr("info"));
					    $(".boxes2").show();
					})
					.bind('mousemove', function (e) {
					    $(".boxes2").css("left", (e.pageX) + 10)
					    .css("top", (e.pageY - $(".boxes2").height() - 5));
					})
					.bind('mouseout', function () {
					    $(".boxes2").hide();
					})
            }
        });

    }

    // ******************************* /My Account and Devices ******************************* //




    // ******************************* Register Device ******************************* //

    if ($("#page_id").text() == "Register Device") {

        $.ajax({
            type: "GET",
            url: "GetModels.aspx",
            dataType: "xml",
            success: function (xml) {
                $(xml).find("ModelInfo").each(function () {
                    if ($(this).attr("result") != "Ok") {
                        //window.location.href = 'Error.aspx?type=GeneralError';
                        alert("Error");
                    } else {
                        $(this).find("manufacturer").each(function () {
                            id_ma = $(this).attr("id");
                            name_ma = $(this).attr("name");
                            $("select[name=manufacturer]").append('<option value="' + id_ma + '">' + name_ma + '</option>');
                            $(this).find("model").each(function () {
                                id_mo = $(this).attr("id");
                                name_mo = $(this).attr("name");
                                $("select[name=model]").append('<option style="display:none" ass="' + id_ma + '" value="' + id_mo + '">' + name_mo + '</option>');
                            });
                        });
                    }
                });
            }
        });

        $(".acetrax_btn_verifyUniqueID .acetrax_btn_bg").click(function () {

            if ($("#uniqueId").val()) {
                $("div[htmlfor=uniqueidvalidation]").html('<img src="acetrax/system/img/ajax-loader.gif" />')
                $.ajax({
                    url: "MyDevice.aspx",
                    dataType: "xml",
                    type: "POST",
                    data: { uniqueId: $("#uniqueId").val() },
                    success: function (xml) {
                        $(xml).find("DeviceInfo").each(function () {
                            if ($(this).attr("result") != "Ok") {
                                $("#uniqueidvalidation").attr("value", "0");
                                $("div[htmlfor=uniqueidvalidation]").html(invalidUniqueID);
                            } else {
                                $(".uniqueid_invalid").text("");
                                $(".uniqueid_invalid").text();
                                iddobruno = $(this).find("ID").text();
                                //deviceId = $(this).find("MacAddress").text();
                                $("#uniqueId").attr("disabled", "disabled");
                                $("#iddobruno").val(iddobruno);
                                $(this).find("Manufacturer").each(function () {
                                    $(this).find("manufactor").each(function () {
                                        var mid = $(this).attr("id").toUpperCase();
                                        $("select[name=manufacturer] option[value=" + mid + "]").attr('selected', 'selected');
                                        $("select[name=manufacturer]").attr("disabled", "");
                                        // show appropriate models
                                        $("select[name=model] option[ass=" + mid + "]").show();
                                    });
                                });

                                $(this).find("Model").each(function () {
                                    $(this).find("model").each(function () {
                                        var mid = $(this).attr("id").toUpperCase();
                                        $("select[name=model] option[value=" + mid + "]").attr('selected', 'selected');
                                        $("select[name=model]").attr("disabled", "");
                                    });
                                });
                                $("input[name=uniqueidvalidation]").attr("value", "1");
                                $("div[htmlfor=uniqueidvalidation]").text("Unique ID Valid"); // TODO: Fix hard-coded string...
                                $("div[htmlfor=uniqueidvalidation]").css("color", "green");
                                //$("select").css({"border":"1px solid #000","backgroundColor":"#ece9d8"})
                                //$("#deviceId").val(deviceId);
                                //$(".deviceRowDeviceId").show();
                            }
                        });
                    }
                });
            }
        });

    }

    // ******************************* /Register Device ******************************* //




    // ******************************* Register and Edit Device ******************************* //

    if ($("#page_id").text() == "Register Device" || $("#page_id").text() == "Edit Device") {

        //tooltip para o icon INFO
        $(".deviceRow a").mouseover(function () {
            $(".boxes2 .replace_content").empty();
            $(".boxes2 .replace_content").html($(this).attr("info"));
            $(".boxes2").show();
        }).mousemove(function (e) {
            $(".boxes2").css("left", (e.pageX) + 10)
					    .css("top", (e.pageY - $(".boxes2").height() - 5));
        }).mouseout(function () {
            $(".boxes2").hide();
        });

        $("input[type=checkbox]").attr("checked", false);

        $("#checkpin").click(function () {
            $("#pin").toggle("fast");
        })

        $("#checkadultpin").click(function () {
            $("#adultpin").toggle("fast");
        })

        $("select[name=manufacturer]").change(function () {
            $("select[name=model] option").hide();
            $("select[name=model] option[ass=" + $(this).val() + "]").show().attr('selected', 'selected');
        });

    }

    // **************************** /Register and Edit Device **************************** //




    // ******************************* Edit Device ******************************* //

    if ($("#page_id").text() == "Edit Device") {

        /*$("#uniqueId").val($.getURLParam("uniqueId"));

        $.ajax({
        type: "GET",
        url: "GetModels.aspx",
        dataType: "xml",
        success: function(xml){
        $(xml).find("ModelInfo").each(function(){
        if ($(this).attr("result")!="Ok") {
        window.location.href = 'Error.aspx?type=GeneralError';
        } else {
        $(this).find("manufacturer").each(function(){
        id_ma = $(this).attr("id");
        name_ma = $(this).attr("name");
        $("select[name=manufacturer]").append('<option value="'+id_ma+'">'+name_ma+'</option>');
        $(this).find("model").each(function(){
        id_mo = $(this).attr("id");
        name_mo = $(this).attr("name");
        $("select[name=model]").append('<option style="display:none" ass="'+id_ma+'" value="'+id_mo+'">'+name_mo+'</option>');
        });
        });
        $.ajax({
        url: "MyDevice.aspx",
        dataType: "xml",
        type:"POST",
        data:{uniqueid: $.getURLParam("uniqueId"), ShowAll: true},
        success: function(xml){
        $(xml).find("DeviceInfo").each(function(){
        if ($(this).attr("result")!="Ok") {
        alert("I see what you did there!");
        } else {
        iddobruno=$(this).find("ID").text();
        deviceId=$(this).find("MacAddress").text();
        $("#iddobruno").val(iddobruno);
        $(this).find("Manufacturer").each(function(){
        $(this).find("manufactor").each(function(){
        $("select[name=manufacturer] option[value="+$(this).attr("id")+"]").attr('selected', 'selected');
        });
        });
        $(this).find("Model").each(function(){
        $(this).find("model").each(function(){
        $("select[name=model] option[value="+$(this).attr("id")+"]").attr('selected', 'selected');
        });
        });
        $("#deviceId").val(deviceId);
        $(".deviceRowDeviceId").show();
        }
        });
        }
        });
        }
        });
        }
        });*/

    }

    // **************************** /Edit Device **************************** //



    // This is to avoid the user to see a disformated page at first
    if ($("#page_id").text() != "Login") {
        $("#wrap").fadeIn(300);
        $(".footer").fadeIn(300);
    }

});

// handles all the user interface rules of the Header
function Header_RefreshGUI(username) {
    // Login Area
    // if username is suplied then log-in call was made externaly
    if (username != "") {
        $(".username span").text(buy_username);
        $(".username span").show();
        $(".username a").remove();
        $(".username").append('<a id="logout">Logout</a>');
        if ($('.accountBalance').length == 0) {
            $(".username").append('<div class="accountBalance">&nbsp;</div>');
        } else {
            $('.accountBalance').empty();
        }

        getVouchersSumary();

        userIsAuthenticated = true;
    }

    if (userIsAuthenticated) {
        $("#logout").click(function () {

            $.ajax({
                url: "Logout.aspx",
                success: function () {
                    window.location.href = "Home.aspx";
                },
                error: function () { alert("Error") },
                complete: function () {
                    //alert("Terminado");
                }
            });
        });
    }
}

function Detail_RefreshGUI() {
    if (userIsAuthenticated) {

        $(".detbox_textbox[name=username]").attr("value", $(".login_div .username span").text());
        $(".detbox_textbox[name=username]").attr('disabled', true);

        if (FEATURE_DOUBLECHECK_ONPURCHASE == false) {
            $(".detbox_login_user_div").hide(); // Username Password Div
        }
        $("#AssetDetail_btnCreateAccount").hide(); // Create Account Button
    } else {
        $("#detbox_pay_method").hide();
    }
}

// ***************************** Devices ******************************* //

function regDevice() {

    var deviceId = "";
    var manufacturer = "";
    var model = "";
    var pin = "";
    var adultpin = "";
    var unique_id = "";

    if ($("#iddobruno").val()) {
        deviceId = $("#iddobruno").val();
    }

    if ($("select[name=manufacturer]").val() != "1") {
        manufacturer = $("select[name=manufacturer]").val();
    }

    if ($("select[name=model]").val() != "1") {
        model = $("select[name=model]").val();
    }

    if ($("#pin_input").val()) {
        pin = $("#pin_input").val();
    }

    if ($("#adultpin_input").val()) {
        adultpin = $("#adultpin_input").val();
    }

    if ($("#uniqueId").val()) {
        unique_id = $("#uniqueId").val();
    }


    $.ajax({
        url: "RegDevice.aspx",
        type: "POST",
        data: { deviceId: deviceId, manufacturer: manufacturer, model: model, pin: pin, adultpin: adultpin, unique_id: unique_id },
        success: function (data, textStatus, XMLHttpRequest) {
            if (data != "" && data != undefined) {
                $("#mydown_container").prepend(data);
                $(".mydown_title5").hide();
                $("#martekingCampaign input[type=button]:last").click(function () {
                    window.href.location = "Generic.aspx?type=Myinfo&tab=1";
                });
            } else {
                window.location.href = 'Generic.aspx?type=Myinfo&tab=1';
            }
        },
        complete: function (XMLHttpRequest, textStatus) {
            // workaround for IE bug in this call
            //window.location.href = 'Generic.aspx?type=Myinfo&tab=1';
            //alert("Now you should have been redirected but I'm not allowing! L1426");
        }
    });

}

function removeDevice(deviceId) {
    var result = confirm('Are You sure you want to remove this?');

    if (result) {
        $.ajax({
            type: "POST",
            url: "removedevice.aspx",
            data: { deviceId: deviceId },
            success: function () {
                window.location.reload(true);
            }
        });
    }
}

// **************************** /Devices ******************************* //

// ***************************** Currency ******************************* //

function convertToCurrencySymbol(currencyCode, value) {
    var symbol = "&euro;";
    switch (currencyCode) {
        case 'EUR': symbol = '&euro;'; break;
        case 'GBP': symbol = '&pound;'; break;
        case 'CHF': symbol = ' CHF'; break;
        case 'USD': symbol = '$'; break;
    }
    if (currencyCode == 'CHF') {
        return "" + value + symbol;
    } else {
        return "" + symbol + value;
    }
}

// ***************************** /Currency ******************************* //


// ******************************* GET USER INFO ******************************* //

/*function getUserInfo() {
$.ajax({
type: "GET",
url: "GetUser.aspx",
dataType: "xml",
success: function(xml){
$(xml).find("UserInfo").each(function(){
var email = $(xml).find("Email").text();
if(email=="") email = "dummy";
$(".acc_input[name='email']").attr("value", email);
});
}
});
}*/

// ******************************* /GET USER INFO ******************************* //



// ******************************* LOGIN/LOGOUT ******************************* //

function checkLogin(url) {
    // for legacy reasons - not necessary any longer
    // code moved to server side
    if (url)
        window.location.href = url;
    else
        window.location.href = "Generic.aspx?type=Login"
}

function ajaxLogin(username, password, callbacks) {
    $.ajax({
        url: "Login.aspx",
        type: "GET",
        data: {
            username: username,
            password: password,
            returntype: "SilverlightXml"
        },
        success: function (xml) {
            if ($(xml).find('UserAuthentication').text() == "OK") {
                if (callbacks.success) {
                    callbacks.success();
                }
            } else {
                if (callbacks.failure) {
                    callbacks.failure();
                }
            }
        },
        error: function () {
            if (callbacks.failure) {
                callbacks.failure();
            }
        }
    })
}
function gotoLogin() {

    var btnClass = ".acetrax_btn_bg";
    disableClick(btnClass);

    login_username = $('.sbox_input:eq(0)').val();
    login_password = $('.sbox_input:eq(1)').val();

    $(".signin_box_invalid_login").hide();
    ajaxLogin(
        login_username,
        login_password,
        {
            success: function () {
                var ref = $.getURLParam("Referrer")
                if (ref) {
                    // Manual Referrer
                    window.location.href = unescape($.getURLParam("Referrer"));
                } else if (document.referrer != undefined
                    && document.referrer != ""
                    && document.referrer != document.location.href
                    && document.referrer.indexOf(document.location.href) < 0
                    ) {
                    // Automatic Referrer
                    window.location.href = document.referrer;
                } else {
                    // Default
                    window.location.href = "/";
                }
            },
            failure: function () {
                $(".signin_box_invalid_login").show();
                enableClick(btnClass);
            }
        }
    );

}

// ******************************* /LOGIN/LOGOUT ******************************* //




// ******************************* CREATE ACCOUNT ******************************* //
/* SG - 03/11/2011 made change for email using as username for simplified account creation */
function validateCaptcha() {
    if (!$("input[name=terms]:checked").val()) {
        $("#dvTCError").removeClass("hidden");
        $("#dvTCError").css("display", "block");
        return false;
    }
    else {
        $("#dvTCError").addClass("hidden");
        $("#dvTCError").css("display", "none");
    }
    var uword = hex_md5(document.getElementById(jfldid).value);

    if (uword == cword[anum - 1]) {
        isto = ".acetrax_btn_bg";

        disableClick(isto);

        //$(".capd .error_captcha").css("display", "none");
        $(".capd .caerror_captcha").css("display", "none");
        
        //username = $("input[name=username]").val();
        password = $("input[name=pw1]").val();
        email = $("input[name=mail1]").val();
        pin = $("input[name=pin]").val();
        newsletter = $("input[name=newsletter]:checked").val();
        if (!newsletter) {
            newsletter = 0;
        }
        firstname = email; //SG

        //hide create account button and display loader
        //SG change css class for alignment
        $('.acc_create_btn').css("background", "transparent");
        $('.acc_create_btn').html('<div class="create_account_processing"><img src="/acetrax/system/img/ajax-loader.gif"></div>');

        $('#email1').attr('readonly', true);
        $('#password').attr('readonly', true);
        $('#pintype').attr('readonly', true);
        $('#uword').attr('readonly', true);

        $.ajax({
            url: "CreateUser.aspx",
            type: "POST",
            data: { id: email, passwd: password, email: email, firstname: firstname, newsletter: newsletter },
            success: function () {
                ajaxLogin(
                    email,
                    password,
                    {
                        success: function () {
                            $.ajax({
                                url: "RegDevice.aspx",
                                type: "POST",
                                data: { deviceId: '', manufacturer: '', model: '', pin: pin, adultpin: '', unique_id: '' },
                                success: function (data, textStatus, XMLHttpRequest) {
                                    if (data != "" && data != undefined) {
                                        //$("#mydown_container").prepend(data);
                                        //$(".mydown_title5").hide();
                                        //$("#martekingCampaign input[type=button]:last").click(function () {
                                        //window.href.location = "Generic.aspx?type=Myinfo&tab=1";
										
                                        window.location.href = "/Home.aspx";
                                        //});
                                    } else {
                                        //window.location.href = 'Generic.aspx?type=Myinfo&tab=1';
										
										
										var type = "RegistrationComplete";
											window.location.href = "/Generic.aspx?type="+type;		
                                        //window.location.href = "/Home.aspx";
                                    }
                                },
                                complete: function (XMLHttpRequest, textStatus) {
                                    // workaround for IE bug in this call
                                    //window.location.href = 'Generic.aspx?type=Myinfo&tab=1';
                                    //alert("Now you should have been redirected but I'm not allowing! L1426");
                                }
                            });
                        },
                        failure: function () {
                            //alert("Error");
                            enableClick(isto);
                            $('#email1').attr('readonly', false);
                            $('#password').attr('readonly', false);
                            $('#pintype').attr('readonly', false);
                            $('#uword').attr('readonly', false);
                        }
                    }
                );
            },
                error: function (jqXHR, textStatus, errorThrown) {
                //alert("Error");
                enableClick(isto);
                ajaxLogin(
                    email,
                    password,
                    {
                        success: function () {

                            $.ajax({
                                url: "RegDevice.aspx",
                                type: "POST",
                                data: { deviceId: '', manufacturer: '', model: '', pin: pin, adultpin: '', unique_id: '' },
                                success: function (data, textStatus, XMLHttpRequest) {
                                    if (data != "" && data != undefined) {
                                        //$("#mydown_container").prepend(data);
                                        //$(".mydown_title5").hide();
                                        //$("#martekingCampaign input[type=button]:last").click(function () {
                                        //window.href.location = "Generic.aspx?type=Myinfo&tab=1";
										window.location.href = "/Home.aspx";
                                        //});
                                    } else {
                                        //window.location.href = 'Generic.aspx?type=Myinfo&tab=1';
                                        window.location.href = "/Home.aspx";
                                    }
                                },
                                complete: function (XMLHttpRequest, textStatus) {
                                    // workaround for IE bug in this call
                                    //window.location.href = 'Generic.aspx?type=Myinfo&tab=1';
                                    //alert("Now you should have been redirected but I'm not allowing! L1426");
                                }
                            });
                            //window.location.href = "/";
                        },
                        failure: function () {
                            //alert("Error");
                            enableClick(isto);
                            $('#email1').attr('readonly', false);
                            $('#password').attr('readonly', false);
                            $('#pintype').attr('readonly', false);
                            $('#uword').attr('readonly', false);
                        }
                    }
                );
            },
            complete: function () {
                //alert("Terminado");
            }
        });
        return true;
    } else {
        if ($(".capd div.error").css("display") == "none") {
            $(".capd .caerror_captcha").css("display", "block");
        }
        //alert("ERROR: Enter the code as it is shown.");
        document.getElementById(jfldid).focus();
        return false;
    }
}
function ClearEmail() {
    $(".create_acc_msg_box").html('');
}
//end by sumit
// ******************************* /CREATE ACCOUNT ******************************* //
//Aman code for FB starts
function validateFBRegistration() {
    alert("Inside FB Validate");
    var uword = hex_md5(document.getElementById(jfldid).value);

    if (uword == cword[anum - 1]) {
        isto = ".acetrax_btn_bg";

        disableClick(isto);

        //$(".capd .error_captcha").css("display", "none");
       // $(".capd .caerror_captcha").css("display", "none");

        //username = $("input[name=username]").val();
        password = "123456";
        email = "aman.jha@gmail.com";
        pin = "123456";
        newsletter = $("input[name=newsletter]:checked").val();
        if (!newsletter) {
            newsletter = 0;
        }
        firstname = "Aman"; //SG

        //hide create account button and display loader
        //SG change css class for alignment
        $('.acc_create_btn').css("background", "transparent");
        $('.acc_create_btn').html('<div class="create_account_processing"><img src="/acetrax/system/img/ajax-loader.gif"></div>');

       
        $('#pintype').attr('readonly', true);
        $('#uword').attr('readonly', true);

        $.ajax({
            url: "CreateUser.aspx",
            type: "POST",
            data: { id: email, passwd: password, email: email, firstname: firstname, newsletter: newsletter },
            success: function () {
                ajaxLogin(
                    email,
                    password,
                    {
                        success: function () {
                            $.ajax({
                                url: "RegDevice.aspx",
                                type: "POST",
                                data: { deviceId: '', manufacturer: '', model: '', pin: pin, adultpin: '', unique_id: '' },
                                success: function (data, textStatus, XMLHttpRequest) {
                                    if (data != "" && data != undefined) {
                                        //$("#mydown_container").prepend(data);
                                        //$(".mydown_title5").hide();
                                        //$("#martekingCampaign input[type=button]:last").click(function () {
                                        //window.href.location = "Generic.aspx?type=Myinfo&tab=1";
                                        window.location.href = "/Home.aspx";
                                        //});
                                    } else {
                                        //window.location.href = 'Generic.aspx?type=Myinfo&tab=1';
                                        window.location.href = "/Home.aspx";
                                    }
                                },
                                complete: function (XMLHttpRequest, textStatus) {
                                    // workaround for IE bug in this call
                                    //window.location.href = 'Generic.aspx?type=Myinfo&tab=1';
                                    //alert("Now you should have been redirected but I'm not allowing! L1426");
                                }
                            });
                        },
                        failure: function () {
                            //alert("Error");
                            enableClick(isto);
//                            $('#email1').attr('readonly', false);
//                            $('#password').attr('readonly', false);
                            $('#pintype').attr('readonly', false);
                            $('#uword').attr('readonly', false);
                        }
                    }
                );
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //alert("Error");
                enableClick(isto);
                ajaxLogin(
                    email,
                    password,
                    {
                        success: function () {

                            $.ajax({
                                url: "RegDevice.aspx",
                                type: "POST",
                                data: { deviceId: '', manufacturer: '', model: '', pin: pin, adultpin: '', unique_id: '' },
                                success: function (data, textStatus, XMLHttpRequest) {
                                    if (data != "" && data != undefined) {
                                        //$("#mydown_container").prepend(data);
                                        //$(".mydown_title5").hide();
                                        //$("#martekingCampaign input[type=button]:last").click(function () {
                                        //window.href.location = "Generic.aspx?type=Myinfo&tab=1";
                                        window.location.href = "/Home.aspx";
                                        //});
                                    } else {
                                        //window.location.href = 'Generic.aspx?type=Myinfo&tab=1';
                                        window.location.href = "/Home.aspx";
                                    }
                                },
                                complete: function (XMLHttpRequest, textStatus) {
                                    // workaround for IE bug in this call
                                    //window.location.href = 'Generic.aspx?type=Myinfo&tab=1';
                                    //alert("Now you should have been redirected but I'm not allowing! L1426");
                                }
                            });
                            //window.location.href = "/";
                        },
                        failure: function () {
                            //alert("Error");
                            enableClick(isto);
//                            $('#email1').attr('readonly', false);
//                            $('#password').attr('readonly', false);
                            $('#pintype').attr('readonly', false);
                            $('#uword').attr('readonly', false);
                        }
                    }
                );
            },
            complete: function () {
                //alert("Terminado");
            }
        });
        return true;
    } else {
        
        //alert("ERROR: Enter the code as it is shown.");
        //document.getElementById(jfldid).focus();
        return false;
    }
}



// Aman code for FB ends

// ******************************* DETAILS VOUCHERS ******************************* //

function freeOffer() {
    var price = $("#" + ($(".detbox_radio_buy:checked").val())).val();

    if (parseFloat(price) === 0) {

        $("#detbox_pay_method").hide();
        $("#detbox_vouchers_list").hide()
        // manually force the option selected to voucher
        $(".detbox_radio_pay[value=voucher]").attr("checked", "checked");
        return true;
    } else {
        return false;
    }
}

function initOfferDisplay() {

    var free = freeOffer()

    if (userIsAuthenticated && !free) {
        getDetailsVouchers();
    }

    if (free) {
        $(".detbox_btn input[type=submit]").val($(".detbox_btn > .tryMovie").text());
    } else {
        $(".detbox_btn input[type=submit]").val($(".detbox_btn > .buyMovie").text());
    };
}

function getDetailsVouchers() {

    $("#detbox_pay_method").show();
    //RN-change-added on july24th- only Below If condition

    if (isChangeLanguageCalled == false) {

        type = "";
        if ($("#detbox_vouchers_list").show()) {
            $("#detbox_vouchers_list").empty();
            $("#detbox_vouchers_list").prepend("<img src='/acetrax/system/img/ajax-loader.gif' /><br style='clear:both'/>")
								  .slideDown("slow");

            $.ajax({
                type: "GET",
                url: "GetUserVouchers.aspx?filterByCurrency=true",
                dataType: "xml",
                success: function (xml) {
                    $("#detbox_vouchers_list").empty();
                    $("#detbox_vouchers_list").prepend("<table id='detbox_vouchers_list_box'></table>");

                    var avs = $(".AVSCase").length > 0; //check if its AVS case
                    selectedType = $(".detbox_radio_buy:checked");
                    if (selectedType != null && !avs) {
                        selectedType = selectedType.parent().next().children().attr("id").split("_")[0].toLowerCase(/// <reference path="../../../PaymentPP.aspx" />
);
                    }
                    $(xml).find('voucher').each(function () {
                        var type = $(this).find('type').text();
                        if (type == "") { type = "ALL" }

                        var contentId = $(this).find('contentId').text();
                        var currency = $(this).find('currency').text();
                        var expirationDate = $(this).find('expirationDate').text();
                        var expirationDateFormated = new Date(expirationDate).format(DEFAULT_DATE_FORMAT)
                        var reference = $(this).find('reference').text();
                        var value = $(this).find('value').text();
                        var isTopUp = $(this).find('is_topup').text();

                        var voucherName = varVoucher_voucher;
                        if (isTopUp.toLowerCase() == 'true') {
                            voucherName = varVoucher_myTopUpCredit
                        }
                        if (((selectedType == "rent") && ((type == "ALL") || (type == "VOD"))) || ((selectedType == "buy") && (type == "ALL"))) {
                            //Force round vouchers value
                            value = value.replace(',', '.');
                            value = parseFloat(value).toFixed(2);
                            //Hide vouchers with value = 0
                            if (value > 0) {
                                value = value.replace('.', ',');
                                $("#detbox_vouchers_list_box").append("<tr class='detbox_each_voucher'><td><input type='radio' value='" + contentId + "' name='voucher' /></td><td class='detbox_voucher_value' value='" + value + "'>" + voucherName + " - " + convertToCurrencySymbol(currency, value) + "</td><td>" + varVoucher_expires + " " + expirationDateFormated + "</td></tr>");
                            }
                        }
                    });

                    if (($(xml).find('voucher').size() == 0) || (((selectedType == "rent") && ((type == "ALL") || (type == "VOD"))) || ((selectedType == "buy") && (type == "ALL")))) {
                        $("#detbox_vouchers_list_box").prepend("<tr class='detbox_each_voucher_head'><td colspan='3'>You don't have any vouchers</td></tr>");
                    } else {
                        $("#detbox_vouchers_list_box").prepend("<tr class='detbox_each_voucher_head'><td colspan='3'>" + varVoucher_title + "</td></tr>");
                    }
                    $("#detbox_vouchers_list_box").slideDown("slow");
                    $(".detbox_voucher_value").each(function () {
                        if (parseFloat($(this).attr("value")) >= parseFloat($(".detbox_radio_buy:checked").parent().next().children().children().text())) {
                            $(this).prev().children().attr("checked", "checked");
                            return false;
                        }
                    });
                    $(".detbox_radio_pay[value=voucher]").attr("checked", "checked");
                    var len = $(".detbox_voucher_value").length;
                    var selectedPrice = GetTotalPriceDetail();

                    for (var i = 0; i < len; i++) {
                        if (parseFloat($(".detbox_voucher_value:eq(" + i + ")").attr("value").replace(",", ".")) > selectedPrice) {
                            $(".detbox_voucher_value:eq(" + i + ")").prev().children().attr("checked", "checked");
                            break;
                        }
                        if (i == len - 1)
                        { $(".detbox_voucher_value:eq(0)").prev().children().attr("checked", "checked"); }
                    }
                    //  $(".detbox_voucher_value:eq(0)").prev().children().attr("checked", "checked");
                }
            });
        }

        //RN -Change below bracket ends
    }
}

function GetTotalPriceDetail() {
    var selectedPrice;
    if (!isSeasonAsset)
    { selectedPrice = parseFloat($(".detbox_radio_buy:checked").parent().next().children().children().text().replace(",", ".")) }
    else
    { selectedPrice = parseFloat($(".detbox_radio_buy:checked").next().val().replace(",", ".")); }
    return selectedPrice;
}

// ******************************* /DETAILS VOUCHERS ******************************* //

// ******************************* VOUCHERS SUMMARY ******************************* //

function getVouchersSumary() {
    i = 0;
    var total_balance = 0;
    var mycurrency = "";
    var placeHolderName = ".accountBalance"

    $(placeHolderName).empty();
    $(placeHolderName).fadeOut("fast");

    $.ajax({
        type: "POST",
        url: "GetUserVouchers.aspx?filterByCurrency=true",
        dataType: "xml",
        data: { allvouchers: 1 },
        success: function (xml) {
            mycurrency = $(xml).find('UserPaymentMethods').attr('currency');
            if (mycurrency == undefined)
                mycurrency = "GBP";
            $(xml).find('voucher').each(function () {
                var contentId = $(this).find('contentId').text();
                var currency = $(this).find('currency').text();
                var expirationDate = $(this).find('expirationDate').text();
                var expirationDateFormated = new Date(expirationDate).format(DEFAULT_DATE_FORMAT)
                var reference = $(this).find('reference').text();
                var value = $(this).find('value').text();
                // convert to number
                value = parseFloat(value) ? parseFloat(value).toFixed(2) : "0.00";
                var state = $(this).find('state').text();
                var type = $(this).find('type').text();
                if (type == "") { type = "ALL"; }

                value = value.replace(",", ".");
                if (state == "new") {
                    total_balance += parseFloat(value);
                }

                i = i + 1;
            });
            //varVoucher_balance + ": " +
            $(placeHolderName).append(Label_MyAccountSumary + ": " + convertToCurrencySymbol(mycurrency, total_balance.toFixed(2)) + "");
            $(placeHolderName).fadeIn("slow");
        }
    });
}

// ******************************* VOUCHERS SUMMARY ******************************* //


// ******************************* GET YOUR VOUCHERS ******************************* //

function getYourVouchers() {
    i = 0;
    var total_balance = 0;
    $(".voucher_exmp_box table").empty();
    var mycurrency = "";
    $.ajax({
        type: "POST",
        url: "GetUserVouchers.aspx?filterByCurrency=true",
        dataType: "xml",
        data: { allvouchers: 1 },
        success: function (xml) {
            mycurrency = $(xml).find('UserPaymentMethods').attr('currency');
            if (mycurrency == undefined)
                mycurrency = "GBP";
            $(xml).find('voucher').each(function () {
                var contentId = $(this).find('contentId').text();
                var currency = $(this).find('currency').text();
                var expirationDate = $(this).find('expirationDate').text();
                var expirationDateFormated = new Date(expirationDate).format(DEFAULT_DATE_FORMAT)
                var reference = $(this).find('reference').text();
                var value = $(this).find('value').text();
                var isTopUp = $(this).find('is_topup').text();
                // convert to number
                value = parseFloat(value) ? parseFloat(value).toFixed(2) : "0.00";
                var state = $(this).find('state').text();
                var type = $(this).find('type').text();
                if (type == "") { type = "ALL"; }

                value = value.replace(",", ".");
                if (state == "new") {
                    total_balance += parseFloat(value);
                }
                if (isTopUp.toLowerCase() != 'true') {
                    $(".voucher_exmp_box table").append("<tr class='" + state.toLowerCase() + " " + type.toUpperCase() + "'><td>" + varVoucher_voucher + " " + convertToCurrencySymbol(currency, value) + "</td><td>" + varVoucher_expires + " " + expirationDateFormated + "</td></tr>");
                } else {
                    $(".voucher_exmp_box table").append("<tr class='" + state.toLowerCase() + " " + type.toUpperCase() + "'><td>" + varVoucher_myTopUpCredit + " " + convertToCurrencySymbol(currency, value) + "</td><td>" + varVoucher_expires + " " + expirationDateFormated + "</td></tr>");
                }
                i = i + 1;
            });

            //retrieving the EasyCollect fag
            var hasEasyCollect;
            hasEasyCollect = $(xml).find('HasEasyCollect').text();
            $("#hasEasyCollect").val(hasEasyCollect);

            // fillTopUpValues(xml);
            var selTopUpValues = $('#TopUpValues');
            //            selTopUpValues.empty();
            //            $('<option/>').attr('value', '').text('Choose recharge amount').appendTo(selTopUpValues);

            var topUpRechargeCurrency;
            $(xml).find('TopUpValue').sort(
		            function (a, b) {
		                var vala = parseFloat($(a).text())
		                var valb = parseFloat($(b).text())
		                vala = vala ? vala : 0;
		                valb = valb ? valb : 0;
		                return vala - valb;
		            }
	            ).each(function () {
	                $('<option/>').attr('value', $(this).text()).text($(this).text() + ' ' + $(this).attr('currency')).appendTo(selTopUpValues);
	                topUpRechargeCurrency = $(this).attr('currency');
	            });
            dropVouchers(); //hide expired 

            $("#topUpRechargeCurrency").val(topUpRechargeCurrency);

            $(".voucher_exmp_box table").prepend("<tr class='detbox_each_voucher_head'><td colspan='2'>" + varVoucher_title + "</td></tr>");
            $(".voucher_exmp_box table").append("<tr class='detbox_each_voucher_foot'><td colspan='2'>" +
                varVoucher_balance + ": " + convertToCurrencySymbol(mycurrency, total_balance.toFixed(2)) + "</td></tr>");
            $(".voucher_exmp_box table").append('<tr><td colspan="2"><input mossdeb="consumed" id="show_inactive_vouchers" type="checkbox" onclick="dropVouchers()" /><label for="show_inactive_vouchers" class="show_inactive_vouchersTXT">' + varVoucher_showConsumed + '</label></td></tr>');
            $(".voucher_exmp_box table").append('<tr><td colspan="2"><input mossdeb="VOD" id="show_only_vod" type="checkbox" onclick="dropVouchers()" /><label for="show_only_vod" class="show_inactive_vouchersTXT">' + varVoucher_showVoD + '</label></td></tr>');
            $(".voucher_exmp_box table").fadeIn("slow");
        }
    });
}

function dropVouchers() {

    a = $(".show_inactive_vouchersTXT:eq(0)").prev().is(":checked")
    b = $(".show_inactive_vouchersTXT:eq(1)").prev().is(":checked")

    $(".ALL").css("display", "none");
    $(".VOD").css("display", "none");

    if (a && b) {
        $(".new.VOD").css("display", "table-row");
        $(".consumed.VOD").css("display", "table-row");
    } else if (!a && !b) {
        $(".new.ALL").css("display", "table-row");
        $(".new.VOD").css("display", "table-row");
    } else if (!a && b) {
        $(".new.VOD").css("display", "table-row");
    } else if (a && !b) {
        $(".new.ALL").css("display", "table-row");
        $(".new.VOD").css("display", "table-row");
        $(".consumed.ALL").css("display", "table-row");
        $(".consumed.VOD").css("display", "table-row");
    }
}

// ******************************* /GET YOUR VOUCHERS ******************************* //




// ******************************* EDIT ACCOUNT ******************************* //

function editAccount() {

    edit_mail = $("#mail1").val();
    edit_oldpass = $(".acc_input[name=pw]").val();
    edit_newpass = $(".acc_input[name=new_pw]").val();
    var uword = hex_md5(document.getElementById(jfldid).value);
    isto = ".bt_editacc";


    disableClick(isto);

    if (uword == cword[anum - 1]) {

        $.ajax({
            url: "EditUser.aspx",
            type: "POST",
            data: { passwd: edit_oldpass, newpasswd: edit_newpass, email: edit_mail },
            success: function () {
                $(".mydown_editConfirmation").fadeIn("slow");
            },
            error: function () {
                alert("Probably the password is wrong");
                enableClick(isto);
            },
            complete: function () {
                //alert("Terminado");
            }
        });
    }
}

function editAccountAdult() {
    edit_newpass = $(".acc_input[name=new_apw]").val();
    edit_newpin = $(".acc_input[name=new_apin]").val();
    isto = ".bt_editacc";

    disableClick(isto);


    $.ajax({
        url: "EditUserDetails.aspx?action=edit",
        type: "POST",
        data: { "Adult Password": edit_newpass, "UserAdultPIN": edit_newpin },
        success: function () {
            $(".mydown_editConfirmation").fadeIn("slow");
        },
        error: function () {
            alert("Probably the password is wrong");
            enableClick(isto);
        },
        complete: function () {
            //alert("Terminado");
        }
    });
}
// ******************************* /EDIT ACCOUNT ******************************* //




// ******************************* BOXSET DETAILS ******************************* //

function avsCheck(contentId, actionId, successCallback) {
    $.ajax({
        url: "avscheck.aspx",
        type: "POST",
        dataType: "json",
        data: {
            contentId: contentId,
            actionId: actionId
        },
        success: function (data) {
            // only one action should be returned
            var actionResult = data.Actions[0];
            // 0 = Ok, 
            if (actionResult.Action == actionId && actionResult.Result === 0) {
                if (successCallback !== undefined && successCallback !== null && typeof (successCallback) === 'function') {
                    successCallback();
                }
            } else if (actionResult.Action == actionId &&
                       actionResult.Result === 2 &&
                       actionResult.DeniedURL.length > 0) {

                document.location = actionResult.DeniedURL;

            } else {

                document.location = actionResult.URL;

            }
        }
    });
}


function avsMyAccountAdult(callback) {
    $.ajax({
        url: "avsmyaccountadult.aspx",
        type: "POST",
        dataType: "json",
        success: function (data) {
            // 0 = Ok,
            if (data.Result === 0) {
                if (callback !== undefined && callback !== null && typeof (callback) === 'function') {
                    callback();
                }
            } else {
                document.location = data.URL;
            }
        }
    });
}

function submitPurchase(offerId, currency, totalPrice, voucherId, varProcessing, varError) {
    $(".detbox_btn").empty();
    $(".detbox_btn").append("<div class='detbox_processing'>" + varProcessing + "</div>");

    var contentId = $(this).find('contentId').text();
    if (contentId == "") contentId = $.getURLParam("contentID");

    avsCheck(contentId, AVS_PURCHASEMOVIE, function () {
        $.ajax({
            url: "EditCart.aspx",
            type: "POST",
            data: { currency: currency, catalog: "A", offerId: offerId, action: "add", resetcart: "true" },
            success: function () {
                switch ($(".detbox_radio_pay:checked").val()) {
                    case "clickbuy":
                        window.location.href = "PaymentCB.aspx?currency=" + currency + "&catalog=A&totalPrice=" + totalPrice;
                        break
                    case "paypal":
                        window.location.href = "PaymentPP.aspx?currency=" + currency + "&catalog=A&totalPrice=" + totalPrice;
                        break
                    case "voucher":
                        if (!$("#detbox_vouchers_list_box input:checked").val()) {
                            if (!freeOffer()) {
                                $(".detbox_each_voucher_head td").css("color", "red");
                                enableClick(isto);
                            } else
                                window.location.href = "PaymentVoucher.aspx?currency=" + currency + "&catalog=A&totalPrice=" + totalPrice + "&voucherId=" + voucherId;
                        } else {
                            window.location.href = "PaymentVoucher.aspx?currency=" + currency + "&catalog=A&totalPrice=" + totalPrice + "&voucherId=" + voucherId;
                        }
                        break
                }
            },
            error: function (req, error, ex) {
                $(".detbox_btn").empty();
                $(".detbox_btn").append("<div class='detbox_error'>" + varError + "</div>");
            },
            complete: function () {
                //alert("Terminado");
            }
        });
    });
}

function onlyEpisodesAreBuyable() {

    selectedEp = 0;
    $(".detbox_selected").each(function () {
        if ($(this).css("display") == "block") {
            selectedEp = 1;
            return false
        } else {
            selectedEp = 0;
        }
    })

    if (selectedEp == 0) {
        /*$(".detbox_right_title").animate({
        opacity: 0
        }, 250).slideUp({},250);*/
        /*$(".detbox_price_box").animate({ 
        opacity: 0
        }, 500, function () {
        $(".detbox_price_box input").attr("checked",false);
        });*/

    } else {

        /*$(".detbox_right_title").slideDown({},250).animate({
        opacity: 1
        }, 250);*/
        $(".detbox_price_box").animate({
            opacity: 1
        }, 500);
        if ($(".login_div .username span").css("display") != "none")
            getDetailsVouchers();

    }
}

// ******************************* /BOXSET DETAILS ******************************* //



// ******************************* AVOID DOUBLE CLICK ******************************* //

var clicks = 1;

function enableClick(isto) {
    //$(".WOOOT").text(clicks+" - clicks --- ENABLE");
    //clicks = clicks + 1;
    $(isto).parent().children(".disable_btn").remove();
}

function disableClick(isto) {
    //$(".WOOOT").text(clicks+" - clicks --- DISABLE");
    $(isto).parent().css("position", "relative");
    //$(isto).parent().append("<div class='disable_btn'><img src='acetrax/system/img/loading/loading53.gif' /></div>");
    $(isto).parent().children(".disable_btn").width($(isto).parent().width());
    $(isto).parent().children(".disable_btn").height($(isto).parent().height());
}

// ******************************* /AVOID DOUBLE CLICK ******************************* //


function closeTooltp() {
    $(".mymovies_ajax_dummy").text(0);
    $(".boxes").hide();
    $(".coverall").hide();
}

// ******************************* /AVOID DOUBLE CLICK ******************************* //

// ******************************* /TOP  UP ACCOUNT  ******************************* //

function Recharge() {

    $(".creditUpdated").hide();

    // var paymentValue = document.getElementById('value').value;
    var paymentValue = $('#TopUpValues').val();
    var paymentCurrency = $('#topUpRechargeCurrency').val();
    var purchaseDesc = $('#topUpPurchaseDesc').val();
    var paymentType = null;

    if (isNaN(paymentValue))
        paymentValue = '';

    for (var i = 0; i < document.accountUp.paymentType.length; i++) {
        if (document.accountUp.paymentType[i].checked)
            paymentType = document.accountUp.paymentType[i].value;
    }

    if (paymentValue == '' || paymentType == '' || paymentType == null || paymentType == 'undefined') {
        $(".creditUpdated").hide().slideDown("slow");
        $(".creditUpdated").show().slideDown("slow");
    }
    else {
        if (paymentType == 'CBTU' && document.getElementById('hasEasyCollect').value == 'true')
            paymentType = 'CBEC';

        window.location.href = "TopActRecharge.aspx?provider=" + paymentType + "&currency=" + paymentCurrency + "&price=" + paymentValue + "&purchaseDesc=" + purchaseDesc;
    }
}


function ajaxPostToContactCustomerCare() {

    //$("#contactUsSubmitBtn").parent().html('<img src="acetrax/system/img/ajax-loader.gif" />');
    $("#contactUsSubmitBtn").parent().hide();
    $("#loaderIcon").show();

    $.ajax({
        type: "POST",
        url: "ContactCustomerCare.aspx",
        data: { emailadress: $("#emailadress").val(), username: $("#username").val(),
            movietitle: $("#movietitle").val(), opsystem: $("#opsystem").val(),
            browser: $("#browser").val(), description: $("#description").val()
        },
        async: true,

        success: function (data, textStatus, XMLHttpRequest) {
            if (data != "" && data != undefined) {
                //alert(data);

                var result = eval('(' + data + ')');
                var errorCode = result.response.errorCode;

                var userName = escape($('#username').val());
                var emailAdress = escape($('#emailadress').val());
                var movieTitle = escape($('#movietitle').val());
                var os = escape($('#opsystem').val());
                var browser = escape($('#browser').val());
                var description = escape($('#description').val());

                $("#contactUsForm").hide();

                if (errorCode != '0') {
                    //alert("vou mandar mail");
                    document.location = 'mailto:cc_support@acetrax.com?subject=Contact%20from%20User%20' + userName + '&body=mail: ' + emailAdress + '%0A%0aMovie Title: ' + movieTitle + '%0A%0aOperation System: ' + os + '%0A%0aBrowser: ' + browser + '%0A%0aDescription:%0A%0a' + description + '%0A%0a';

                    $("#contactUsErrorDiv").show();
                }
                else {
                    $("#contactUsOkDiv").show();
                }


            } else {
                document.location = 'mailto:cc_support@acetrax.com?subject=Contact%20from%20User%20' + userName + '&body=mail: ' + emailAdress + '%0A%0aMovie Title: ' + movieTitle + '%0A%0aOperation System: ' + os + '%0A%0aBrowser: ' + browser + '%0A%0aDescription:%0A%0a' + description + '%0A%0a';
                $("#contactUsErrorDiv").show();
            }
        },

        error: function () {
            $("#contactUsForm").hide();
            $("#contactUsErrorDiv").show();
            document.location = 'mailto:cc_support@acetrax.com?subject=Contact%20from%20User%20' + userName + '&body=mail: ' + emailAdress + '%0A%0aMovie Title: ' + movieTitle + '%0A%0aOperation System: ' + os + '%0A%0aBrowser: ' + browser + '%0A%0aDescription:%0A%0a' + description + '%0A%0a';
        }

    });
}

function addContactCustomerCareFormValidator() {

    $("#contactUs").validate({
        rules: {
            emailadress: { required: true, email: true },
            username: { required: true },
            description: { required: true }
        },
        messages: {
            emailadress: {
                required: $("#missingEmail").html(),
                email: $("#invalidEmail").html()
            },
            username: {
                required: $("#missingUser").html()
            },
            description: {
                required: $("#missingDesc").html()
            }
        },
        submitHandler: function () {
            ajaxPostToContactCustomerCare();
        }

    });

}

/*Salil
Category browsing sorting feature
Jira Id: AT-937 
Done on: 13-06-2011 Start*/
function sortXML() {
    var queryparams = '';
    var redirecturl = document.location.href.substring(0, document.location.href.indexOf('false') + 5);
    if (order != '') {
        queryparams = queryparams + '&order=' + order;
    }
    if (sort != '')
        queryparams = queryparams + '&sort=' + sort;
    if (filter != '')
        queryparams = queryparams + '&filter=' + filter;
    redirecturl = redirecturl + queryparams;
    //$(location).attr('href', redirecturl);
    document.location.replace(redirecturl + '&pos=0');
    /*debugger;
    var filterradio = $('#chkRent').get(0);
    var filter = '';
    if (filterradio.checked)
    filter = filterradio.value;
    else
    filter = '';
    sortData(sort, order, filter);*/
}

function filteroffer() {
    var queryparams = '';
    var redirecturl = '';
    if (document.location.href.indexOf('mo=false') > 0)
        redirecturl = document.location.href.substring(0, document.location.href.indexOf('mo=false') + 8);
    else if (document.location.href.indexOf('mo=true') > 0)
        redirecturl = document.location.href.substring(0, document.location.href.indexOf('mo=true') + 7);
    else
        redirecturl = document.location.href;
    if (order != '') {
        var orderVal = $.getURLParam('order');
        if (orderVal != null)
            redirecturl = redirecturl.replace('order=' + orderVal, 'order=' + order);
        else
            queryparams = queryparams + '&order=' + order;
    }
    if (sort != '') {
        var sortVal = $.getURLParam('sort');
        if (sortVal != null)
            redirecturl = redirecturl.replace('sort=' + sortVal, 'sort=' + sort);
        else
            queryparams = queryparams + '&sort=' + sort;
    }
    if (offer != '') {
        var loc = $.getURLParam('mo');
        if (loc != null)
            redirecturl = redirecturl.replace('mo=' + loc, 'mo=' + offer);
        else
            redirecturl = redirecturl + '&mo=' + offer;
    }
    if (filter != '') {
        queryparams = queryparams + '&filter=' + filter;
    }
    redirecturl = redirecturl + queryparams;
    //$(location).attr('href', redirecturl);
    var posVal = $.getURLParam('pos');
    if (posVal!=null) {
        redirecturl = redirecturl.replace('pos=' + posVal, 'pos=0');
        document.location.replace(redirecturl);
    }
    else {
        document.location.replace(redirecturl + '&pos=0');
    }
    /*debugger;
    var filterradio = $('#chkRent').get(0);
    var filter = '';
    if (filterradio.checked)
    filter = filterradio.value;
    else
    filter = '';
    sortData(sort, order, filter);*/
}

function setParam(el, containerid) {
    switch (containerid) {
        case 'dvPurchaseType':
            filter = el.value;
            break;

        case 'dvMovieDetails':
            sort = el.value;
            break;

        case 'dvOrder':
            order = el.value;
            break;

        case 'dvOfferType':
            offer = el.value;
            break;
    }
}


/*function setColor(link, classname) {
$('.' + classname).each(function () { $(this).css('color', '#CFCFCF'); });
$(link).css('color', '#920101');
}

function getQuerystring(key, default_) {
if (default_ == null) default_ = "";
key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
var qs = regex.exec(window.location.href);
if (qs == null)
return default_;
else
return qs[1];
}

function sortData(sort, order, filter) {
$('.pagination_bottom_category').show();
var copyParent = dManager.getData();
if (filter != '')
arEl = $('.retailAsset_tab_1 div[id*="' + filter + '"]');
else {
arEl = $('.retailAsset_tab_1 .list_new_hover');
}
if (arEl.length > 0) {
if (sort == 'title')
arEl.sort(sortElTitle);
else if (sort == 'date')
arEl.sort(sortEl);
$('.retailAsset_tab_1').empty();
$(arEl).each(function () { $('.retailAsset_tab_1').append(this); });
$('.retailAsset_tab_1').append('<br clear="left"/>');
}
else {
var el = $('.retailAsset_tab_1');
el.empty();
el.removeClass('retailAsset_tab_1');
el.addClass('no_rentalmovies');
el.append('<span>Sorry, no rental movies found.</span>');
$('.pagination_bottom_category').hide();
}
}

function sortEl(el1, el2) {
var date1 = $(el1).find('div.list_new_box').attr('id');
var date2 = $(el2).find('div.list_new_box').attr('id');
if (order == 'asc')
return parseInt(date1 != '' ? date1 : '0') - parseInt(date2 != '' ? date2 : '0');
else if (order == 'desc')
return parseInt(date2 != '' ? date2 : '0') - parseInt(date1 != '' ? date1 : '0');

}

function sortElTitle(el1, el2) {
var title1 = $(el1).find('span.topsMovieTitle').html().toLowerCase();
var title2 = $(el2).find('span.topsMovieTitle').html().toLowerCase();
if (order == 'desc') {
return (title2 > title1 ? 1 : -1);
}
else if (order == 'asc') {
return (title1 > title2 ? 1 : -1);
}
}*/

function refreshLinks() {
    $('.sort1').each(function () { $(this).css('color', '#CFCFCF'); });
}

/*Salil
Category browsing sorting feature
Jira Id: AT-937 
Done on: 13-06-2011 End*/

/*
RN- Rajiv
Change Language Feature
Jira Id:AT-944
Done on: 24-06-2011
Start*/
function GetDefaultRadioSelectedAccToLanguage(lang) {
    var span = '';
    if (lang == "German") {

        lang = "DE";

    }
    $('#spnLangCode', document).each(function () {
        var html = new String($(this).html());

        if (iFlag == false) {
            if ($(this).html().indexOf(lang.toUpperCase().substring(0, 2)) > 0) {
                if (lang != 'DE') {
                    //chRadioLanguage = $('input[type="radio"]', $(this).parent().parent().siblings());
                    //chRadioLanguageValue = $('input[type="radio"]', $(this).parent().parent().siblings()).val();
                    chRadioLanguage = $('input[type="radio"]', $(this).parent().parent().prev());
                    chRadioLanguageValue = $('input[type="radio"]', $(this).parent().parent().prev()).val();
                }
                else {
                    /*chRadioLanguage = $('input[type="radio"]', $(this).parent().parent().siblings()[2]);
                    chRadioLanguageValue = $('input[type="radio"]', $(this).parent().parent().siblings()[2]).val();*/
                    chRadioLanguage = $('input[type="radio"]', $(this).parent().parent().prev());
                    chRadioLanguageValue = $('input[type="radio"]', $(this).parent().parent().prev()).val();
                }
            }
        }
    });
}
/*
Rajiv
Change Language Feature
Jira Id:AT-944
Done on: 24-06-2011
End*/


