/**
 +----------------------------------------------------------
 * 判断页面是否存在某个ID
 +----------------------------------------------------------
*/
jQuery.getid = function(id)
{
    return document.getElementById(id) != null;
};

/**
 +----------------------------------------------------------
 * 判断是否IE6
 +----------------------------------------------------------
*/
jQuery.ie6 = $.browser.msie && $.browser.version < 7;


/**
 +----------------------------------------------------------
 * 图片轮播插件
 * timer : 执行时间
 * speed : 切换速度
 +----------------------------------------------------------
*/
jQuery.HolaSlide = function(timer,speed)
{
    timer = timer || 2000;
    speed = speed || 600;

    var $img        = $('#ad_slide_img li'),
        $num        = $('#ad_slide_num>li'),
        count       = $img.size(),
        index       = 0,
        cTime;

    // 图片轮播
    var slidePlay = function(i)
    {
        $num.eq(i).addClass('on').siblings().removeClass('on');
        $img.eq(i).fadeIn(speed).siblings().fadeOut(speed);
    };

    // 首次打开页面执行
    if (!cTime)
    {
        slidePlay(0);
    }

    // 索引初始化
    var slideInit = function()
    {
        slidePlay(index);
        index++;
        if(index == count)
        {
            index = 0;
        }
    };

    // 自动播放
    cTime = setInterval(slideInit,timer);

    // 鼠标移动到数字事件
    $num.hover(
        function()
        {
            if(cTime)
            {
                clearInterval(cTime);
            }

            index  = $num.index(this);

            cTime = setTimeout(function(){
                $img.stop();
                slidePlay(index);
            } , 400);
        },
        function()
        {
            clearInterval(cTime);
            cTime = setInterval(slideInit, timer);
        }
    );

    // 鼠标移动到图片事件
    $img.hover(
        function()
        {
            if(cTime)
            {
                clearInterval(cTime);
            }
        },
        function()
        {
            cTime = setInterval(slideInit, timer);
        }
    );
};

