// +----------------------------------------------------------------------
// | Lohas Metro.com 乐活都市网
// +----------------------------------------------------------------------
// | Copyright (c) Metroer.com All Rights Reserved.
// +----------------------------------------------------------------------
// | Author: ThinkPHP liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$

(function($){

    /* 是否存在id */
    $.getid = function(id)
    {
        return document.getElementById(id) != null;
    };

    /**
     +----------------------------------------------------------
     * 搜索 焦点控制 增强用户体验
     +----------------------------------------------------------
    */
    $.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;
                    }
                });
          });
    };

    /**
     +----------------------------------------------------------
     * 页面滚动 增强用户体验
     +----------------------------------------------------------
    */
    $.scroll_to = function(_to,diff)
    {
        _to = _to && typeof _to == 'string' && ( $('#'+_to).offset().top - (diff || 15) ) || _to || 0;
        $('html,body').animate({scrollTop : _to},750);
    };

    /**
     +----------------------------------------------------------
     * 搜索
     +----------------------------------------------------------
    */
    $.fn.Tosearch = function()
    {
        var $this     = $(this),
            $sel      = $('select',this),
            $p        = $this.find('p'),
            $ul       = $this.find('ul');

        // 根据select设置默认的搜索类型
        $p.html($('select option:selected',this).html());

        // 下拉动画
        $('.nav_select',this).hover(
            function(){ul_play();},
            function(){ul_play(1);}
        );

        // 关键词输入
        $('input.nav_text',this).focus_ctrl();

        // 选择处理
        $ul.find('a').each(function() {
            var _this = $(this);
            _this.bind('click',function(){
                $p.html(_this.html());
                $sel.val(_this.attr('rel'))
                ul_play(1);
            });
        });

        // 下拉菜单显示与隐藏
        function ul_play(up)
        {
            up ? $ul.slideUp(300) : $ul.slideDown(400);
        }

    };// 搜索控制 end

    /**
     +----------------------------------------------------------
     * 活动模块轮播
     +----------------------------------------------------------
    */
    $.fn.ActSlide = function(time)
    {
        if(!this){ return;}

        return this.each(function() {

            var $this = $(this),
                $div  = $this.children('div'),
                $ul   = $div.children('ul'),
                $li   = $ul.children('li'),
                count = $li.length,
                $h    = $this.children('h3');

            // 首页需要显示标题
            if($h.length)
            {
                set_title(0);
            }

            // 填充标题内容
            function set_title(i)
            {
                var $a = $li.eq(i).children('a').get(0);
                $h.html('<a href="'+$a.href+'" title="'+$a.title+'">'+$a.title+'</a><span>'+$a.rel+'</span>');
            }

            // 当li只有一个时，就此88
            if(count < 2) { return; }

            // 生成模板内容
            var _html = '',$span = $('<span></span>');

            for(var i=1; i<=count; i++)
            {
                _html += '<a href="javascript:void(0);" title="">'+i+'</a>';
            }

            $span.html(_html).css({opacity:0.75}).appendTo($div);

            var $ctrl = $span.children('a'),
                n     = 0,t;

            var run   = function(i)
            {
                if($h.length)
                {
                    set_title(i);
                }

                $ctrl.eq(i).addClass('on').siblings().removeClass('on');
                $li.eq(i).show().siblings().hide();
            };

            var play  = function()
            {
                run(n);n ++;

                if(count == n)
                {
                    n = 0;
                }
            };

            if (!t)
            {
                run(0);
            }

            time = time || 2000;

            t = setInterval(play,time);

            $ctrl.hover(
                function()
                {
                    if(t)
                    {
                        clearInterval(t);
                    }

                    n  = parseInt($(this).html())-1;

                    t = setTimeout(function(){
                            $li.stop();
                            run(n);
                        } ,100);
                },
                function()
                {
                    clearInterval(t);
                    t = setInterval(play, time);
                }
            );

            $li.each(function() {
                $(this).hover(
                    function()
                    {
                        if(t)
                        {
                            clearInterval(t);
                        }
                    },
                    function()
                    {
                        t = setInterval(play, time);
                    }
                );
            });

        });
    };

    /**
     +----------------------------------------------------------
     * 资讯正文 对首张图片添加提示和下一页链接
     +----------------------------------------------------------
    */
    $.fn.BoxText = function()
    {
        if(!this){ return;}

        var ahref = $(this).attr('nextpagehref');// 下一页链接地址

        $('img',this).eq(0).parent('p')
            .addClass('page_tips')
            .prepend('<span class="ptips">点击图片，进入下一页</span>')
            .end().end().each(function() {
                $(this).wrap('<a href="'+ahref+'" title="下一页"></a>')
            });

        return this;
    };

    /**
     +----------------------------------------------------------
     * 活动页 展开收起
     +----------------------------------------------------------
    */
    $.read_ctrl = function(_this,_id,_class)
    {
        var $this = $(_this),
            $id   = $(_id),
            isoff = $this.attr('rel');

        if('off' == isoff)
        {
            isoff = 'on';
            $this.attr({rel:'on',title:'收起来'}).addClass('read_hide').html('收起来');
            $id.removeClass(_class);
        }
        else
        {
            isoff = 'off';
            $this.attr({rel:'off',title:'展开更多'}).removeClass('read_hide').html('展开更多');
            $id.addClass(_class);
        }
    };

    /**
     +----------------------------------------------------------
     * 活动年历页 显示数据列表
     +----------------------------------------------------------
    */
    $.fn.ActShow = function()
    {
        if(!this){ return;} // 避免不必要的执行

        var $this  = $(this),
            $title = $this.children('ul.act_title');

        $this.children('div').each(function() {

            $(this).hover(
                function()
                {
                    var $_this = $(this),
                        $ul    = $_this.children('ul');

                    // 存在内容才生效
                    if($ul.length)
                    {
                        // 定位计算
                        // 624 = 列表第6列position-left的定位值625减1
                        // 861 = 列表第7列position-left的定位值750 + 窗格宽度110 + 线段宽1
                        // 100 = 窗格高度110 减去10偏移
                        // 124 = 窗格宽度110 加上窗格之间的margin值13

                        var os  = $_this.position(),
                            pos = { top: os.top+100 };

                        if(os.left > 624)
                        {
                            pos.right = 861 - os.left;
                        }
                        else
                        {
                            pos.left = os.left + 124;
                        }

                        $title.html($ul.html()).css(pos).show();
                    }
                },
                function()
                {
                    $title.hide().html('').attr('style','');
                }
            );
        });
    }; // 活动年历页 end

    /**
     +----------------------------------------------------------
     * 全选反选
     +----------------------------------------------------------
    */
    $.select_all = function(_this,_name)
    {
        var $this     = $(_this),
            $checkbox = $this.parents('form').find('input[name="'+_name+'"]');

        if(_this.checked)
        {
            $this.attr('checked','checked');
            $checkbox.each(function() {
                $(this).attr('checked','checked');
            });
        }else
        {
            $this.removeAttr('checked');
            $checkbox.each(function() {
                $(this).removeAttr('checked');
            });
        }
    };

    /* ---------------------------------------------------- */
    /* 新闻轮播
    /* ---------------------------------------------------- */
    $.slide_news  = function()
    {
        $('#slide_news li').eq(0).slideUp(600,function(){
            $(this).clone().appendTo($(this).parent()).slideDown(100);
            $(this).remove();
        });
    };

    /**
     +----------------------------------------------------------
     * 首页专用轮播
     +----------------------------------------------------------
    */
    $.fn.IndexSlide   = function(timer)
    {
        if(!this){ return;}

        timer = timer || 2000;

        var $view = $('.slide_view',this),
            $li   = $('>ul>li',this).each(function(i){$(this).attr('rel',i)}),
            $ctrl = $li.children('a.slide_img'),
            index = 0,
            cTime;

        var slideInit = function()
        {
            slidePlay(index);
            index++;
            if(5 == index)
            {
                index = 0;
            }
        };

        // 轮播执行
        var slidePlay = function(i)
        {
            $li.eq(i).addClass('on').siblings().removeClass('on');
            $view.html($li.eq(i).html());
        };

        // 首次打开页面执行
        if (!cTime)
        {
            slidePlay(0);
        }

        cTime = setInterval(slideInit,timer);

        // 鼠标移动到图片时显示该列内容
        $ctrl.hover(
            function()
            {
                if(cTime)
                {
                    clearInterval(cTime);
                }

                index  = $(this).parent('li').attr('rel');

                cTime = setTimeout(function(){
                    $view.stop();
                    slidePlay(index);
                } ,100);
            },
            function()
            {
                clearInterval(cTime);
                cTime = setInterval(slideInit, timer);
            }
        );

        // 鼠标在视图内停止转换
        $view.hover(
            function()
            {
                if(cTime)
                {
                    clearInterval(cTime);
                }
            },
            function()
            {
                cTime = setInterval(slideInit, timer);
            }
        );
    };// 首页轮播 end

    /**
     +----------------------------------------------------------
     * 首页 上下翻页控制 大家最近关注的活动
     +----------------------------------------------------------
    */
    $.fn.ShowHotList = function(_speed)
    {
        if(!this){ return;}

        var $ul = $('>ul',this),
            $li = $ul.children('li'),
            count = $li.length,
            $up = $('#act_up',this).addClass('gray'),
            $down = $('#act_down',this);

        if(count < 4)
        {
            $down.addClass('gray');
            return;
        }

        _speed = _speed || 500;

        var liH  = $li.height(),
            maxH = liH * 4,
            allH = liH * count,
            posT = 0;

        $ul.height(allH);

        // 往下滚动
        $down.bind('click',function(){

            if(allH <= maxH - posT)
            {
                return;
            }

            posT = posT - maxH;

            $ul.animate(
                    {top: posT},
                    {duration:_speed,complete:function(){

                        $up.removeClass('gray');

                        if(allH <= maxH - posT)
                        {
                            $down.addClass('gray');
                        }
                    }}
                );
        });

        // 往上滚动
        $up.bind('click',function(){

             if(posT >= 0)
             {
                 return;
             }

             posT = posT + maxH;

             $ul.animate(
                    {top: posT},
                    {duration:_speed,complete:function(){
                        if(posT >= 0)
                        {
                            $up.addClass('gray')
                        }
                        $down.removeClass('gray');
                    }}
                );
        });
    };// 上下翻页 end

    /* ---------------------------------------------------- */
    /* 活动内容页的左右滚动
    /* ---------------------------------------------------- */
    $.fn.ToScroll   = function(_speed)
    {
        if(!this){ return;}

        return this.each(function() {
            var $ul    = $('.scroll_list>ul',this),
                $div   = $ul.children().children('div'),
                $left  = $('.scroll_left',this),
                $right = $('.scroll_right',this);

            // 处理参赛作品的缩略图
            if($div.length)
            {
                $('a:has(img)',$div).each(function() {
                    var $this = $(this),
                        w     = $this.width(),
                        h     = $this.height();
                    $this.css({width:w,height:h,marginTop:-h/2,marginLeft:-w/2});
                });
            }

            if($ul.children().length < 4)
            {
                return;
            }

            _speed = _speed || 200;

            // 向左滚动
            $right.bind('click',function(){

                $ul.animate(
                    {left:'-162px'},
                    {duration:_speed,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','-162px');
                $ul.animate(
                    {left:0},
                    {duration:_speed,complete:function(){
                        $ul.find('li:last').remove();
                    }}
                );
            });
        });


    };//左右滚动end


    /**
     +----------------------------------------------------------
     * 文章页面图片宽度自适应
     +----------------------------------------------------------
    */
    $.fn.ImgAutoSize   = function(maxsize)
    {
        if(!this){ return;}

        return this.each(function() {
            var $img = $(this).find('img');

            if(! $img.length)
            {
                return;
            }

            $img.each(function() {
                var w = $(this).width(),
                    h = $(this).height();

                maxsize = maxsize || 600;
                if(w > maxsize)
                {
                    // 涉及到编辑器的原因，必需用属性设置
                    $(this).attr({width:maxsize,height:maxsize/w * h});
                }
            });

        });
    };

// 闭包end
})(jQuery);


