// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
var TIMEINTER = null ;
var GDS_IDS = null ;//商品刷新id列表
var GDS_DTL = null ;//商品id详情
var RQDATA = null ;//商品取得的数据
var BIDSDT = null ;//出价详细数据
var TLKDT = null ;//商品聊天记录
var TLKSTART = false ;//聊天刷新功能
var TLKRQLOCK = false ;//聊天刷新数据锁定开关，当一个进程请求的时候锁定，禁止其他进程请求
var GDS_DTL_MPC = 0.0;//详细页面商品市场价格
var BUYTIMEREMAIN = null;//商品购买权限倒计时
var GDS_DOMS = null ; // 商品的dom对象缓存

//消息提示全局变量
var NOTIFICATION_DISPLAY = false;
var NOTIFICATION_OBJ = null;
var NOTIF_CURR = 0 ;

var GLOBAL_USER_STATE = null; //静态页面判断用户的登录状态

var Notice = {};

Notice = {
    show: function(eleid,info){
        if($(eleid)){
            $(eleid).html(info);
            $(eleid).show();
            setTimeout(function(){
                $(eleid).fadeOut();
            },1000);
        }
    }
};


//刷新商品信息功能代码
//window.onload = function(){
//    start_get_status();
//};

$(function(){  
    start_get_status();
});

function start_get_status(){
    if(GDS_IDS||GDS_DTL){

      //准备缓存 dom信息
      var gids = GDS_IDS.split(",");
      GDS_DOMS = {} ;
      for(var i=0; i<gids.length; i++){
        GDS_DOMS[ "t_"+gids[i] ] =  $("#gdstime_"+gids[i]) ;
        GDS_DOMS[ "p_"+gids[i] ] =  $("#gdsprice_"+gids[i]) ;
        GDS_DOMS[ "m_"+gids[i] ] =  $("#gdsmember_"+gids[i]) ;
      }
      if(GDS_DTL){
        GDS_DOMS[ "gbt" ] =  $("#goods_bids_table") ;
      }
      // 启动 到表
      TIMEINTER = setInterval("req_goods();",1000);
    }
}

function req_goods(){
    var pars = "";
    //# ids=622,623,625,626,620_dtl=620_lbid=333938_tk=0
    //如果普通列表页面存在值则goods_ids应该存在值
    if(GDS_IDS){
        pars += "_ids="+GDS_IDS ;
    }
    //如果产品详细信息页面则goods_detail应该存在值
    if(GDS_DTL){
        pars += "_dtl="+GDS_DTL;
        lbdid = 0;
        if(BIDSDT){
            lbdid = BIDSDT[0].i;
        }
        pars += "_lbid="+lbdid;
        //处理聊天信息参数
        if( TLKSTART && (!TLKRQLOCK) ){
            ltkid = 0;
            if(TLKDT){
                ltkid = TLKDT[TLKDT.length-1].i;
            }
            pars += "_tk="+ltkid;
        }
    }
    if(pars==""){
        return false;
    }
    else{
        pars = pars.substring(1)
    }
    //	alert(pars);
    //锁定聊天功能
    TLKRQLOCK = true ;
    var url = '/goods_status/' + pars + '?'+ Math.random();
    //  alert(url);
    $.ajax({
        type: "GET",
        url: url,
        dataType: 'json',
        complete: function(data){
            show_goods_bid_info(data);
        }
    });
    return false;
}

