﻿function css_browser_selector(u) { var ua = u.toLowerCase(), is = function(t) { return ua.indexOf(t) > -1; }, g = 'gecko', w = 'webkit', s = 'safari', o = 'opera', h = document.getElementsByTagName('html')[0], b = [(!(/opera|webtv/i.test(ua)) && /msie\s(\d)/.test(ua)) ? ('ie ie' + RegExp.$1) : is('firefox/2') ? g + ' ff2' : is('firefox/3.5') ? g + ' ff3 ff3_5' : is('firefox/3') ? g + ' ff3' : is('gecko/') ? g : is('opera') ? o + (/version\/(\d+)/.test(ua) ? ' ' + o + RegExp.$1 : (/opera(\s|\/)(\d+)/.test(ua) ? ' ' + o + RegExp.$2 : '')) : is('konqueror') ? 'konqueror' : is('chrome') ? w + ' chrome' : is('iron') ? w + ' iron' : is('applewebkit/') ? w + ' ' + s + (/version\/(\d+)/.test(ua) ? ' ' + s + RegExp.$1 : '') : is('mozilla/') ? g : '', is('j2me') ? 'mobile' : is('iphone') ? 'iphone' : is('ipod') ? 'ipod' : is('mac') ? 'mac' : is('darwin') ? 'mac' : is('webtv') ? 'webtv' : is('win') ? 'win' : is('freebsd') ? 'freebsd' : (is('x11') || is('linux')) ? 'linux' : '', 'js']; c = b.join(' '); h.className += ' ' + c; return c; }; css_browser_selector(navigator.userAgent);

$(document).ready(function () {
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
    function EndRequestHandler(sender, args) {
        InitJquery();
        InitShoppingcart();
    }
    InitJquery();
});

var isIE6 = false;
var topOffset = 0;
function EnsureQV() {
    var cartPlace = $('#RegularCart');
    var packType = parseInt(cartPlace.find('#packTypeHF').val(), 10);
    var qvValue = parseInt(cartPlace.find('.shcartTotalQV_right').html(), 10);
    if (packType == 3) {
        if (qvValue < 450) {
            var hasBasic = false;
            cartPlace.find('.shcartItem').each(function () {
                if ($(this).find('.productCode').val() == "3000") {
                    hasBasic = true;
                }
            });
            if(!hasBasic)
            {
                $('.qvBtnPopup').click();
            }
            else
            {
                GoFromProducts();
            }
        }
        else {
            GoFromProducts();
        }
    }
    else if (packType == 2) {
        if (qvValue < 1350) {
            $('.qvBtnPopup').click();
        }
        else {
            GoFromProducts();
        }
    }
    else {
        GoFromProducts();
    }
}
function doProcceed()
{
    $('#btnOkay').click();
}
function GoFromProducts() {
    $('#gonext').click();
}
function InitShoppingcart() {
    if (jQuery('#floatingPanel').position()) {
        var initialTop = jQuery('#floatingPanel').position().top;
        topOffset = parseFloat($('#defaultHeight').val());
        jQuery(window).scroll(function () {
            topOffset = parseFloat($('#defaultHeight').val());
            var topValue = initialTop;
            var windowValue = jQuery(window).scrollTop();
            var windowHeight = jQuery(window).height();
            if (jQuery('#floatingPanel').height() > 1000) {
                if (topOffset == 0) {
                    topValue = 20;
                }
                else {
                    topValue = 60;
                }
            }
            else {
                if (topOffset < windowValue) {
                    if (topOffset == 0) {
                        if (windowValue > 420)
                            topValue = windowValue - 420 + 20;
                        else
                            topValue = 0;
                    }
                    else {
                        if (windowValue > 420)
                            topValue = windowValue - 1700 + 20;
                        else
                            topValue = 0;
                    }
                }
                else
                    topValue = 0;
                var bottomOffset = windowHeight - jQuery('#floatingPanel').height();
                if (bottomOffset < 0) {
                    topValue += (bottomOffset - 100);
                    if (topValue < initialTop)
                        topValue = 0;
                }
            }
            jQuery('#floatingPanel').animate({ top: topValue + "px" }, { queue: false, duration: 350 });
        });

        jQuery('#floatingPanel').find('.shcartBtns_delete').BindProductsDelete();
    }
    
}

jQuery.fn.BindProductsDelete = function() {
    this.click(function(e) {
        var itemstodelete = '';
        var cartPlace = jQuery('#RegularCart');
        cartPlace.find(".shcartItem_cb input:checked").each(function() {
            itemstodelete += jQuery(this).parent().parent().find('.hf_code')[0].value + ",";
        });
        if (itemstodelete.length < 2) {
            return;
        }
        DeleteProduct(itemstodelete, true);
    });
    return this;
}