/**
 +----------------------------------------------------------
 * 底部弹出层插件
 +----------------------------------------------------------
*/
$.fn.HolaBar = function()
{
    var _this  = this,
        barH   = _this.outerHeight(true),
        $tab   = $('.bar_tab a',_this),
        $ctrl  = $('.bar_ctrl a',_this),
        $wrap  = $('#bar_content'),
        $box   = $('.bar_box','#bar_content'),
        $left  = $('.bar_left','#bar_content'),
        $right = $('.bar_right','#bar_content'),
        $list  = $box.children('.bar_list'),
        $car   = $('#shop_car_max'),
        isShow = false;

    // 仅对ie6有效 解决ie6下select标签不能遮盖的bug
    // 底部弹出层放置的页面以一屏为计，拖到最顶层时屏幕下方如果包含有select，请去掉相关注释
    // 否则请保留注释，以免影响执行效率
    if ($.ie6)
    {
        _this.css('position','absolute');

        /* -------修正select bug 开始------去掉此行----
        var $iframe = $('<iframe class="ie6mask" src="javascript:;" frameBorder=0></iframe>');
        $iframe.css({
            display : 'block',
            position: 'absolute',
            filter  : 'alpha(opacity=0)',
            width   : '100%',
            height  : barH+'px',
            left    : 0,
            top     : getTop(_this)+'px',
            zIndex  : _this.css('z-index')-1
        }).appendTo('body');
        -----------修正select bug 结束-------去掉此行------ */

        // 弹出层置底
        $(window).scroll(function(){

            _this.css( 'top' , getTop() );

            /* -------修正select bug----去掉此行------
            $iframe.css({top:getTop()+'px',height:barH});
            ----------去掉此行-------------- */
        });
    }

    $('#shop_car').find('li').each(function() {
        $('<span>关闭</span>').appendTo(this).bind('click',function(){
            $(this).parent('li').remove();
        });
    });

    // 展开收缩控制
    $ctrl.click(function(){
        $ctrl.blur();
        box_play(0);
        return false;
    });

    // tab控制
    $tab.each(function(i) {

        $(this).bind('click',function(){

            $(this).blur();

            if (!isShow)
            {
                box_play(i);
            }

            shop_car(i);

            $(this).parent().addClass('on').siblings().removeClass('on');
            $list.eq(i).fadeIn().siblings().fadeOut();
        });
    });

    // 各个tab的记录数量获取及滚动
    $list.each(function(i) {

        var $ul     = $(this).children('ul'),
            $li     = $ul.children('li'),
            count   = $li.size();

        $tab.eq(i).children('span').html(count);

        // 当记录个数超过8个时允许点击滚动
        if (i == 0 && count > 6 || count > 8)
        {
            // 向左滚动
            $right.bind('click',function(){
                $ul.animate(
                    {left:'-118px'},
                    {duration:200,complete:function(){
                        $ul.append($ul.find('li:first'));
                        $ul.css('left','0');
                    }}
                );
            });

            // 向右滚动
            $left.bind('click',function(){
                $ul.find('li:last').clone().prependTo($ul);
                $ul.css('left','-118px');
                $ul.animate(
                    {left:0},
                    {duration:200,complete:function(){
                        $ul.find('li:last').remove();
                    }}
                );
            });
        }

    });

    // ie6下获取滚动高度
    function getTop()
    {
        return $(window).scrollTop() + $(window).height() - barH;
    }

    // 盒子弹出与隐藏动画
    function box_play(n)
    {
        n = n || 0;
        isShow = !isShow;
        shop_car(n);

        if (isShow)
        {
            $ctrl.addClass('down').attr('title','收起').html('收起');

            $tab.eq(n).parent().addClass('on');

            $list.eq(n).fadeIn().siblings().fadeOut();
        }
        else
        {
            $ctrl.removeClass('down').attr('title','展开').html('展开');

            $tab.parent().removeClass('on');

            $list.fadeOut();
            $car.hide();
        }

        $wrap.slideToggle('slow',function(){
            if ($.ie6)
            {
                barH = _this.outerHeight(true);

                _this.animate({top:getTop()},500);

                /* -------修正select bug----------
                $iframe.css({top:getTop()+'px',height:barH});
                --------------------------------- */
            }
        });
    }

    function shop_car(i)
    {
        if(i == 0)
        {
            $car.show();
            $right.css('right','238px');
        }
        else
        {
            $car.hide();
            $right.css('right','0');
        }
    }

};

/**
 +----------------------------------------------------------
 * 单品页面展示专用
 * 放大镜显示
 * 小图片滚动及鼠标移到小图显示大图
 +----------------------------------------------------------
 * 参数设为ture或1或任何字符，会对小图列表对应的大图进行预加载
 +----------------------------------------------------------
*/