function show_goods_bid_info(data){
    o = eval('('+data.responseText+')');
    if(o){
        for(i=0;i<o.g.length;i++){
            GDS_DOMS["t_"+o.g[i].i].text(formate(o.g[i].t));
            if(o.g[i].t<=10){
                GDS_DOMS["t_"+o.g[i].i].css({
                    'color':"#DD0000"
                });
            }else{
                GDS_DOMS["t_"+o.g[i].i].css({
                    'color':"#1E255B"
                });
            }
            if(GDS_DOMS["p_"+o.g[i].i].html()!="¥"+o.g[i].p){
                if(GDS_DOMS["p_"+o.g[i].i].html()!="--"){
                    animate_color(GDS_DOMS["p_"+o.g[i].i],"#ff0000","#ffffff")
                }
                GDS_DOMS["p_"+o.g[i].i].html("¥"+o.g[i].p);
                if(o.g[i].m=="0"){
                    GDS_DOMS["m_"+o.g[i].i].html("<a href=\"#temp\">暂无</a>");
                }
                else{
                    GDS_DOMS["m_"+o.g[i].i].html("<a href=\"#temp\">"+o.g[i].m+"</a>");
                }
                if(GDS_DTL){
                    if(o.g[i].i==GDS_DTL){
                        calc_save_price(o.g[i].p);
                    }
                }
            }
        }
        if(o.b){
            BIDSDT = o.b ; //赋值新的请求对象数据
            var bids_html = "" ;
            var ass = "";
            var if_free = "";
            for(i=0;i<o.b.length;i++){
                ass = o.b[i].a==0 ? "普通出价" : "有拍秘书"
                if_free = o.b[i].f == 0 ? "nf_bid_price":"f_bid_price";
                bids_html += '<tr><td>'+o.b[i].m+"</td><td><span class="+if_free+">¥"+o.b[i].p+'</span></td><td>'+ass+'</td></tr>'
            }
            bids_html = '<table><tr class="title"><td class="ta">出价人</td><td class="tb">价格</td><td class="tc">出价方式</td></tr>'
            +bids_html+'</table>';
            if(GDS_DOMS[ "gbt" ])
                GDS_DOMS[ "gbt" ].html(bids_html);
        }
        if(o.t){
            var lts_tk_id = 0;
            if(TLKDT){
                lts_tk_id = TLKDT[TLKDT.length-1].i
            }
            if(o.t[0].i>lts_tk_id){
                TLKDT = o.t ;//赋值新的聊天数据对象
                var talk_html = "";
                for(i=0;i<o.t.length;i++){
                    talk_html += '<li id="tkmsg_'+o.t[i].i+'"><span>'+o.t[i].m+'</span>:'+o.t[i].s+'</li>';
                }
                var tk_el = $("#talk-msg-list") ;
                if(tk_el){
                    tk_el.innerHTML += talk_html;
                    //$('tkmsg_'+o.t[o.t.length-1]).focus();
                    //alert($("talk-list").scrollHeight);
                    $("#talk-list").scrollTop = $("#talk-list").scrollHeight;
                }
            }
        }
        //解除聊天刷新锁
        TLKRQLOCK = false ;
    }
//	alert(str);
}


//计算节省价格，并更新相关数据
function calc_save_price(curr_price){
    if(!GDS_DTL){
        return;
    }
    $("#gds_curr_price_"+GDS_DTL).html("¥"+curr_price);
    $("#gds_save_price_"+GDS_DTL).html("¥"+( GDS_DTL_MPC - Number(curr_price) ).toFixed(2));
}

//计算出价返还的钱数并更新 计算最终购买的价格并更新
function calc_buy_price(bids_return){
    if(!GDS_DTL){
        return;
    }
    $("bids_return_money").html("-¥"+Number(bids_return).toFixed(2));
    $("buy_total_case").html("¥"+(GDS_DTL_MPC - Number(bids_return)).toFixed(2));
}

function formate(time_length){
    var hour = time_length/3600|0;
    var min = (time_length%3600)/60|0;
    var sec = (time_length%3600)%60;
    if(hour<10){
        hour = "0"+hour;
    }
    if(min<10){
        min = "0"+min;
    }
    if(sec<10){
        sec = "0"+sec;
    }
    return hour+":"+min+":"+sec;
}


function MM_preloadImages() { //v3.0
    var d=document;
    if(d.images){
        if(!d.MM_p) d.MM_p=new Array();
        var i,j=d.MM_p.length,a=MM_preloadImages.arguments;
        for(i=0; i<a.length; i++)
            if (a[i].indexOf("#")!=0){
                d.MM_p[j]=new Image;
                d.MM_p[j++].src=a[i];
            }
    }
}