function DeleteProduct(itemstodelete, updateSelect) {
    cartType = $('.cartType').val();
    var cartPlace = jQuery('#RegularCart');
    cartPlace.find(".shcartBtns_delete").fadeOut('slow');
    cartPlace.find(".shcartTotalPrice_right").fadeOut('slow');
    cartPlace.find(".shcartTotalQV_right").fadeOut('slow');
    var item = jQuery(this).parent().parent();
    $.ajax({
        type: "POST",
        url: "Default.aspx/DeleteProduct",
        data: "{ code:'" + itemstodelete + "',cartType:'" + cartType + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            jQuery.each(data.d.Items, function () {
                jQuery('#id_' + this).remove();
                if (updateSelect) {
                    var hfCount = $('#products').find('#' + this).find('#hfCount');
                    hfCount.val(0);
                    var select = hfCount.next();
                    select.find('option:selected').removeAttr('selected');
                    select.find('option').each(function () {
                        if (0 == parseInt($(this).val())) {
                            $(this).attr('selected', 'selected');
                        }
                    });
                }
            });
            if ($('#cartTypeField').val() == 0) {
                ChechForCCP(data.d.CCP);
            }
            cartPlace.find(".shcartTotalQV_right").html(data.d.VisibleQV);
            cartPlace.find(".shcartTotalPrice_right").html('$' + data.d.Total);
            cartPlace.find(".shcartBtns_delete").fadeIn('slow');
            cartPlace.find(".shcartTotalPrice_right").fadeIn('slow');
            cartPlace.find(".shcartTotalQV_right").fadeIn('slow');
        }
    });
}
function BindAddToCart(productCode, count, control) {
        var cartContainer = jQuery('#RegularCart');
        jQuery(control).hide();
        jQuery(control).parent().find('.shloader').show();
        cartType = $('.cartType').val();
        jQuery.ajax({
            type: "POST",
            url: "Default.aspx/AddProduct",
            data: "{ productCode:'" + productCode + "',cartType:'" + cartType + "',count:'" + count + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {

                var newItem = true;
                var selectedHidden;
                var productName = data.d.ProductName;
                var price = data.d.Price;
                var quant = data.d.Quantity;
                cartContainer.find(".shcartItems").find(".hf_code").each(function () {
                    if (this.value == productCode) {
                        newItem = false;
                        selectedHidden = this;
                    }
                });
                if (newItem) {
                    var ItemDiv = AddNewItem(productCode, productName, price, quant);
                    cartContainer.find('.shcartItems').append(ItemDiv);
                }
                else {
                    jQuery(selectedHidden).parent().find('.shcartItem_qt').html(quant);
                }

                if ($('#cartTypeField').val() == 0) {
                    ChechForCCP(data.d.CCP);
                }
                cartContainer.find(".shcartTotalQV_right").html(data.d.VisibleQV);
                cartContainer.find(".shcartTotalPrice_right").html('$' + data.d.Total);
                jQuery(control).parent().find('.shloader').hide();
                jQuery(control).show();
                cartContainer.find(".shcartBtns_delete").fadeIn('slow');
                cartContainer.find(".shcartTotalPrice_right").fadeIn('slow');
                cartContainer.find(".shcartTotalQV_right").fadeIn('slow');

                // TO DO: Call back for client logic
            }
        });
    }

    function ChechForCCP(command) {
        if (command.IsAction) {
            if (command.Product) {
                var ItemDiv = AddNewItem(command.Product.Code,
           command.Product.Description, command.Product.Price, "1", true);
                jQuery('#RegularCart').find('.shcartItems').append(ItemDiv);
            }
            jQuery('#id_' + command.RemovePackCode).remove();
        }
    }
    
    function AddNewItem(productCode, productName,price,quant, isDisabled){
        var ItemDiv = jQuery('<div></div>').addClass('shcartItem').attr('id', 'id_' + productCode);
        var ItemLcheck = jQuery('<label></label>').addClass('shcartItem_cb');
        var Itemcheckbox = jQuery('<input />').attr('type', 'checkbox');
        if (isDisabled) {
            Itemcheckbox.attr('disabled', true);
        }
        var codeItem = jQuery('<input />').attr('type', 'hidden').addClass('productCode').val(productCode);
        var Ttemname = jQuery('<label></label>').addClass('shcartItem_name').html(productName);
        var Ttemprice = jQuery('<label></label>').addClass('shcartItem_price').html('$' + price);
        var Itemquantity = jQuery('<label />').addClass('shcartItem_qt').html(quant);
        var Itemcode = jQuery('<input />').addClass('hf_code').attr('type', 'hidden').attr('value', productCode);
        ItemDiv.append(ItemLcheck);
        ItemLcheck.append(Itemcheckbox);
        ItemDiv.append(Ttemname);
        ItemDiv.append(Itemquantity);
        ItemDiv.append(Ttemprice);
        ItemDiv.append(Itemcode);
        ItemDiv.append(codeItem);
        return ItemDiv;
    }

    function UpdateSelects() {
        $('.productItem').find('#hfCount').each(function() {
            var count = parseInt($(this).val());
            if (count > 0) {
                var select = $(this).next();
                //if (count > 3) {
                //    for (i = 4; i <= count; i++) {
                //       select.append("<option value=" + i + ">" + i + "</option>");
                //    }
                //}
                select.find('option:selected').removeAttr('selected');
                select.find('option').each(function() {
                    if (count == parseInt($(this).val())) {
                        $(this).attr('selected', 'selected');
                    }
                });

            }
        });
        //total();
    }

