function is_ie6() {
    if(checkVersionIE8()) return false;
    return (jQuery.browser.msie && jQuery.browser.version < 7) ? true : false;
}

function csShow(){
    jQuery("#cs_li").addClass("over");
    jQuery("#cs_li").find("ul").show();
    jQuery(".hide_span").addClass("hidden_span");
    jQuery("#cs_li #cs_a").addClass("hover");
}
function csHide(){
    jQuery("#cs_li").removeClass("over");
    jQuery("#cs_li").find("ul").hide();
    jQuery(".hide_span").removeClass("hidden_span");
    jQuery("#cs_li #cs_a").removeClass("hover");
}

function getInternetExplorerVersion() {
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
    }
    return rv;
}

function checkVersionIE8() {
    var ver = getInternetExplorerVersion();
    if (ver > -1) {
        if (ver >= 8.0)
            return true;
    }
    return false;
}

//加入收藏
function addToMyFavorite(type,id){
    next_url = [type];
    jQuery.ajax({
        url: "/members/my_favorite",
        type: "post",
        data: {
            "type":type,
            "id":id
        },
        dataType: 'script',
        complete: function(XMLHttpRequest, textStatus){
        //alert(XMLHttpRequest.responseText);
        },
        error: function(){
            alert("wrong");
        }
    })
}

function remove_cart(cart_id){
    jQuery.ajax({
        url: "/shopping_cart/remove_cart?cart_id="+cart_id.toString(),
        dataType: 'script',
        type: 'post',
        complete: function(XMLHttpRequest, textStatus){
        //alert(XMLHttpRequest.responseText);
        }
    });
}

// 购物车

// 通过存放数量的input处理加入购物车操作
function put_in_shopping_cart_by_dom_id(dom_id,product_uuid,quantity_dom_id,check_width){
    jQuery('#check_cart_'+dom_id).css('display', 'block')
    quantity = jQuery('#'+quantity_dom_id).val();
    if(quantity==null || quantity==''){
        quantity=1;
    }
    extend_price = jQuery('#extend_price').val()
    put_in_shopping_cart(dom_id,product_uuid,quantity,check_width)
}

// 通过存放数量值处理加入购物车操作
var desc_flag = false;
function put_in_shopping_cart(dom_id,product_uuid,quantity,check_width){
    var product_specification = (jQuery('#product_specification_select').length > 0)?jQuery('#product_specification_select').val():'';
    //var img = jQuery("#shopping_cart_img");
    var add_to_cart = jQuery("#cart_" + dom_id).html
    var desc = '';
    desc = getProductDesc();
    if(!desc_flag){
        jQuery.ajax({
            url:'/shopping_cart/put_in_cart',
            type:'post',
            data:{
                "dom_id":"check_cart_" + dom_id,
                "uuid":product_uuid,
                'purchase_quantity':quantity,
                'product_specification':product_specification,
                'from_list':jQuery("#from_list_" + dom_id).val(),
                'desc':desc
            },
            beforeSend: function() {
                jQuery("#shopping_cart_button_" + dom_id).hide();
                jQuery("#img_load").html("<img src='/images/loading.gif' />");
            },
            complete: function(XMLHttpRequest){
                var msg = XMLHttpRequest.responseText;
                //    jQuery("#shopping_cart_button_" + dom_id).html(add_to_cart);
                // alert(msg);
                if(msg != "" && msg.length > 10) {
                    alert(msg);
                    jQuery("#img_load").hide();
                    jQuery("#shopping_cart_button_" + dom_id).show();
                //                    jQuery("#cart_" + dom_id).html(add_to_cart);
                //  jQuery("#check_cart_"+dom_id).html("error");
                } else {
                    refresh_cart_num(msg);
                    // jQuery("#cart_" + dom_id).html("");
                    // jQuery("#cart_" + dom_id).append(add_to_cart);
                    //jQuery("#check_cart_"+dom_id).html("<a href='/shopping_cart/show_cart'>check cart</a>");
                    check_html = "<a href='/shopping_cart/show_cart'><img src='/images/product_show_images/check_cart_icon.png' border='0'";
                    if (check_width == 0 || check_width == '0' || check_width == null || typeof(check_width) == undefined)  {
                        check_html +="'/></a>" ;
                    }else {
                        check_html +=" width='" +check_width +"'/></a>" ;
                    }
                    //  alert(check_html);
                    jQuery("#cart_"+dom_id).replaceWith(check_html);
                }
            },
            error: function(){
                jQuery("#shopping_cart_button_" + dom_id).html("error");
            }
        });
    }
}