/*
 * Added by  backer
 * Desc: move prototype to jquery use jump price_color
 *
 **/
function animate_color(dom,from,to){
    $(dom).css("backgroundColor",from);
    $(dom).animate({
        "backgroundColor":to
    },900);
}

/* remove hot relation goods */
function remove_hot_goods(){
    var __temp_remove = $("#goods_rel_li_id_"+GDS_DTL);
    if(__temp_remove.size() > 0){
        __temp_remove.remove();
    }else{
        $("#goods_rel li:last-child").remove();
    }
}

/* show category js */
$(function(){
    /* show category */
    $("#category").find("h5 > a").click( function(){
        if( $("#category").find(".category_list").css("display")=="none"){
            $("#category").find(".category_list").slideDown(200);
        }else{
            $("#category").find(".category_list").slideUp(200);
        }
    });

    /* show news and winner_share */
    $("#h_winner_share").click(function(){
        $("#index_ws_part").show();
        $("#index_notice_part").hide();
        $("#h_winner_share").parent().addClass("curr");
        $("#h_public_notice").parent().removeClass("curr");
    });

    $("#h_public_notice").click(function(){
        $("#index_ws_part").hide();
        $("#index_notice_part").show();
        $("#h_winner_share").parent().removeClass("curr");
        $("#h_public_notice").parent().addClass("curr");
    });

    if ($("#notice_wrap > h5").html()){
        $("#notice_wrap").addClass("notice_wrap");
        $("#notice_wrap").fadeIn().delay(3000).fadeOut();
    }

    /*show focus play*/
    Play("#play", 3000);
    function Play( o , ms )
    {
        var obj = $(o);
        var ul_lis = obj.find("ul > li");
        var ol_lis = obj.find("ol > li");
        var p      = obj.find("p");
        var timer;
        var num    = 0;

        auto();
        function auto()
        {
            timer = setInterval(function(){
                num++;
                if( num >= ul_lis.length ){
                    num = 0;
                };

                ul_lis.fadeOut();
                ul_lis.eq(num).fadeIn();
                ol_lis.attr("class","");
                ol_lis.eq(num).attr("class","active");
                p.html( ol_lis.eq(num).attr("title"));

            }, ms);
        };

        obj.find("ul").hover(function(){
            clearInterval(timer);
        },function(){
            auto();
        });
        obj.find("ol").hover(function(){
            clearInterval(timer);
        },function(){
            auto();
        });

        ol_lis.click(function(){
            num = ol_lis.index(this);
            ul_lis.fadeOut();
            ul_lis.eq(num).fadeIn();
            ol_lis.attr("class","");
            ol_lis.eq(num).attr("class","active");
            p.html( ol_lis.eq(num).attr("title"));
        });
    };

    /**
     * created by zhang qign hua
     * orders display function
     **/
    var headline_count;
    var headline_interval;
    var old_headline = 0;
    var current_headline = 0;

    headline_count = $("#winner_info_scroll>p").size();
    $("#winner_info_scroll>p:eq("+current_headline+")").css('top', '-20px');

    headline_interval = setInterval(headline_rotate,3000);

    $('#winner_info_down').hover(function() {
        clearInterval(headline_interval);
    }, function() {
        headline_interval = setInterval(headline_rotate,3000);
        headline_rotate();
    });

    $('#inner_info_list').hover(function() {
        clearInterval(headline_interval);
    }, function() {
        headline_interval = setInterval(headline_rotate,3000);
        $("#winner_info_list").slideUp(300);
        headline_rotate();
    });

    function headline_rotate() {
        current_headline = (old_headline + 1) % headline_count;
        $("#winner_info_scroll>p:eq(" + old_headline + ")")
        .animate({
            top: -20
        },"slow", function() {
            $(this).css('top', '20px');
        });
        $("#winner_info_scroll>p:eq(" + current_headline + ")")
        .animate({
            top: 0
        },"slow");
        old_headline = current_headline;
    }


    /* show winner info */
    $("#winner_info_down").click(function(){
        if( $("#winner_info_list").css("display")=="none"){
            $("#winner_info_list").slideDown(200);
        }else{
            $("#winner_info_list").slideUp(200);
        }
    });

    /**
     * Loading user's personal data from  server
     *
     **/
    $("#loading").bind("ajaxSend", function(){
        $(this).show();
    }).bind("ajaxComplete", function(){
        $(this).hide();
    });
    $.ajax({
        url: '/member_status',
        type: 'GET',
        dataType: 'html',
        error: function(data){
        },
        success: function(data){
            $("#member_status").html(data);
            if($("#v_points").html()!= null){
                GLOBAL_USER_STATE = true;
            }
            else
            {
                GLOBAL_USER_STATE = false ;
            }
        }
    })
});

