// Constants
FEATURE_DOUBLECHECK_ONPURCHASE = false;
DEFAULT_DATE_FORMAT = "dd mmm yyyy";

// Global Variables
userIsAuthenticated = false;
isSeasonAsset = false;

AVS_WATCHMOVIE = 1
AVS_PURCHASEMOVIE = 2

/* Formating date in javascript implementation*/

var gsMonthNames = new Array(
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
);
var varxml = null;
var gsDayNames = new Array(
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
);


Date.prototype.format = function (f) {
    if (!this.valueOf())
        return ' ';

    var d = this;

    return f.replace(/(yyyy|mmmm|mmm|mm|dddd|ddd|dd|hh|nn|ss|a\/p)/gi,
        function ($1) {
            switch ($1.toLowerCase()) {
                case 'yyyy': return d.getFullYear();
                case 'mmmm': return gsMonthNames[d.getMonth()];
                case 'mmm': return gsMonthNames[d.getMonth()].substr(0, 3);
                case 'mm': return (d.getMonth() + 1);
                case 'dddd': return gsDayNames[d.getDay()];
                case 'ddd': return gsDayNames[d.getDay()].substr(0, 3);
                case 'dd': return d.getDate();
                case 'hh': return ((h = d.getHours() % 12) ? h : 12);
                case 'nn': return d.getMinutes();
                case 'ss': return d.getSeconds();
                case 'a/p': return d.getHours() < 12 ? 'a' : 'p';
            }
        }
    );
}

/* Formating date in javascript implementation*/