jQuery.goods_summary_init = function(cache)
{
    var $big  = $('#goods_img_big'),        // 左侧大图层
        $img  = $big.children('img'),       // 左侧大图
        $ul   = $('#goods_img_list ul'),    // 小图容器
        count = $ul.children().size(),      // 小图列表个数
        maxW  = Math.ceil(count*0.2)*360,   // 小图列表总宽度(个数*72/360)*360
        $move = $('#zoom_move'),            // 放大镜指示层
        $view = $('#zoom_view'),            // 放大镜显示层
        v = {                               // 变量寄存器
            bigL  : $big.offset().left,
            bigT  : $big.offset().top,
            x     : 0,
            y     : 0,
            moveW : 50,
            moveH : 50,
            alt   : ''
        };

    /* 动态预处理及预载大图片 */
    $ul.css('width',maxW+'px');

    $('#goods_img_small').children('p').addClass('no');

    set_zoom_img($img.attr('bigimgsrc'),$img.attr('alt'));

    $move.css('opacity','0.5');


    /* 小图左右移动及显示大图 */
    if (count > 5 )
    {
        var $left  = $('#ctrl_l'),
            $right = $('#ctrl_r'),
            _left  = 0;

        $right.removeClass('no');

        // 往左滚动处理
        $left.hover(function(){

            if(!_left)
            {
                return;
            }

            setTimeout(function(){
                _left = parseFloat($ul.css('left'))+360;
                _left = _left > 0 ? 0 : _left;

                $(this).removeClass('no');

                if(_left == -maxW + 360)
                {
                    $right.addClass('no');
                }
                else
                {
                    $right.removeClass('no');
                }

                $ul.animate(
                    {left:_left+'px'},
                    {duration:800,complete:function(){
                        if(!_left)
                        {
                            $left.addClass('no');
                        }
                    }}
                );
            },20);
        });

        // 向右滚动处理
        $right.hover(function(){

            if(_left-360 == -maxW)
            {
                return;
            }

             setTimeout(function(){
                _left -= 360;
                $ul.animate(
                    {left:_left+'px'},
                    {duration:800,complete:function(){
                        $left.removeClass('no');
                        if(_left == -maxW + 360)
                        {
                            $right.addClass('no');
                        }
                    }}
                );
             },20);
        });
    }

    /* 鼠标移到到小图显示大图 */
    $ul.children().each(function(i) {

        var $_this= $(this),
            $_img = $_this.find('img'),
            _src  = $_img.attr('src'),
            _alt  = $_img.attr('alt'),
            _bimg = $_img.attr('imgbig');

        /* 缓存所有大图 */
        if(cache)
        {
            $('<div style="display:none"><img src="'+_src+'" alt="" /><img src="'+_bimg+'" alt="" /></div>').appendTo(this);
        }

        // 事件绑定
        $_this.bind('mouseover',function(){
            setTimeout(function(){

                $_this.addClass('on').siblings().removeClass('on');

                $img.attr({
                    src: _src,
                    alt: _alt,
                    bigimgsrc: _bimg
                });

                set_zoom_img(_bimg,_alt);

            },20);

            //return false;
        });
    });

	/* 放大镜显示 */
    $big.bind('mouseenter',function(e){

        if($.ie6){ $('#ie6select select').hide(); }

        $view.show();

        var $this  = $(this),
            $bimg  = $view.children('img');

        v.w   = $bimg.get(0).offsetWidth;
        v.h   = $bimg.get(0).offsetHeight;
        v.alt = $bimg.attr('alt');

        $bimg.attr('alt','');

        // 放大镜指示层大小计算
        $move.css({
            width : (v.moveW = parseFloat(120000/v.w)) +'px',
            height: (v.moveH = parseFloat(120000/v.h)) +'px'
        }).show();

		// 首次预处理
        toZoom(e.pageX, e.pageY);

		// 鼠标移动处理
        $this.bind('mousemove',function(e){
			setTimeout(function(){
				toZoom(e.pageX,e.pageY);
			},10);
		});

	}).bind('mouseleave',function(){

        $view.hide().children('img').attr('alt',v.alt);

        $move.hide();

        if($.ie6){ $('#ie6select select').show();}

        $(this).unbind('mousemove');
	});

	/* 放大镜显示 */
    function toZoom(x,y)
    {
		v.x =  x - v.bigL - v.moveW/2;
		v.y =  y - v.bigT - v.moveH/2;

        if(v.x < 0) { v.x  =  0; }
        if(v.y < 0) { v.y  =  0; }

        if( v.x + v.moveW >= 400 )
        {
			v.x  = 400 - v.moveW;
		}

        if( v.y + v.moveH >= 400)
        {
			v.y  = 400 - v.moveH;
		}

		$move.css({left: v.x, top: v.y});

        $view.children('img').css({
            left : - v.x * parseFloat(v.w/400),
            top  : - v.y * parseFloat(v.h/400)
        });
	}


    /* 设置大图 */
    function set_zoom_img(src,alt)
    {
        $view.html('<img src="'+src+'" alt="'+alt+'" />');
    }

};