function on_biding_button_mouseout(goods_id){
    $("#biding_buttons_"+goods_id).html("出 价");
}

function on_biding_button_mouseover(goods_id){
    if (GLOBAL_USER_STATE == null) return ;
    if (!GLOBAL_USER_STATE){
        $("#biding_buttons_"+goods_id).html("登 录");
        $("#biding_buttons_"+goods_id ).click(function()
        {
            window.location = "/login";
            return false;
        })
    }
}
/*
 * Added by  zhang qing hua
 * Desc: load a user's activity details
 *
 **/

function  load_activites(){
    if (get_cookie('activities_required') == '1'){
        $.ajax({
            url: '/main/activity_list',
            type: 'GET',
            dataType: 'html',
            error: function(data){
                fail_func(data);
            },
            success: function(data){
                display_notifications(data);
            }
        });
    }
}

/*
 * 更新已经看多的通知
 *
 **/

function expire_notifications(){
    $.ajax({
        url: '/main/expire_activities',
        type: 'GET',
        success: function(data){
            close_notification_bar(data);
        }
    });
}

// 显示消息的通知，并设定超时
function  display_notifications(response){
    var noti_string = response;
    NOTIFICATION_OBJ = jQuery.parseJSON(noti_string);
    if( NOTIFICATION_OBJ.length >0){
        NOTIF_CURR = 0;
        //alert(obj.length);
        var noti_content = $("#notification_content");
        noti_content.html("<span class=\"" + NOTIFICATION_OBJ[0].message.style + "\"></span>" + NOTIFICATION_OBJ[0].message.description + "");
        var notification_var = $("#notification_bar");
        notification_var.hide();
        notification_var.slideDown();
        NOTIFICATION_DISPLAY  = true;
        setTimeout(notification_time_out,4000*NOTIFICATION_OBJ.length);
        __noti_next_hand = setInterval(display_next,4000);
    }
}


var __noti_next_hand = null;

function display_next(){
    __curr = NOTIF_CURR+1;
    if(__curr>NOTIFICATION_OBJ.lenght-1){
        __curr = 0;
        __noti_next_hand = null;
        return false;
    }
    NOTIF_CURR = __curr ;
    var noti_content = $("#notification_content");
    if(noti_content){
        noti_content.html("<span class=\"" + NOTIFICATION_OBJ[__curr].message.style + "\"></span>" + NOTIFICATION_OBJ[__curr].message.description + "");
    }
}

function notification_time_out(){
    if(NOTIFICATION_DISPLAY){
        $('#notification_bar').slideUp();
    }
}

function fail_func(response){
    $('#notification_bar').hide();
}

function close_notification_bar(){
    $('#notification_bar').slideUp();
    NOTIFICATION_DISPLAY = false ;
}

function get_cookie( name ) {
    var start = document.cookie.indexOf( name + "=" );
    var len = start + name.length + 1;
    if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
        return null;
    }
    if ( start == -1 ) return null;
    var end = document.cookie.indexOf( ';', len );
    if ( end == -1 ) end = document.cookie.length;
    return unescape( document.cookie.substring( len, end ) );
}

function trim(s)
{
    var l=0;
    var r=s.length -1;
    while(l < s.length && s[l] == ' ')
    {
        l++;
    }
    while(r > l && s[r] == ' ')
    {
        r-=1;
    }
    return s.substring(l, r+1);
}
/*
 * end
 *
 **/