$(document).ready(function () {

    //$("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) {
        //deles 2                          
        case "eded5ec1-cf91-4c2c-a6c2-8e87dfa8a258": // Home		
            $("#nav li#nav-01 a").addClass("active");
        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 "9a591e65-86d9-42fc-ba96-a558e162de8f": //Browse
            $("#nav li#nav-02 a").addClass("active");
            $("#page_id").text("Browse");
            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 "70699ddc-3c56-41c2-99e1-12dfd212b74e": //Voucher
            $("#nav li#nav-05 a").addClass("active");
            $("#page_id").text("Voucher");
            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 "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 "412b117a-b245-4f91-a89b-bfdaaf81338c": //Category Browsing
            $("#nav li#nav-02 a").addClass("active");
            $("#page_id").text("Category Browsing");
            break
        case "aea39bf0-34ef-4fcd-b80e-144d0b0b62e8": //My Account and My Devices
            if ($.getURLParam("tab") == "0" || $.getURLParam("tab") == "3" || $.getURLParam("tab") == '') {
                $("#nav li#nav-06 a:eq(0)").addClass("active");
                $("#page_id").text("My Account");
            } else if ($.getURLParam("tab") == "1") {
                $("#nav li#nav-04 a:eq(0)").addClass("active");
                $("#page_id").text("My Devices");
            } else if ($.getURLParam("tab") == "2") {
                $("#nav li#nav-07 a:eq(0)").addClass("active");
                $("#page_id").text("Top-Up Credit");
            }
            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
        case "533EB752-70E6-4AAA-A539-6C2980559948": //Samsung Revamp contact us page validations
            //$("#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');
    });
    });*/

    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();
    });


    // <!-- ===== Movie Download overlay UI========= -->
    //tooltip quando download
    //$(".button-download a").click(function () {
    /* function MyMoviesDownload(purchaseID, channelID, contentID, assetID) {
    //window.download_PID = $(this).attr("pid");
    //window.download_COID = $(this).attr("coid");
    //window.download_CHID = $(this).attr("chid");
    //window.download_AID = $(this).attr("aid");

    window.download_PID = purchaseID;
    window.download_COID = channelID;
    window.download_CHID = contentID;
    window.download_AID = assetID;

    $(".mymovies_ajax_dummy").text(1);
    avsCheck(window.download_COID, AVS_WATCHMOVIE, function () {
    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: window.download_AID },
    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" />');
    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="bg_btn" 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();
    })
    // < ! --===== END : Movie Download overlay UI========= //-->

    // /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" || $("#page_type").text() == "CategoryBrowsing") {
        $("#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();
    }

    /******************** Samsung Revamp Logic: To Display "Popular Movies" list above "All Movies" list *********************/
    tabAllMoviesContent = $("#CategoryAllMovies").html();
    $("#CategoryAllMovies").remove();
    tabPopularMoviesContent = $("#CategoryPopularMovies").html();
    $("#CategoryPopularMovies").remove();
    $("#CategoryContent").html(tabPopularMoviesContent + tabAllMoviesContent);


    // ******************************* /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 ******************************* //


    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();
            }
        });

        //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()) {
                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();
                    });
                }
                $(".detbox_btn input[type=submit]").val($(".detbox_btn > .buyMovie").text());
            } else
                $(".detbox_btn input[type=submit]").val($(".detbox_btn > .tryMovie").text());
        });


        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') {
                            if (typeof ($("input[name='voucher']:checked").val()) != 'undefined')
                                itsPayTime();
                            else {
                                if (!freeOffer())
                                    $(".detbox_each_voucher_head > td:first").addClass('detbox_error');
                                else
                                    itsPayTime();
                            }
                        } else
                            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_type").text().toUpperCase() == "LOGIN") {
        $("#wrap").fadeIn(300);
        $(".footer").fadeIn(300);
        //Not-working $(".sbox_input[name=pw]").focus();
		//Set focus on UserName field
		$("#pw").focus();
    }



    // ******************************* /LOGIN/LOGOUT ******************************* //




    // ******************************* CONTACT US ****************************** //

    if ($("#page_id").text() == "Contact Us" || $("#page_type").text() == "ContactUs") {

        //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);

        addContactCustomerCareFormValidator();
    }

    // ******************************* /CONTACT US ****************************** //



    // ******************************* CREATE ACCOUNT ****************************** //

    if ($("#page_id").text() == "CreateAccount") {

        //Trigger checknames funcionality
        $(".create_acc_box_form_line input[name='username']").blur(function () {
            $(".create_acc_msg_box").addClass('hidden');
            var usernameToCheck = $(this).val();
            if (usernameToCheck.length > 3) {
                $(".create_acc_check_name").removeClass('hidden');
                $.ajax({
                    url: "CheckNames.aspx",
                    type: "POST",
                    dataType: "json",
                    data: { username: usernameToCheck },
                    success: function (resp) {
                        $(".create_acc_check_name").addClass('hidden');
                        if (resp.result == "ok") {
                            $(".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 == "exists") {
                            $(".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").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").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").addClass('detbox_error');
                            $("input[name='userValidation']").val('');
                        }
                    },
                    error: function () {
                        $(".create_acc_check_name").addClass('hidden');
                        $(".create_acc_msg_box").html(varError_user);
                        $("input[name='userValidation']").val('');
                    },
                    complete: function () {
                        $(".create_acc_msg_box").removeClass('hidden');
                    }
                });
            }
        });
        $(".create_acc_box_form_line input[name='username']").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
        $('.acetrax_btn_create_account input').mousedown(function () {
            var usernameToCheck = $("input[name='username']").val();
            $.ajax({
                url: "CheckNames.aspx",
                type: "POST",
                dataType: "json",
                data: { username: usernameToCheck },
                success: function (resp) {
                    if (resp.result != "ok")
                        $(".create_acc_box_form_line input[name='username']").blur();
                }
            });
        });
    }

    // ******************************* /CREATE ACCOUNT ****************************** //



    // ******************************* MY DOWNLOADS ******************************* //

    if ($("#page_id").text() == "My Downloads") {

        $(".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=MyMoviesTV&filter=" + $.getURLParam("filter") + "&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) {
                $("#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 ******************************* //




    // ******************************* My Account and Devices ******************************* //
    /********************* Edited for Samsung Revamp - For "My Account" and "RedeemVoucher"*********************/
    //Added: || $("#page_type").text() == "MyInfo" || $("#page_type").text() =="RedeemVoucher" ) {

    if ($("#page_id").text() == "My Account" || $("#page_id").text() == "My Devices" || $("#page_id").text() == "Top-Up Credit" || $("#page_type").text() == "MyInfo" || $("#page_type").text() == "RedeemVoucher" || $("#page_type").text() == "EditAccount") {

        ////Samsung Revamp Logic////////////
        if ($("#page_type").text() == "MyInfo") {
            $("#user_name").text($("#userid").text());
            $("#user_email").text($("#email_hidden").text());
        }

        ////Samsung Revamp Logic////////////
        if ($("#page_type").text() == "EditAccount") {
            $("#user_name").text($("#userid").text());
            $("#user_email").text($("#email_hidden").text());
        }

        ////Acetrax logic////// $(".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 ******************************* //

function validateCaptcha() {
    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");

        username = $("input[name=username]").val();
        password = $("input[name=pw1]").val();
        email = $("input[name=mail1]").val();
        newsletter = $("input[name=newsletter]:checked").val();
        if (!newsletter) {
            newsletter = 0;
        }
        firstname = username;

        //hide create account button and display loader
        $('.acetrax_btn_create_account').html('<div class="create_acc_check_name"><img src="/acetrax/system/img/ajax-loader.gif"></div>');

        $.ajax({
            url: "CreateUser.aspx",
            type: "POST",
            data: { id: username, passwd: password, email: email, firstname: firstname, newsletter: newsletter },
            success: function () {
                ajaxLogin(
                    username,
                    password,
                    {
                        success: function () {
                            window.location.href = "/";
                        },
                        failure: function () {
                            alert("Error");
                            enableClick(isto);
                        }
                    }
                );
            },
            error: function () {
                alert("Error");
                enableClick(isto);
            },
            complete: function () {
                //alert("Terminado");
            }
        });
        //return true;
    } else {
        if ($(".capd div.error").css("display") == "none") {
            $(".capd .error_captcha").css("display", "block");
        }
        //alert("ERROR: Enter the code as it is shown.");
        document.getElementById(jfldid).focus();
        //return false;
    }
}

// ******************************* /CREATE ACCOUNT ******************************* //


// ******************************* 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();

    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");
        if (varxml == null) {
            $.ajax({
                type: "GET",
                async: false,
                url: "GetUserVouchers.aspx?filterByCurrency=true",
                dataType: "xml",
                success: function (xml) {
                    varxml = 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();
                    }
                    $(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");
                }
            });
        }
        else {
           $("#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();
                    }
                    $(varxml).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 (($(varxml).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"); }
                    } 
                }
        }
}


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 CREDIT ******************************* //

function getVouchersCredit() {
    i = 0;
    var total_balance = 0;
    var mycurrency = "";
    var currency = "";
    var placeHolderName = ".voucherCredit"
     
    $(placeHolderName).empty();
    $(placeHolderName).fadeOut("fast");
    if (varxml == null) {
        $.ajax({
            type: "POST",
            async: false,
            url: "GetUserVouchers.aspx?filterByCurrency=true",
            dataType: "xml",
            data: { allvouchers: 1 },
            success: function (xml) {
                varxml = 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"; }
                    var isTopUp = $(this).find('is_topup').text();

                    value = value.replace(",", ".");
                    if (state == "new") {
                        if (isTopUp.toLowerCase() != 'true') {
                            total_balance += parseFloat(value);
                        }
                    }


                    i = i + 1;
                });
                $(placeHolderName).append(convertToCurrencySymbol(mycurrency, total_balance.toFixed(2)) + "");
                $(placeHolderName).fadeIn("slow");
            }
        });
    }
    else {
    mycurrency = $(varxml).find('UserPaymentMethods').attr('currency');
                if (mycurrency == undefined)
                    mycurrency = "GBP";
                $(varxml).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"; }
                    var isTopUp = $(this).find('is_topup').text();

                    value = value.replace(",", ".");
                    if (state == "new") {
                        if (isTopUp.toLowerCase() != 'true') {
                            total_balance += parseFloat(value);
                        }
                    }

                    i = i + 1;
                });
                $(placeHolderName).append(convertToCurrencySymbol(mycurrency, total_balance.toFixed(2)) + "");
                $(placeHolderName).fadeIn("slow");
            }
    }