/**
 +----------------------------------------------------------
 * 购买数量控制插件
 +----------------------------------------------------------
*/
jQuery.fn.buy_count = function(options)
{
    if (!this)
    {
        return;
    }

    return this.each(function() {
        /* 可用设置 */
        var opt = {
            input:'.text',                  // 数值显示input的id或class
            del:'.count_del',               // 减少按钮
            add:'.count_add',               // 增加按钮
            min:1,                          // 最小值
            max:9999,                       // 最大值
            step:1                          // 步进或步减值
        };

        if (options)
        {
            opt = $.extend(opt,options);
        }

        var $del = $(opt.del,this),
            $add = $(opt.add,this),
            $val = $(opt.input,this);

        // 增加
        $add.bind('click',function(){
            var num = $val.val();
            if (num < opt.max)
            {
                $val.val(parseFloat(num)+opt.step);
            }
        });

        // 减少
        $del.bind('click',function(){
            var num = $val.val();
            if (num > opt.min)
            {
                $val.val(parseFloat(num)-opt.step);
            }
        });
    });
};

/**
 +----------------------------------------------------------
 * POP弹出层插件
 * 仅支持产品信息弹出 及 提示信息弹出
 +----------------------------------------------------------
 * 产品弹出使用onclick="$.Holapop({属性1:设置值，属性2:设置值....});"
 * 具体属性对应内容请参考变量opt的注释
 + ---------------------------------------------------------
 * 信息提示的使用，在判断需要弹出后，直接调用$.Holapop('html模板')则可
 * 内置设定了h5标题样式及p标签分段样式。例如：
   if(条件成立)
   {
       $.Holapop('<h5>信息提示标题</h5><p>信息提示内容</p>');
   }
 * 若不使用内置样式，可自定义模板内容，直接在模板中添加样式
 * 需注意参数中对模板的引号使用，以免产生html自身的影响
 +----------------------------------------------------------
*/