function InitJquery() {

    CheckLanguage();

    var currentcountry = $('.country .nm').text();

    if (navigator.appVersion.indexOf("MSIE 6") > -1) {
        //alert("IE6");
        isIE6 = true;
    } else {
        //alert("IE 8");
        isIE6 = false;
    }
    $('#autoUpline').change(function() {
        if ($(this).attr("checked")) {
            $('.txID').val('');
             $('.txID').attr('disabled', 'disabled'); 
        }
        else {
         $('.txID').removeAttr('disabled');
        }
    });
    $('.country .nm').click(function() {
        if ($(this).next().is(':hidden')) {
            $('.country .nm').hide();
            $(this).next().slideDown('fast');
        }
        else {
            $('.country .nm').show();
            $(this).next().slideUp('fast');

        }
    });
    
    function ShowTwPopup() {
        alert("RBC　LIFE美商泰康自10月1日（星期六）起，正式在臺開放所有相關營業運作，詳情請致電(02)2503-8018");
    }

    if ($("#ShowTwPopup").val() == "true") {
        ShowTwPopup();
    }
    
    $('.country ul a').click(function () {
        var isAdmin = $("#isAdminIndicator").val() == 'true';
        if (!isAdmin && $(this).text().toLowerCase().indexOf("taiwan") != -1) {
            $('.country .nm').click();
            ShowTwPopup();
            return false;
        }
        var value = $(this).text();
        $('#icountry').val($(this).attr('id'));
        var im = $(this).children('img').clone();
        $('.country .nm').children().remove().end().text($(this).text()).prepend(im).next().slideUp('fast');
        $('.country .nm').show();
        // changestep(2);
        if (currentcountry != value) {
            currentcountry = value;
            __doPostBack('Upanel', value);
        }
    });
    
    $('#gonext,#loginaction').mousedown(function() { $(this).addClass('mousedown') }).mouseup(function() { $(this).removeClass('mousedown') });

    $('#products tr:last').addClass('prev');
    
    function total() {
        var sum = 0, qvsum = 0, col = 0, quant = 0, cost = 0, qv = 0;
              
        $('.productItem').each(function() {
        if ($(this).find('input:hidden').val()) { quant = parseInt($(this).find('input:hidden').val()); } else { quant = 0 }
            cost = parseFloat($(this).find('.priceLbl').text());
            qv = parseFloat($(this).find('.qvLbl').text());
            col += quant;
            sum += cost * quant;
            qvsum += qv * quant;

        });  
        $('#products .quant').text(col);
        $('#products .cash').text(sum.toFixed(2));
        $('#products .qvcash').text(qvsum.toFixed(2));
        $('#itotal').val(sum.toFixed(2));
        if (sum > 0) {
            $('#gonext').removeAttr('disabled');
            changestep(2);
        }
        else {
            $('#gonext').attr('disabled', 'disabled');
            //changestep(1);            
        }
    }

    var oldstep = 0;
    function changestep(step) {
        if (oldstep != step) {
            oldstep = step;
            var pos = (step - 1) * (-185);
            $('#steps').css('background-position', '0 ' + pos + 'px');
        }
    }

    $('.paypal_ddl').change(function () {

        $('.paypal_name').html($(this).val() + " account ID");

    });
//    $('#Step3Control_tb_city').keyup(function() {
//        if ($(this).val().length > 25) {
//            $(this).val($(this).val().substring(0, 25));
//            $('#citymaxlengh').show();
//        }
//        else {
//            $('#citymaxlengh').hide();
//        }
//    });

//    $('#Step3Control_tb_city').blur(function() {
//        if ($(this).val().length > 25) {
//            $(this).val($(this).val().substring(0, 25));
//            $('#citymaxlengh').show();
//        }
//    });

    $('#nfr_form').find('.tx').each(function () {
        var allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890@,.-_! ";
        $(this).keydown(function (e) {
            if ($(this).attr("id") == "Step3Control_tb_accountusername" && e.which == "32") {
                var text = $(this).val();
                $(this).val(text.substring(0, text.length - 1));
                alert("No space is allowed in username field.");
                return false;
            }
            if (e.which == "8" || e.which == "9" || e.which == "46")
                return true;
            if ($(this).attr('class').indexOf('freeinput') != -1) {
                return true;
            }
            var unicode = e.keyCode ? e.keyCode : e.charCode;
            if (allowedChars.indexOf(String.fromCharCode(unicode)) != -1) {
                return true;
           }
            else {
                return true;
            }
        });
    });
    
    $('#Step3Control_tb_zip').keyup(function() {
        if ($(this).val().length > 10) {
            $(this).val($(this).val().substring(0, 10));
            $('#postalmaxlengh').show();
        }
        else {
            $('#postalmaxlengh').hide();
        }
    });

    $('#Step3Control_tb_zip').blur(function() {
        if ($(this).val().length > 10) {
            $(this).val($(this).val().substring(0, 10));
            $('#postalmaxlengh').show();
        }
    });
    
    
    $('.calc .op span').click(function() {
        $('#dt').show(); $('span.dm').remove();
        $('#dt').calendarLite({
            onSelect: function(date) {
                var dt = date;
                $('#date').val(dt);
                $('<span class="dm">&nbsp;(' + dt + ')</span>').insertAfter('.calc .op span:first');
                $('#dt').hide();
                return false;
            }
        });
    });

    $('#ccv').mouseout(function() { $(this).hide() }).click(function() { $(this).hide() });
    $('a.ccv').click(function() {
        $('#ccv').css('visibility', 'visible').show();
        return false
    });
    $('tr.tl').prev().addClass('prv');
    $('div.fintable table tr:eq(1)').addClass('firstline');


    $('#btn_reset').click(function() {
        $('.productItem').find('input:hidden').each(function() {
            $(this).val(0);
            $(this).next().find('option:selected').removeAttr('selected');
            $(this).next().find('option:first').attr('selected', 'selected');
        });
        total();
    });

    var maxCount = 3;
    if ($("#country .nm").text().toLowerCase().indexOf("hongkong") != -1) {
        maxCount = 10;
    }
    if ($('.accessLevel').val() == 'admin') {
        maxCount = 10;
    }

    $('.addtocart').click(function() {
        var select = $(this).parent().parent().find('select');
        var selected = parseInt(select.find('option:selected').val());
        if (selected < maxCount) {
            var next = select.find('option:selected').next();
            select.find('option:selected').removeAttr('selected');
            next.attr('selected', 'selected');
        }
        //var quantity = parseInt(select.find('option:last').val());
        //quantity++;
        //select.append("<option value=" + quantity + ">" + quantity + "</option>");
        $('.productItem select').change();
    });
    $('.productItem a').click(function () {
        var qField = $(this).parent().find('#hfCount');
        var code = $(this).parent().find('#hfCode').val();
        var quantity = parseInt($(this).parent().find('#tbQntity').val());
        qField.val(quantity);
        if (quantity > maxCount) {
            quantity = maxCount;
        } 
        if (quantity > 0) {
            var isBackOrder = $(this).parent().find('.hdnIsBackOrder').val();
            if (isBackOrder == "1") {
                jQuery(this).parent().find('.btnAddProductPopup').click();
            }
            BindAddToCart(code, quantity, this);
        }

    });
    $('.productItem .qntTextBox').keypress(function (e) {
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
            return false;
        }
    });
    $('.productItem .qntTextBox').keyup(function (e) {
        if (parseInt(this.value, 10) > maxCount) {
            this.value = maxCount;
        }
    });

    $('.productItem select').change(function () {
        var qField = $(this).parent().find('#hfCount');
        var code = $(this).parent().find('#hfCode').val();
        var quantity = parseInt($(this).val());
        qField.val(quantity);

        if (quantity > 0) {
            var isBackOrder = $(this).parent().find('.hdnIsBackOrder').val();
            if (isBackOrder == "1") {
                jQuery(this).parent().find('.btnAddProductPopup').click();
            }      
            
            BindAddToCart(code, quantity, this);
        }
        else {
            DeleteProduct(code, false);
        }
        //total();
    });

    //Checking Placement Id last month + current month QV
    /*$('.placementcode').blur(function () {
        var placementId = $(this).val();
        if (placementId != '') {
            $.ajax({
                type: "POST",
                url: "Default.aspx/CheckPlacementQv",
                data: "{'accountCode':'" + $(this).val() + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    var result = parseFloat(msg.d);
                    if (result == -1) {
                        alert("The are no PlacementID: " + placementId);
                        return;
                    }
                    else if (result < 70) {
                        alert("The Placement you choose didn't meet the minimum QV requirement, please choose another one.");
                    }
                    //else {
                    //    alert("lastmonth QV + this month QV = " + msg.d);
                   // }
                }
            });
        }
    });*/