function put_in_cart_from_direct(product_id){
    source_dom = jQuery("#cart_" + product_id);
    img_width =  jQuery("#shopping_cart_img_"+ product_id).attr("width");
    jQuery.ajax({
        url:'/shopping_cart/put_in_cart',
        type:'post',
        data: "product_id=" + product_id,
        beforeSend: function() {
            jQuery("#cart_" + product_id).html("<img src='/images/loading.gif' />");
        },
        complete: function(XMLHttpRequest){
            var msg = XMLHttpRequest.responseText;           
            jQuery("#img_load_"+product_id).hide();
            if(msg != "" && msg.length > 10) {
                alert(msg);
                jQuery("#shopping_cart_img_"+product_id).show();
            } else {
                refresh_cart_num(msg);
                check_html = "<a href='/shopping_cart/show_cart'>"
                check_html +="<img src='/images/product_show_images/check_cart_icon.png' border='0' width='" +img_width+ "'/></a>" ;
                jQuery("#cart_" + product_id).replaceWith(check_html);
            }
        },
        error: function(){
        }
    });
}

function put_in_cart_from_detail(){
    
    var desc = '';
    desc = getProductDesc();
   
    jQuery("#description").val(desc);
    // alert(jQuery("#cart_form").serialize())
    // return;
    jQuery.ajax({
        url:'/shopping_cart/put_in_cart',
        type:'post',
        data: jQuery("#cart_form").serialize(),
        beforeSend: function() {
            jQuery("#shopping_cart_img").hide();
            jQuery("#img_load").html("<img src='/images/loading.gif' />");
        },
        complete: function(XMLHttpRequest){
            var msg = XMLHttpRequest.responseText;
            //    jQuery("#shopping_cart_button_" + dom_id).html(add_to_cart);
            // alert(msg);
            jQuery("#img_load").hide();
            if(msg != "" && msg.length > 10) {
                alert(msg);                
                jQuery("#shopping_cart_img").show();           
            } else {
                refresh_cart_num(msg);                
                check_html = "<a style='padding-right:0px;' href='/shopping_cart/show_cart'><img src='/images/product_show_images/check_cart_icon.png' border='0'";
                check_html +="'/></a>" ;                              
                jQuery("#shopping_cart_img").replaceWith(check_html);
            }
        },
        error: function(){
            alert("put in cart error!");
        }
    });
}

function refresh_cart_num(cart_num){
    var cart_num_item = jQuery("#cart_num_item");
    cart_num_item.html(cart_num);
    if (cart_num == 0){
        jQuery("#cart_img").attr('src', "/images/head/cart_k.png")
    }else {
        jQuery("#cart_img").attr('src', "/images/head/cart_n.png")
    }
    // alert(cart_num);
    jQuery("#cart_window_num").html(cart_num);      
}


function  load_cart_num(){
    jQuery.ajax({
        url:"/shopping_cart/get_cart_num",
        cache:false,
        success: function(cart_num){
            refresh_cart_num(cart_num);
        }
    });
   
}


function get_off_shelf_product_name(cart_id_string){
    var off_shelf_product_name = ''
    jQuery.ajax({
        url:"/shopping_cart/get_off_shelf_product_name",
        type:"get",
        async:false,
        data:{
            'carts':cart_id_string
        },
        complete: function(XMLHttpRequest){
            off_shelf_product_name = XMLHttpRequest.responseText;
        }
    });
    return off_shelf_product_name;
}

function show_shopping_cart_link(dom_id, product_uuid){
    jQuery.post('/shopping_cart/show_shopping_cart_link', {
        'dom_id':dom_id,
        'uuid':product_uuid
    },function(){},'script');
}