$.Holapop = function(settings)
{
    /* 信息提示处理 */
    if (typeof settings == 'string')
    {
        box_show('<div class="p_tips">'+settings+'</div>');
    }
    else
    {
        /* 请自行根据项目需要添加默认值 */
        var opt = $.extend(true,{
                /* 产品设置 */
                img     : '', // 产品图片
                alt     : '', // 图片alt属性
                title   : '', // 产品标题
                price   : '', // 产品价格
                pic     : '', // 产品单位
                number  : '', // 产品编号
                intro   : '', // 产品简介
                spec    : '', // 产品相关规格选择，多个以逗号分开
                color   : '', // 产品颜色选择
                favorite: '', // 添加到收藏夹的url
                href    : '', // 立即购买的url
                /* 其它默认设置 */
                _this     : null,    // 如果设置了该属性，则会缓存数据模板，可加快速度
                action    : '',      // form的action属性要填的内容 请自行设
                method    : 'get',   // form的method属性要填的内容 请自行设
                name      : '',      // form的name属生要填的内容 请自行设
                specName  : 'spec',  // 默认规格选择(select标签)的name和id名称(用户体验需要)
                colorName : 'color', // 默认颜色选择(select标签)的name和id名称(用户体验需要)
                showCall  : null,    // 弹出层显示后的回调函数，例如要对点击立即购买绑定事件
                removeCall: null     // 关闭弹出层时的回调函数
         },settings);

        // 缓存该产品内容模板
        var tpl_cache = opt._this && $(opt._this).data('hola_pop') || null;

        if (!tpl_cache)
        {
            opt.spec  = build_option(opt.spec);
            opt.color = build_option(opt.color);

            // 创建内容模板
            tpl_cache = '<dl class="p_goods_l"><dt><img src="'+opt.img+'" alt="'+opt.alt+'" /></dt><dd><em>￥'+opt.price+'/'+opt.pic+'</em></dd><dd><p class="favorite_link"><a href="'+opt.favorite+'" title="加入收藏夹">加入收藏夹</a></p></dd><dd><a href="'+opt.href+'" title="购买" class="btn btn_shop_small">立即购买</a></dd></dl><dl class="p_goods_r"><dt>'+opt.title+'</dt><dd>商品编号 '+opt.number+'</dd><dd class="p_goods_intro">'+opt.intro+'</dd><dd><form action="'+opt.action+'" method="'+opt.method+'" name="'+opt.name+'"><div class="goods_buy_count"><p><label for="">数量</label></p><p class="count_del"><span class="icon_ctrl">减1</span></p><p><input name="" type="text" class="text" value="1" /></p><p class="count_add"><span class="icon_ctrl">加1</span></p></div><div class="c"><label for="hola_'+opt.specName+'">规格</label><select name="'+opt.specName+'" id="hola_'+opt.specName+'"><option value="">请选择</option>'+opt.spec+'</select></div><div><label for="hola_'+opt.colorName+'">颜色</label><select name="'+opt.colorName+'" id="hola_'+opt.colorName+'"><option value="">请选择</option>'+opt.color+'</select></div></form></dd></dl>';

            // 如果设置了a对象
            if (opt._this)
            {
                $(opt._this).parent('li').data('hola_pop',tpl_cache);
            }
        }

        box_show(tpl_cache,opt);
    }

    /* 弹出层显示 */
    function box_show(tpl,conf)
    {
        // 创建pop基本架构
        var $pop = $('<div class="pop" id="pop"><p class="p_top"></p><div class="p_wrap"><div class="p_body">'+tpl+'</div><a href="javascript:void(0);" title="关闭" class="p_close">关闭</a></div><p class="p_btm"></p></div>').css('top',get_top()).appendTo('body');

        // ie6下修正
        if($.ie6)
        {
            $('#orders').hide();
        }

        $pop.slideDown(500);

        // 加减数值事件绑定
        $('.goods_buy_count','#pop').buy_count();

        // 弹出层显示后回调函数绑定
        if(conf && conf.showCall && $.isFunction(conf.showCall))
        {
            conf.showCall();
        }

        // 关闭事件
        $('.p_close','#pop').unbind('click.Holapop').bind('click.Holapop',function(){

            $pop.slideUp(300,function(){

                if(conf && conf.removeCall && $.isFunction(conf.removeCall))
                {
                    conf.removeCall();
                }

                if($.ie6)
                {
                    $('#orders').show();
                }

                $pop.remove();
            });

            return false;
        });
    }

    /* 创建option 模板 */
    function build_option(obj)
    {
        var _tpl = '';
        $.each(obj,function(i,n) {
            _tpl += '<option value="'+i+'">'+n+'</option>';
        });
        return _tpl;
    }

    /* 获取top值 */
    function get_top()
    {
		var de = document.documentElement,t;

        t = de && de.scrollTop  || document.body.scrollTop;

        return t + parseFloat($(window).height()/4) +'px';
	}

};

/**
 +----------------------------------------------------------
 * 弹出关闭注册协议
 +----------------------------------------------------------
*/
jQuery.HolaAgree = function(isShow)
{
    var $agree = $('#agree');

    if(isShow)
    {
        $agree.fadeIn('slow');
    }
    else
    {
        $agree.fadeOut('slow');
    }
    return false;
};

/* 焦点事件 */
jQuery.fn.focus_ctrl = function()
{
      return this.each(function() {

            var defaults = this.value;

            $(this).focus(function(){
                if(this.value == defaults)
                {
                    this.value = '';
                }
            }).blur(function(){
                if(this.value == '')
                {
                    this.value = defaults;
                }
            });

      });
};