//    $('#Step3Control_tb_accountusername').keyup(function() {
//        var name = $('#Step3Control_tb_accountusername').val();
//        if (name.length > 2) {
//            $.ajax({
//                type: "POST",
//                url: "Default.aspx/CheckUsername",
//                data: "{'accountusername':'" + name + "'}",
//                contentType: "application/json; charset=utf-8",
//                dataType: "json",
//                success: function(msg) {
//                    if (msg.d == "0") {
//                        $('.accountstatelbl').attr("src", 'i/ok.png');
//                    }
//                    else {
//                        $('.accountstatelbl').attr("src", 'i/cross.png');
//                    }
//                }
//            });
//        }
//        else {
//            $('.accountstatelbl').attr("src", 'i/cross.png');
//        }
//    });

    UpdateSelects();

    //Check address line for max 40 char.
    if (isIE6 == false) {
        var eventNames = "change keyup onpropertychange oninput"; // all events you wish to bind to
        var AddressCheck = function () {
            return false;
            var text = $(this).val();
            if (text.length <= 40) {
                return false;
            }
            else {
                if (text.toLowerCase().indexOf("taiwan (r.o.c.)") >= 0) {
                    var textarray = text.split(",");
                    start = textarray.length - 2;
                    end = textarray.length - 3;
                    var city = new String();
                    var address = new String();
                    var address2 = new String();
                    if (textarray.length >= 4) {
                        for (i = end; i <= start; i++) {
                            if (i != end) city += ",";
                            if (textarray[i].charAt(0) == " ") textarray[i] = textarray[i].substring(1, textarray[i].length);
                            city += textarray[i];
                        }
                        for (i = 0; i < end; i++) {
                            if (i != 0) address += ",";
                            if (textarray[i].charAt(0) == " ") textarray[i] = textarray[i].substring(1, textarray[i].length);
                            address += textarray[i];
                        }
                    }
                    if (address.length > 40) {
                        for (i = 39; i >= 0; i--) {
                            if (address.charAt(i) == ",") {
                                address2 = address.substr(i + 1, address.length);
                                if (address2.charAt(0) == " ") address2 = address2.substring(1, address2.length);
                                address = address.substring(0, i);
                                i = 0;
                                break;
                            }
                        }
                    }
                    $('.b4').find('.address1').val(address);
                    $('.b4').find('.address2').val(address2);
                    $('.b4').find('.city').val(city);
                    //alert(city + " -- " + address + " -- " + address2);
                }
                else {
                    $('.b4').find('.address1').unbind(eventNames);
                    alert("Address Line1 max length is 40 characters. Please use Address Line2 to proceed.");
                    $('.b4').find('.address1').val(text.substring(0, 40));
                    $('.b4').find('.address2').val(text.substr(39, text.length));
                    $('.b4').find('.address2').focus();
                    $('.b4').find('.address1').bind(eventNames, AddressCheck);
                }
            }
        }
        $('.b4').find('.address1').bind(eventNames, AddressCheck);
        $('.b4').find('.address2').bind("change keyup", function () {
            var text = $(this).val();
            if (text.length <= 40) {
                return false;
            }
            else {
                alert("Address Line2 max length is 40 characters.");
                $('.b4').find('.address1').val(text.substring(0, 40));
                $(this).blur();
            }
        });
    }
    $('.enrollerplacement').change(function () {
        var tb_placementid = $('.placementcode');
        var ddl_placementid = $('.placementoption');
        if ($(this).val() == "Manual") {
            tb_placementid.removeAttr("disabled").css('background-color', 'white');
            ddl_placementid.removeAttr("disabled").css('background-color', 'white');
        }
        else {
            tb_placementid.attr("disabled", "disabled").css('background-color', '#f1f1f1').val("");
            ddl_placementid.attr("disabled", "disabled").css('background-color', '#f1f1f1');
        }
    });
    $('.billingcountry').change(function () {
        var country = $(this).val();
        $('.hf_billingCountry').val(country);
    });
    $('.usercountry').change(function () {
        var country = $(this).val();
        $('.hf_Country').val(country);
        $('.hf_billingCountry').val(country);
        $('.billingcountry').find('option').each(function () {
            if ($(this).val() == country) {
                $(this).attr("selected", "selected");
            }
            else {
                $(this).removeAttr("selected");
            }
        });
        var country = $(this).val();
        $.ajax({
            type: "POST",
            url: "Default.aspx/UpdateShipping",
            data: "{'country':'" + country + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                $('#Step3Control_lb_total_wship').html(parseFloat(msg.d, 10));
            }
        });

    });

}