function showCategoryList(){
    jQuery("#category_menu_list").show();
    jQuery("#category_menu_down").hide();
    jQuery("#other_categories").show();
    jQuery("#cate_menu_left").css("height","584px");
    jQuery("#category_menu_list").css("height","584px");
}

//form validate
//id,  id_error_msg
document.write("<style type='text/css'>.bbform_input_border_red{border: 1px solid red;}</style>");
var BBForm = {
    i: 0,

    //text
    textVal: function(id, error_msg) {
        var v = jQuery('#' + id.toString()).val();
        var status = v.match(/^\s*$/);
        BBForm.checkError(id, status, error_msg);
        return v;
    },
    //number
    numVal: function(id, error_msg) {
        var v = jQuery('#' + id.toString()).val();
        var status = v.match(/^[0-9\.]+$/);
        BBForm.checkError(id, !status, error_msg);
        return v;
    },
    //a-zA-Z0-9
    numEngVal: function(id, error_msg) {
        var v = jQuery('#' + id.toString()).val();
        var status = /^[a-zA-Z0-9]+$/.test(v);
        BBForm.checkError(id, !status, error_msg);
        return v;
    },
    //email
    emailVal: function(id, error_msg) {
        var v = jQuery('#' + id.toString()).val();
        var status = v.match(/^[a-zA-Z0-9\.\-\_]+@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]+$/);
        BBForm.checkError(id, !status, error_msg);
        return v;
    },
    //single select
    selectVal: function(id, error_msg, default_value) {
        var s = default_value || '';
        jQuery('#' + id.toString() + ' option').each(function(){
            if(jQuery(this).attr('selected'))
                s = jQuery(this).attr('value');
        })
        var ss = (s == default_value || s == '') ? true : false;
        BBForm.checkError(id, ss, error_msg);
        return s;
    },
    //value length
    lengthVal: function(id, error_msg, len, len2) {
        var v = jQuery('#' + id.toString()).val();
        var v2 = v.replace(/^[\s\n　]+|[\s\n　]+$/g, "");
        var status = (v2.length >= len && v2.length <= len2);
        BBForm.checkError(id, !status, error_msg);
        return v;
    },
    //date 2009-08-23
    dateVal: function(id, error_msg) {
        var v = jQuery('#' + id.toString()).val();
        var status = v.match(/^[1-9][0-9]{3}-[01][12]-[0-3][0-9]$/);
        BBForm.checkError(id, !status, error_msg);
        return v;
    },


    //private
    checkError: function(id, error, error_msg) {
        var e = jQuery('#' + id.toString() + '_error_msg');
        var ei = jQuery('#' + id.toString());
        if(error) {
            BBForm.i++;
            e.html(error_msg);
            BBForm.setBorderColor(ei);
        } else {
            e.html('');
            BBForm.clearBorderColor(ei);
        }
    },
    //set input border color
    setBorderColor: function(e) {
        e.css("border", "1px solid red");
    },
    clearBorderColor: function(e) {
        e.css("border", "1px solid black");
    }
}

//replace email, number
String.prototype.gsub_email_number = function() {
    var source = this;
    source = source.replace(/..@.{4}/g, '*******').replace(/(\d{5})\d+/, '$1***');
    return source;
}


// number format

function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+
        num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + 'USD' + num + '.' + cents);
}

//BeebuyerAD Class
function BeebuyerAd(newAd) {
    //instance variables
    //ads: all position html ids
    //click_link: redirect url, all statistics will do here
    this.ads = [];
    this.click_link = new String();
    
    if(arguments.length > 0)
        this.ads.push(newAd)

    //instance methods//
    //new ad
    this.new_ad = function(position) {
        this.ads.push(position);
        return this;
    };

    //generate ad div
    this.write_ad_html = function(position) {
        document.write('<div style="margin-bottom:5px;display: none;" id="' + position + '"></div>');
        return this;
    };

    //get ad html
    this.getAd = function() {
        if(!window.location.pathname.match(/^\/(c|ct|products|asearch)\/.*/))
            return

        //ajax request
        jQuery.getJSON("/welcome/beebuyer_ad?" + 'ads=' + this.ads.join(',') + '&url=' + window.location,
            function(data) {
                jQuery.each(data.items, function(i, item) {
                    jQuery('#' + item.beebuyer_ad.position).show().html(item.beebuyer_ad.content)
                })
            })
    }
    //ad link click
    this.click = function(c, u) {
        var code = c;   //ad id
        var url = u;    //link url

        var loc  = window.location;
        //jQuery.cookie('beebuyer_ad_track', code);
        window.location = this.click_link + '?url=' + escape(url) + '&code=' + code + '&loc=' + escape(loc);
    }
}
//new ad instance
//also var beebuyer_ad = new BeebuyerAd('id_name');