/**
 +----------------------------------------------------------
 * 事件应用
 +----------------------------------------------------------
*/
jQuery(document).ready(function(){

    // 当前导航高亮
    $('#nav_'+consts('mname')).addClass('on');

    // 搜索控制
    $('#nav_search').Tosearch();

    // 首页轮播 参数越大变换越慢 不填为2000
    $('#index_slide').IndexSlide(2500);

    // 首页最近关注的活动上下翻页 参数是滚动速度
    $('#act_hot_list').ShowHotList(600);

    // 活动轮播
    $('#act_slide').ActSlide();

    // 活动页左右滚动
    $('#scroll_box1,#scroll_box2').ToScroll(200);

    // 正文图片点击及进入下一页提示
    $('#box_text').BoxText();

    // 验证码刷新
    if($.getid('verify_img'))
    {
        $('#verify_img').click(function(){
            $(this).attr('src',this.src + '/' + new Date().getTime());
        });
    }

    // 登录输入框优化
    if($.getid('login_form'))
    {
        $('#login_form input.text').focus_ctrl();
    }

    if($.getid('index_first') && !$.support.style)
    {
        $('#user_news').height(393);
    }

    // 活动年历页显示数据
    $('#act_datalist').ActShow();

    // 文章内容图片宽度自适应
    // 最大宽度默认为600,需要更改可传入参数，例如:(500)
    $('#box_text,.item_text').ImgAutoSize();

    // 新闻轮播
    if($('#slide_news>ul>li').length >1)
    {
        setInterval('$.slide_news()',5000);
    }

    // 首页960*400广告 11秒
    if($('#ad960x400').children().length)
    {
        var $ad    = $('#ad960x400').clone(true).prependTo('body').show(),
            _time  = 8000,
            _speed = 2000;
        window.setTimeout(function(){$ad.slideUp(_speed,function(){$ad.remove();});},_time);
    }
});