function getFlashMovieObject(movieName) {
    if (window.document[movieName]) {
        return window.document[movieName];
    }
    if (navigator.appName.indexOf("Microsoft Internet") == -1) {
        if (document.embeds && document.embeds[movieName])
            return document.embeds[movieName];
    }
    else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
    {
        return document.getElementById(movieName);
    }
}
 
function CheckLanguage() {
    var lang = $('#selectedlanguage').val();
    if (lang == "zh-tw") {
        $('#loginaction').removeAttr('class').addClass('loginaction_tw');
        $('#btn_Agree').removeAttr('class').addClass('agreebtn agreebtn_tw');
        $('#steps').removeAttr('class').addClass('steps_tw');
        $('.icons').removeAttr('class').addClass('icons icons_tw');
        $('#step2').removeAttr('class').addClass('step234n_tw');
        $('.goback2').removeAttr('class').addClass('goback2 goback2_tw');
        $('.gonext2').removeAttr('class').addClass('gonext2 gonext2_tw');
        $('#products').find('#btn_addtocart').each(function() {
            $(this).removeAttr('class').addClass('addtocart addcart_tw');
        });
        $('#btn_reset').removeAttr('class').addClass('reset_tw');
        $('#total').attr('src', 'i/tw/total.png');
        $('#step3').removeAttr('class').addClass('step34n_tw');
        $('#enroller_image').attr('src', 'i/tw/enid.png');
        $('#step4next').removeAttr('class').addClass('stepfour_tw');
        $('#step4').removeAttr('class').addClass('stepfour_tw');
        $('#ccv_image').attr('src', 'i/tw/ccv.png');
        $('.goback').removeAttr('class').addClass('goback goback_tw');
        $('.placeorder').removeAttr('class').addClass('placeorder placeorder_tw');
        $('#steps3').removeAttr('class').addClass('steps3_tw');
        $('#steps4').removeAttr('class').addClass('steps4_tw');
        $('#finished_image').attr('src', 'i/tw/finished.png');
        if (getFlashMovieObject("nfr_banner").setLanguage){
            getFlashMovieObject("nfr_banner").setLanguage("cn");
        }
    }
    else {
        $('#loginaction').removeAttr('class').addClass('loginaction_en');
        $('#btn_Agree').removeAttr('class').addClass('agreebtn agreebtn_en');
        $('#steps').removeAttr('class').addClass('steps_en');
        $('.icons').removeAttr('class').addClass('icons icons_en');
        $('#step2').removeAttr('class').addClass('step234n_en');
        $('.goback2').removeAttr('class').addClass('goback2 goback2_en');
        $('.gonext2').removeAttr('class').addClass('gonext2 gonext2_en');
        $('#products').find('#btn_addtocart').each(function() {
            $(this).removeAttr('class').addClass('addtocart addcart_en');
        });

        $('#btn_reset').removeAttr('class').addClass('reset_en');
        $('#total').attr('src', 'i/total.gif');
        $('#step3').removeAttr('class').addClass('step34n_en');
        $('#enroller_image').attr('src', 'i/enid.png');
        $('#step4next').removeAttr('class').addClass('stepfour_en');
        $('#step4').removeAttr('class').addClass('stepfour_en');
        $('#ccv_image').attr('src', 'i/ccv.png');
        $('.goback').removeAttr('class').addClass('goback goback_en');
        $('.placeorder').removeAttr('class').addClass('placeorder placeorder_en');
        $('#steps3').removeAttr('class').addClass('steps3_en');
        $('#steps4').removeAttr('class').addClass('steps4_en');
        $('#finished_image').attr('src', 'i/finished.gif');
        if (getFlashMovieObject("nfr_banner").setLanguage) {
            getFlashMovieObject("nfr_banner").setLanguage("en");
        }
    }
}