// ******************************* VOUCHERS CREDIT ******************************* //
// ******************************* VOUCHERS SUMMARY ******************************* //

    function getVouchersSumary() {
        i = 0;
        var total_balance = 0;
        var account_balance = 0;
        var voucher_balance = 0;
        var topup_balance = 0;
        var mycurrency = "";
        var currency = "";
        var topUpHolderName = ".topupCredit"
        $(topUpHolderName).empty();
        $(topUpHolderName).fadeOut("fast");
        var voucherHolderName = ".voucherCredit"
        $(voucherHolderName).empty();
        $(voucherHolderName).fadeOut("fast");
        var accountHolderName = ".accountBalance"
        $(accountHolderName).empty();
        $(accountHolderName).fadeOut("fast");
        if (varxml == null) {
            $.ajax({
                type: "POST",
                async: false,
                url: "GetUserVouchers.aspx?filterByCurrency=true",
                dataType: "xml",
                data: { allvouchers: 1 },
                success: function (xml) {
                    varxml = 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"; }
                        var isTopUp = $(this).find('is_topup').text();

                        value = value.replace(",", ".");
                        if (state == "new") {
                            if (isTopUp.toLowerCase() == 'false') {
                                voucher_balance += parseFloat(value);
                            }
                            else if (isTopUp.toLowerCase() == 'true') {
                                topup_balance += parseFloat(value);
                            }
                            //account_balance = voucher_balance + topup_balance;
                        }

						account_balance = voucher_balance + topup_balance;
                        i = i + 1;
                    });
                    $(topUpHolderName).append(convertToCurrencySymbol(mycurrency, topup_balance.toFixed(2)) + "");
                    $(topUpHolderName).fadeIn("slow");
                    $(voucherHolderName).append(convertToCurrencySymbol(mycurrency, voucher_balance.toFixed(2)) + "");
                    $(voucherHolderName).fadeIn("slow");
                    $(accountHolderName).append(convertToCurrencySymbol(mycurrency, account_balance.toFixed(2)) + "");
                    $(accountHolderName).fadeIn("slow");
                }
            });
        }
        else {
            mycurrency = $(varxml).find('UserPaymentMethods').attr('currency');
            if (mycurrency == undefined)
                mycurrency = "GBP";
            $(varxml).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"; }
                var isTopUp = $(this).find('is_topup').text();

                value = value.replace(",", ".");
                if (state == "new") {
                    if (isTopUp.toLowerCase() == 'false') {
                        voucher_balance += parseFloat(value);
                    }
                    else if (isTopUp.toLowerCase() == 'true') {
                        topup_balance += parseFloat(value);
                    }
                    //account_balance = voucher_balance + topup_balance;
                }

				account_balance = voucher_balance + topup_balance;
                i = i + 1;
            });
            $(topUpHolderName).append(convertToCurrencySymbol(mycurrency, topup_balance.toFixed(2)) + "");
            $(topUpHolderName).fadeIn("slow");
            $(voucherHolderName).append(convertToCurrencySymbol(mycurrency, voucher_balance.toFixed(2)) + "");
            $(voucherHolderName).fadeIn("slow");
            $(accountHolderName).append(convertToCurrencySymbol(mycurrency, account_balance.toFixed(2)) + "");
            $(accountHolderName).fadeIn("slow");
        }
    }


    // ******************************* VOUCHERS CREDIT ******************************* //