function check_price() {
    var price_min = jQuery("#search_price_min").val();
    var price_max = jQuery("#search_price_max").val();
    var flag = true;
    if(price_min != undefined && price_min != "") {
        if(price_max != undefined && price_max != "") {
            if(!price_max.match(/^\d+(\.\d+)?$/) || parseFloat(price_max) < parseFloat(price_min)) {
                jQuery("#search_price_max").attr("value", "");
                flag = false;
            }
        }
        if(!price_min.match(/^\d+(\.\d+)?$/) || parseFloat(price_min) < parseFloat(0)){
            jQuery("#search_price_min").attr("value", "");
            flag = false;
        }
    }else {
        if(price_max != undefined && price_max != "") {
            if(!price_max.match(/^\d+(\.\d+)?$/) || parseFloat(price_max) < parseFloat(0)) {
                jQuery("#search_price_max").attr("value", "");
                flag = false;
            }
        }

    }
    if(!flag) {
        return false;
    }
    return true;
}

function cateSearch() {
    if(!check_price()) {
        alert("please check price values");
        return false;
    }

    jQuery('#multi_cond_form').submit();
}
function listOrderChange() {
    cateSearch();
//$A($('sort_select').getElementsByTagName('option')).select(function(i) {
//  if(i.selected && i.value.length != '') {
//    $('sort').value = i.value;
//    cateSearch();
//  }
//})
}


function getProductDesc(){
    var desc = '';
    num = parseInt(tag_size);
    if(num > 0){
        for(var i=0;i<num;i++){
            var value = jQuery("#attr_value_"+i).val();
            var name = jQuery("#attr_name_"+i).html();
            var customize_v = jQuery('#customize_checkbox_'+i);
            if(!customize_v.attr('checked')){
                if(value == 'please-select' || value == ""){
                    alert('please select '+name);
                    desc_flag = true;
                    break;
                }else{
                    desc_flag = false;
                    desc += name;
                    desc += "(";
                    desc += value;
                    desc += ")";
                    if(i != num-1){
                        desc += ","
                    }
                }
            }else{
                var customize_size = jQuery(".attr_num").length;
                for(var k=1;k<=customize_size;k++){
                    var c_length = jQuery("#attr_div_"+k).find(".attr_value").length;
                    for(var j=1;j<=c_length;j++){
                        var a_n = jQuery("#html_name_"+k.toString()+"_"+j.toString()).html();
                        var a_v = jQuery("#html_value_"+k.toString()+"_"+j.toString()).val();
                        desc += a_n ;
                        desc += "(" ;
                        desc += a_v ;
                        desc += ")" ;
                        if(i != num-1){
                            desc += ","
                        }
                    }
                }
            }
        }
    }
    return desc;
}

function get_cart_num(){
    var num = jQuery.cookie("cart_num");
    n = parseInt(num);
    if (isNaN(n)) {
        return 0;
    }else {
        return n;
    }
}