function ValidateAccount(source, clientside_arguments) {
    clientside_arguments.IsValid = validateUsers();
//    var text = $('.accountstatelbl').attr("src");
//    if (text == 'i/ok.png') {
//        clientside_arguments.IsValid = true;
//    }
//    else { clientside_arguments.IsValid = false; }
}

function WelcomeAgreeValidation(source, clientside_arguments) {
    if ($('#agreecheckbox').is(':checked')) {
        clientside_arguments.IsValid = true;
    }
    else { clientside_arguments.IsValid = false; }
    if (clientside_arguments.IsValid == false)
        alert("You must agree to the Terms & Conditions");
}


function ValidateExpirationDate(source, clientside_arguments) {
    clientside_arguments.IsValid = true;
    var currdate = new Date();
    var mm = $('.col2').find('.expirationmm').find('option:selected').val();
    var yy = $('.col2').find('.expirationyy').find('option:selected').val();
    var currdate = new Date();
    var month = currdate.getMonth();
    var year = currdate.getFullYear();
    if (parseInt(yy, 10) < parseInt(year, 10)) {
        clientside_arguments.IsValid = false;
    }
    if (parseInt(yy, 10) == parseInt(year, 10) && parseInt(mm, 10) < (parseInt(month, 10)+1)) {
        clientside_arguments.IsValid = false;
    }
    if (clientside_arguments.IsValid == false) {
        alert("Enter correct expiration date.");
    }
}

function ShowCCV() {
    $('#ccv').css('visibility', 'visible').show();
}
function CloseCCV() {
    $('#ccv').css('visibility', 'visible').hide();
}