/* 主题馆产品左右移动 */
jQuery.fn.HolaMoveGoods = function()
{
    var $this = $(this),
        $left = $this.find('p.show_l>span'),
        $right= $this.find('p.show_r>span'),
        $ul   = $this.find('ul'),
        $li   = $ul.children('li'),
        outerW= $li.outerWidth(true),
        count = $li.length;

    $ul.css('width',(count+1)*outerW+'px');

    // 向左滚动
    $right.bind('click',function(){
        $ul.animate(
            {left:'-'+outerW+'px'},
            {duration:200,complete:function(){
                $ul.append($ul.find('li:first'));
                $ul.css('left','0');
            }}
        );
    });

    // 向右滚动
    $left.bind('click',function(){
		$ul.find('li:last').clone().prependTo($ul);
		$ul.css('left','-'+outerW+'px');
        $ul.animate(
            {left:0},
            {duration:200,complete:function(){
                $ul.find('li:last').remove();
            }}
        );
    });

};

/* 导航 主题馆下拉 */
jQuery.fn.Hola_submenu = function(ie6)
{
    if (!this) { return;}

    var $this  = $(this),
        suffix = ie6? '.gif' : '.png',
        ie6bug = ie6 && $.getid('address_table');

    $this.hover(
        function()
        {
            $this.css({background:'url(./images/submenu'+suffix+') no-repeat'});

            $this.children('div').css({
                background:'url(./images/submenu'+suffix+') no-repeat 0 100%'
            }).slideDown(300);

            if(ie6bug)
            {
                $('#address_table').find('select').hide();
            }
        },
        function()
        {
            if(ie6bug)
            {
                $('#address_table').find('select').show();
            }

            $this.children('div').slideUp(300,function(){
                $this.css({background:'none'});
            });
        }
    );
};

/**
 +----------------------------------------------------------
 * 页面就绪事件绑定
 +----------------------------------------------------------
*/
jQuery(document).ready(function(){

    /* 主题馆下拉菜单 */
    $('#nav_submenu').Hola_submenu($.ie6);

    /* 图片轮播绑定 */
    if ($.getid('ad_slide'))
    {
        $.HolaSlide(2000);
    }

    /* 购买数量加减 */
    $('.goods_buy_count').buy_count();

    /* 产品快速查看按钮ie6修正 */
    if ($.ie6)
    {
        if ($.getid('goods_list') || $.getid('show_goods'))
        {
            $('#goods_list>li,#show_goods .show_goods_list>ul>li').each(function() {
                var $btn = $(this).children('a.btn_view');
                $(this).hover(
                    function()
                    {
                        $btn.show();
                    },
                    function()
                    {
                        $btn.hide();
                    }
                );
            });
        }
    }

    /* 单品展示 */
    if ($.getid('goods_summary'))
    {
        $.goods_summary_init();//需要缓存加参数true
    }

    /* 底部弹出层 */
    if ($.getid('bar'))
    {
        $('#bar').HolaBar();
    }

    /* 索取发票 */
    if($.getid('need_invoice'))
    {
        $('#need_invoice').click(function(){
            var $this = $(this),
                $invoice = $this.parent().next('ul');
            if($this.is(':checked'))
            {
                $invoice.show();
            }
            else
            {
                $invoice.hide();
            }
        });
    }

    /* 搜索提示文字焦点事件 */
    $('input.text_bg').focus_ctrl();

    /* dm hover事件 */
    if($.getid('dm_list'))
    {
        $('#dm_list>li').each(function() {
            $(this).hover(
                function()
                {
                   $(this).css('background-position','-462px -360px');
                },
                function()
                {
                    $(this).css('background-position','0 -360px');
                }
            );
        });
    }

    /* 主题馆产品列表左右移动 */
    if($.getid('show_goods'))
    {
        $('.show_box','#show_goods').each(function() {
            $(this).HolaMoveGoods();
        });
    }

});