jQuery(document).ready(function(){
    var cart_num_list = new Array("cart_num_item","manage_cart_num","cart_window_num");

    for (var i = 0; i < cart_num_list.length; i++){
        if ( jQuery("#" + cart_num_list[i]).length){
            jQuery("#" + cart_num_list[i]).html(get_cart_num());
        }
    }
    
    var cart_num_item = jQuery("#cart_num_item").html();
    if (cart_num_item == 0){
        jQuery("#cart_img").attr('src', "/images/head/cart_k.png")
    }else {
        jQuery("#cart_img").attr('src', "/images/head/cart_n.png")
    }

    jQuery("#nav_hover").mouseover(function(){
        jQuery("#nav").show();
    })

//    var nav_show_timer;
//    var nav_hide_timer;

    jQuery(".nav_li a").mouseover(function(){
        jQuery(".sub").hide();
        jQuery(this).next().show();

//        clearTimeout(nav_show_timer);
//        clearTimeout(nav_hide_timer);
//        var show_this = this;
//        nav_show_timer = setTimeout(function(){
//            jQuery(show_this).next().show();
//        }, 100);

    })

    jQuery(".nav_li").mouseleave(function(){
         jQuery(".sub").hide();

//        nav_hide_timer = setTimeout(function(){
    //            jQuery(".sub").hide();
    //        }, 100);
       
    })

    jQuery("#beebuyer_logo").mouseover(function(){
        jQuery("#nav").hide();
    })

    jQuery(".nav li a").mouseover(function(){
        jQuery("#nav").hide();
    })
       

    jQuery(".sub").mouseover(function(){
        jQuery(this).show();
        jQuery(this).prev().addClass("sub_hover");
    })

    jQuery(".sub").mouseleave(function(){
        jQuery(this).hide();
        jQuery(this).prev().removeClass("sub_hover");

    })

    jQuery(".b_a").mouseover(function(){
        jQuery(this).next().css('height', '200px').css('top', '100px')
    })

    jQuery("#nav").mouseleave(function(){
        jQuery('#nav').hide();
    })

    jQuery("#nav").mouseover(function(){
        jQuery('#nav').show();
    })
    
    // category nav
    jQuery(".b_a").mouseover(function(){
        jQuery(this).next().css('bottom', '0px').css('top', '100px')
    })
    jQuery(".b_b").mouseover(function(){
        jQuery(this).next().css('bottom', '0px').css('top', '150px')
    })
    jQuery(".b_c").mouseover(function(){
        jQuery(this).next().css('bottom', '0px').css('top', '80px')
    })

});

function btn_img_mouseover(id, img) {
    jQuery(id).mouseover(function(){
        jQuery(this).css("background-image", img)
    })
};
function btn_img_mouseout(id, img) {
    jQuery(id).mouseout(function(){
        jQuery(this).css("background-image", img)
    })
};
function btn_img_mouseup(id, img) {
    jQuery(id).mouseup(function(){
        jQuery(this).css("background-image", img)
    })
};
function btn_img_mousedown(id, img) {
    jQuery(id).mousedown(function(){
        jQuery(this).css("background-image", img)
    })
};

// bottom.js

function recordEmail_b2() {
    jQuery("#sub_button").attr("disabled", "disabled");
    var email = jQuery("#from_bottom").val();
    if(email == "" || email.match(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/) == null){
        alert("wrong E-mail address");
        jQuery("#sub_button").removeAttr("disabled");
        return false;
    } else {
        jQuery("#contact_info_form").submit();
    }  
}
var beebuyer_ad = new BeebuyerAd();
beebuyer_ad.click_link = '/welcome/ad_click';
jQuery(document).ready(function() {    
    beebuyer_ad.getAd();
});

var cart_window_timer;
var category_window_timer;

function show_cart_window() {
    cart_num = parseInt(jQuery("#cart_num_item").text().split(' ')[0]);
    if(cart_num > 0){

        jQuery("#cart_window").show();
        jQuery.ajax({
            url: "/shopping_cart/cart_window_show",
            type: "get",
            cache:false,
            dataType:"html",
            complete: function(XMLHttpRequest, XMLStatus){
                jQuery("#cart_show").html(XMLHttpRequest.responseText);
                jQuery("#sort_select").css("visibility","hidden");
            }
        })
    }
}
function stop_window_timer(){
    clearTimeout(cart_window_timer);
}
function start_window_timer() {
    cart_window_timer = setTimeout("hide_cart_window()", 200);
}
function hide_cart_window() {
    jQuery("#sort_select").css("visibility","visible");
    jQuery("#cart_window").hide();
}

function show_category_window() {
    jQuery("#category_window").show();
}

function stop_category_timer(){
    clearTimeout(category_window_timer);
    show_category_window();
}
function start_category_timer() {
    category_window_timer = setTimeout("hide_category_window()", 200);
}
function hide_category_window() {
    jQuery("#category_window").hide();
}