function PostBack(args) {
    $.ajax({
        type: "POST",
        url: "Default.aspx?" + args,
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function() {
        }
    });
}

function AgreeClicked() {
    if ($('#chb_agree').is(':checked')) {
        $('#chb_donot').attr('checked', false);
    }
    else {
        $('#chb_donot').attr('checked', true);
    }
}
function DoNotAgreeClicked() {
    if ($('#chb_donot').is(':checked')) {
        $('#chb_agree').attr('checked', false);
    }
    else {
        $('#chb_agree').attr('checked', true);
    }
}

function Validate() {
    var isValid = true;
    isValid = validateUsers();
    if (!isValid) {
        alert("User name is not valid");
    }
    $('#nfr_form').find(':text').each(function() {
        if ($(this).attr("alt") != "novalidation") {
            if (!$(this).val()) {
                isValid = false;
                $(this).parent().parent().addClass('error')
                $(this).keypress(function(e) {$(this).parent().parent().removeClass('error');});
            }
        }

    });
    $('#nfr_form').find(':password').each(function() {
        if (!$(this).val()) {
            isValid = false;
            $(this).parent().parent().addClass('error')
            $(this).keypress(function(e) { $(this).parent().parent().removeClass('error'); });
        }
    });

    if ($('#tot').find(':checkbox').is(':checked')) {
        var text = $('#tot').find('.selectAMOText').val();
        if (text == '') {
            isValid = false;
            $('#tot').find('#Step3Control_autoshipdatevalidator').css("color", "red");
            alert("Please set up your Autoship starting date, and please be aware your first Autoship order will be shipped on that date, and the same date every other month thereafter. Thanks for shopping with RBC Life.");
        }
    }
    
    var paypal = $('#nfr_form').find('.paypal').val();
    if (paypal.length > 0)
    {
        var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
        if (!emailPattern.test(paypal) || paypal.length > 25) {
            isValid = false;
        }
    }

    if (isValid) {
        var mpu = $find('ProceedRegPopupExtender');
        mpu.show();
    }
    return isValid;
}

function CheckPayPalLength(source, clientside_arguments) {
    clientside_arguments.IsValid = true;
    var paypallength = $('#nfr_form').find('.paypal').val();
    if (paypallength.length > 25) {
        clientside_arguments.IsValid = false;
    }
}

var oldAccount = "";
var oldCart = "";
var isNeedtoClose = false;



function ChangeBillingValidation(checkboxID, shippingName, shippingAddress1, shippingAddress2, shippingCity, shippingPostal,
    billingName, billingAddress1, billingAddress2, billingCity, billingPostal) {
    
    if ($('#' + checkboxID).attr("checked")) {
        $('#' + billingName).val($('#' + shippingName).val());
        $('#' + billingAddress1).val($('#' + shippingAddress1).val());
        $('#' + billingAddress2).val($('#' + shippingAddress2).val());
        $('#' + billingCity).val($('#' + shippingCity).val());
        $('#' + billingPostal).val($('#' + shippingPostal).val());

        //Remove Validation
        $('#' + billingName).parent().parent().removeClass('error');
        $('#' + billingName).attr("alt", "novalidation");
        $('#' + billingAddress1).parent().parent().removeClass('error');
        $('#' + billingAddress1).attr("alt", "novalidation");
        $('#' + billingCity).parent().parent().removeClass('error');
        $('#' + billingCity).attr("alt", "novalidation");
        $('#' + billingPostal).parent().parent().removeClass('error');
        $('#' + billingPostal).attr("alt", "novalidation");
        $('.usercountry').change();
        //$('#BillingInfo').find('.validationerror').each(function() {
        //    ValidatorEnable($(this)[0], false);
        //});

    }
    else {
        $('#' + billingName).val('');
        $('#' + billingAddress1).val('');
        $('#' + billingAddress2).val('');
        $('#' + billingCity).val('');
        $('#' + billingPostal).val('');
        
        //Add validation
        $('#' + billingName).removeAttr("alt");
        $('#' + billingAddress1).removeAttr("alt");
        $('#' + billingCity).removeAttr("alt");
        $('#' + billingPostal).removeAttr("alt");
        
        //$('#BillingInfo').find('.validationerror').each(function() {
        //    ValidatorEnable($(this)[0], true);
        //});
    }

}

function ValidateCard(source, clientside_arguments) {
      var cardReffer = $('#Step4Control_ProPay_CardRefer')[0].value;
      var cardMask = $('#Step4Control_ProPay_CardMask')[0].value;
      if (cardReffer.length > 10 && cardMask.length > 10) {
          clientside_arguments.IsValid = true;
      }
      else {
          clientside_arguments.IsValid = false;
      }
  }