// ******************************* GET YOUR VOUCHERS ******************************* //
/********************* Edited for Samsung Revamp - For "My Account" and "RedeemVoucher" table heading*********************/
//Added: var flagIf = false;  var flagElse = false;
function getYourVouchers() {

    //////////Samsung Revamp Logic////////////
    var flagIf = false;
    var flagElse = false;

    i = 0;
    var total_balance = 0;
    $(".voucher_exmp_box table").empty();
    var mycurrency = "";
    if (varxml == null) {
        $.ajax({
            type: "POST",
            async: false,
            url: "GetUserVouchers.aspx?filterByCurrency=true",
            dataType: "xml",
            data: { allvouchers: 1 },
            success: function (xml) {
                varxml = 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);
                    }

                    /////AceTrax Logic////
                    /*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>");
                    }*/

                    ////////Samsung Revamp Logic////////////
                    if (isTopUp.toLowerCase() != 'true') {

                        //alert("inif");
                        if (flagIf != true) {
                            $(".voucher_exmp_box table").append("<tr class='" + state.toLowerCase() + " " + type.toUpperCase() + "'><th class='voucher_Style'>" + varVoucher_amount + " </th><th class='voucher_Style'>" + varVoucher_expires + " </th><th class='voucher_Style'>" + varVoucher_Type + " </th></tr>");
                            flagIf = true;
                        }
                        $(".voucher_exmp_box table").append("<tr class='" + state.toLowerCase() + " " + type.toUpperCase() + "'><td>" + convertToCurrencySymbol(currency, value) + " </td><td>" + expirationDateFormated + " </td><td>" + type + " </td></tr>");
                    } else {
                        if (flagElse != true) {
                            $(".voucher_exmp_box table").append("<tr class='" + state.toLowerCase() + " " + type.toUpperCase() + "'><th class='voucher_Style'>" + varVoucher_myTopUpCredit + " </th><th class='voucher_Style'>" + varVoucher_expires + " </th><th class='voucher_Style'>" + varVoucher_Type + " </th></tr>");
                            flagElse = true;
                        }
                        $(".voucher_exmp_box table").append("<tr class='" + state.toLowerCase() + " " + type.toUpperCase() + "'><td>" + convertToCurrencySymbol(currency, value) + " </td><td>" + expirationDateFormated + " </td><td>" + type + " </td></tr>");
                    }
                    ////////Samsung Revamp Logic////////////

                    i = i + 1;
                });

                //retrieving the EasyCollect fag
                var hasEasyCollect;
                hasEasyCollect = $(xml).find('HasEasyCollect').text();
                $("#hasEasyCollect").val(hasEasyCollect);

                // fillTopUpValues(xml);


                /////AceTrax Logic////var selTopUpValues = $('#TopUpValues');
                ////////Samsung Revamp Logic////////////
                var selTopUpValues = document.getElementById('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);
                ////////Samsung Revamp Logic////////////
                if ($("#page_type").text() != "MyInfo" && $("#page_type").text() != "RedeemVoucher") {
                    $(".voucher_exmp_box table").prepend("<tr class='detbox_each_voucher_head'><td colspan='2'>" + varVoucher_title + "</td></tr>");
                }

                /////AceTrax Logic////$(".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' style='height:20px;padding-top:15px;padding-bottom:15px;'><b>" +
                varVoucher_balance + ": " + convertToCurrencySymbol(mycurrency, total_balance.toFixed(2)) + "</b></td></tr>");
				/*Removed - As per Sven's changes on Sept 2, 2011*/
                //$(".voucher_exmp_box table").append('<tr><td colspan="2" style="padding:0px" ><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" style="padding:0px" ><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");
            }
        });
    }
    else {
    mycurrency = $(varxml).find('UserPaymentMethods').attr('currency');
                if (mycurrency == undefined)
                    mycurrency = "GBP";
                $(varxml).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);
                    }

                    /////AceTrax Logic////
                    /*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>");
                    }*/

                    ////////Samsung Revamp Logic////////////
                    if (isTopUp.toLowerCase() != 'true') {

                        //alert("inif");
                        if (flagIf != true) {
                            $(".voucher_exmp_box table").append("<tr class='" + state.toLowerCase() + " " + type.toUpperCase() + "'><th class='voucher_Style'>" + varVoucher_amount + " </th><th class='voucher_Style'>" + varVoucher_expires + " </th><th class='voucher_Style'>" + varVoucher_Type + " </th></tr>");
                            flagIf = true;
                        }
                        $(".voucher_exmp_box table").append("<tr class='" + state.toLowerCase() + " " + type.toUpperCase() + "'><td>" + convertToCurrencySymbol(currency, value) + " </td><td>" + expirationDateFormated + " </td><td>" + type + " </td></tr>");
                    } else {
                        if (flagElse != true) {
                            $(".voucher_exmp_box table").append("<tr class='" + state.toLowerCase() + " " + type.toUpperCase() + "'><th class='voucher_Style'>" + varVoucher_myTopUpCredit + " </th><th class='voucher_Style'>" + varVoucher_expires + " </th><th class='voucher_Style'>" + varVoucher_Type + " </th></tr>");
                            flagElse = true;
                        }
                        $(".voucher_exmp_box table").append("<tr class='" + state.toLowerCase() + " " + type.toUpperCase() + "'><td>" + convertToCurrencySymbol(currency, value) + " </td><td>" + expirationDateFormated + " </td><td>" + type + " </td></tr>");
                    }
                    ////////Samsung Revamp Logic////////////

                    i = i + 1;
                });

                //retrieving the EasyCollect fag
                var hasEasyCollect;
                hasEasyCollect = $(varxml).find('HasEasyCollect').text();
                $("#hasEasyCollect").val(hasEasyCollect);

                // fillTopUpValues(xml);


                /////AceTrax Logic////var selTopUpValues = $('#TopUpValues');
                ////////Samsung Revamp Logic////////////
                var selTopUpValues = document.getElementById('TopUpValues');


                //            selTopUpValues.empty();
                //            $('<option/>').attr('value', '').text('Choose recharge amount').appendTo(selTopUpValues);

                var topUpRechargeCurrency;
                $(varxml).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);
                ////////Samsung Revamp Logic////////////
                if ($("#page_type").text() != "MyInfo" && $("#page_type").text() != "RedeemVoucher") {
                    $(".voucher_exmp_box table").prepend("<tr class='detbox_each_voucher_head'><td colspan='2'>" + varVoucher_title + "</td></tr>");
                }

                /////AceTrax Logic////$(".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' style='height:20px;padding-top:15px;padding-bottom:15px;'><b>" +
                varVoucher_balance + ": " + convertToCurrencySymbol(mycurrency, total_balance.toFixed(2)) + "</b></td></tr>");
				/*Removed - As per Sven's changes on Sept 2, 2011*/
                //$(".voucher_exmp_box table").append('<tr><td colspan="2" style="padding:0px" ><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" style="padding:0px" ><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) {
            if (data.Actions != null) {
                // 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 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
				            submitPurchase(offerId, currency, totalPrice, voucherId, varProcessing, varError);
				        }
				    },
				    failure: function () {
				        $(".detbox_login_invalid").slideDown("slow");
				        enableClick(isto);
				    }
				}
			);
            }
        } else {
            // all good to go
            submitPurchase(offerId, currency, totalPrice, voucherId, varProcessing, varError);
        }
    }
}


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",
        //OLD
        /*data: { emailadress: $("#emailadress").val(), username: $("#username").val(),
        movietitle: $("#movietitle").val(), opsystem: $("#opsystem").val(),
        browser: $("#browser").val(), description: $("#description").val()*/
        //NEW
        data: { emailadress: $("#emailadress").val(), username: $("#username").val(),
            movietitle: $("#movietitle").val(), opsystem: $("#opsystem").val(), phonemodel: $("#phoneModel").val(),
            browser: $("#browser").val(), description: $("#description").val()
        },
        async: true,

        success: function (data, textStatus, XMLHttpRequest) {
            if (data != "" && data != undefined) {

                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 phonemodel = escape($('#phoneModel').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%30User%20' + userName + '&body=mail body' + emailAdress + '%0A%0aMovie Title: ' + movieTitle + '%0A%0aOperation System: ' + os + '%0A%0aBrowser: ' + browser + '%0A%0aPhoneModel: ' + phonemodel + '%0A%0aDescription:%0A%0a' + description + '%0A%0a';

                    //Updated on Jun 13, 2011 : As per Sven's comment under Pietro's mail on Jun 9, 2011 subjected as 'Update: Follow-up: official - samsung revamp for test' display ok message inplace of error if client mail is opening.
                    //$("#contactUsErrorDiv").show();

                    $("#contactUsOkDiv").show();
                }
                else {
                    $("#contactUsOkDiv").show();
                }


            } else {
                document.location = 'mailto:cc_support@acetrax.com?subject=Contact from User ' + $('#username').val() + '&amp;body=Email Address: ' + $('#emailadress').val() + '%0A%0aMovie Title: ' + $('#movietitle').val() + '%0A%0aOperation System: ' + $('#opsystem').val() + '%0A%0aBrowser: ' + $('#browser').val() + '%0A%0aPhoneModel: ' + phonemodel + '%0A%0aDescription:%0A%0a' + $('#description').val() + '%0A%0a';
                $("#contactUsErrorDiv").show();
            }
        },

        error: function () {
            $("#contactUsForm").hide();
            $("#contactUsErrorDiv").show();
            document.location = 'mailto:cc_support@acetrax.com?subject=Contact from User ' + $('#username').val() + '&amp;body=Email Address: ' + $('#emailadress').val() + '%0A%0aMovie Title: ' + $('#movietitle').val() + '%0A%0aOperation System: ' + $('#opsystem').val() + '%0A%0aBrowser: ' + $('#browser').val() + '%0A%0aPhoneModel: ' + phonemodel + '%0A%0aDescription:%0A%0a' + $('#description').val() + '%0A%0a';
        }

    });
}

function addContactCustomerCareFormValidator() {
    $("#contactUs").validate({
        rules: {
            emailadress: { required: function(element){return varValidate}, email: true },
            username: { required: function(element){return varValidate}},
            description: { required: function(element){return varValidate}}
        },
        messages: {
            emailadress: {
                required: $("#missingEmail").html(),
                email: $("#invalidEmail").html()
            },
            username: {
                required: $("#missingUser").html()
            },
            description: {
                required: $("#missingDesc").html()
            }
        },
        submitHandler: function () {
									if(varValidate) 
									{  ajaxPostToContactCustomerCare(); }
        }
    });
}

//Show movies as flash at Samsung revammp home page top
function addMovieClipFlash() {
    $("#movie-clips").cycle({
        speed: 750,
        timeout: 5000,
        pager: "#movie-clip-loader",
        pagerAnchorBuilder: function (idx, slide) {
            // return selector string for existing anchor
            return '#movie-clip-loader li:eq(' + idx + ') a';
        },
        pagerEvent: "mouseover"
    });
}

//Show scroll pane on Samsung revammp FAQ page 
function showScrollPane() {
    $(".faq-panel-inner").jScrollPane();
}