function ValidateCreditCard(sender, args) {
      args.IsValid = isValidCreditCard(jQuery(".paymentMethod").val(), jQuery('.CCNumber').val());
  }
function isValidCreditCard(type, ccnum) {
      if (type == "Visa") {
          // Visa: length 16, prefix 4, dashes optional.
          var re = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/;
      } else if (type == "MasterCard") {
          // Mastercard: length 16, prefix 51-55, dashes optional.
          var re = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/;
      } else if (type == "Discover") {
          // Discover: length 16, prefix 6011, dashes optional.
          var re = /^6011-?\d{4}-?\d{4}-?\d{4}$/;
      } else if (type == "AMEX") {
          // American Express: length 15, prefix 34 or 37.
          var re = /^3[4,7]\d{13}$/;
      }
      if (!re.test(ccnum))
          return false;
      // Remove all dashes for the checksum checks to eliminate negative numbers
      ccnum = ccnum.split("-").join("");
      // Checksum ("Mod 10")
      // Add even digits in even length strings or odd digits in odd length strings.
      var checksum = 0;
      for (var i = (2 - (ccnum.length % 2)); i <= ccnum.length; i += 2) {
          checksum += parseInt(ccnum.charAt(i - 1));
      }
      // Analyze odd digits in even length strings or even digits in odd length strings.
      for (var i = (ccnum.length % 2) + 1; i < ccnum.length; i += 2) {
          var digit = parseInt(ccnum.charAt(i - 1)) * 2;
          if (digit < 10) { checksum += digit; } else { checksum += (digit - 9); }
      }
      if ((checksum % 10) == 0)
          return true;
      else
          return false;
  }
function CheckAgree(source, clientside_arguments) {
    if ($('#chb_agree').is(':checked')) {
        clientside_arguments.IsValid = true;
        $('#agreevalidator').attr("style", "cursor:pointer");
    }
    else {
        clientside_arguments.IsValid = false;
        $('#agreevalidator').attr("style", "color:red; cursor:pointer");
     }
}

function ClearHistory() {
    var iframe = $('#newCard');
    iframe.location.replace(iframe.src);
}

function ValidatePasswordLength(source, clientside_arguments) {
     var IsValid = true;
     $('#nfr_form').find(':password').each(function() {
         var length = $(this).val().length;
         if (length < 6 && length > 0) {
             IsValid = false;
             $('#nfr_form').find('#pswlengthvalidator').attr("style", "color:red");
         }
     });
     if (IsValid) {
         $('#nfr_form').find('#pswlengthvalidator').removeAttr("style");
     }
     clientside_arguments.IsValid = IsValid;
 }

 function ValidateAutoShip(source, clientside_arguments) {

     if ($('#tot').find(':checkbox').is(':checked')) {
         var text = $('#tot').find('.selectAMOText').val();
         if (text != '') {
             clientside_arguments.IsValid = true;
         }
         else {
             clientside_arguments.IsValid = false;
             $('#tot').find('#Step3Control_autoshipdatevalidator').css("color", "red");
             alert("Please set up your Autoship starting date, and please be aware your first Autoship order will be shipped on that date, and the same date every other month thereafter. Thanks for shopping with RBC Life.");
         }
     }
     else {
         clientside_arguments.IsValid = true;
     }
 }

 function ShowImage() {
     var image = $('.popup_Buttons').find('#imagediv');
     image.removeAttr("style");
     return true;
 }

 function CloseTerms() {
     var mpu = $find('AgreePopupExtender');
     mpu.hide();
     UpdateCard();
 }

 function CloseConfirmationPopUp() {
     var mpu = $find('SubmitPopupExtender');
     mpu.hide();
     UpdateCard();
 }
 function CloseQVPopUp() {
     var mpu = $find('CheckQVCCPPopupExtender');
     mpu.hide();
     UpdateCard();
 }

 function ProcessAshipPopUp() {
     if ($('#Step3Control_aship').is(':checked')) {
         var mpu = $find('Step3Control_AshipPopupExtender');
         mpu.show();
     }
     else {
         $('.amoProdList').hide();
         $('.amoPicker').hide();
     }
 }

 function CloseAshipPopUp(isAship) {
     var mpu = $find('Step3Control_AshipPopupExtender');
     if (isAship == "false") {
         $('#Step3Control_aship').attr('checked', false);
     }
     else {
         $('.amoProdList').show();
         $('.amoPicker').show();
     }
     if (mpu)
     {
     mpu.hide();
     }
 }

 function UpdateCard() {
     if (oldAccount.length > 0 && oldCart.length > 0) {
         fillCards(oldAccount, oldCart);
     }
 }

 function Print() {
     if (navigator.appVersion.indexOf("MSIE 7") != -1) {
            document.execCommand('print', false, null);
         }
         else {
             window.print();
         }
 }
 function MoveToTop() {
     setTimeout("scroll(0, 0)", 300);
      
 }
