/**
 * 依赖js包
 *
 * easing 缓动函数插件
 * html select 样式自定义插件
 */
(function($){

     // 动画缓动函数插件{{{
    jQuery.easing['jswing'] = jQuery.easing['swing'];
    jQuery.extend( jQuery.easing, {
        def: 'easeOutQuad',
        swing: function (x, t, b, c, d) {
            //alert(jQuery.easing.default);
            return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
        },
        easeInQuad: function (x, t, b, c, d) {
            return c*(t/=d)*t + b;
        },
        easeOutQuad: function (x, t, b, c, d) {
            return -c *(t/=d)*(t-2) + b;
        },
        easeInOutQuad: function (x, t, b, c, d) {
            if ((t/=d/2) < 1) return c/2*t*t + b;
            return -c/2 * ((--t)*(t-2) - 1) + b;
        },
        easeInCubic: function (x, t, b, c, d) {
            return c*(t/=d)*t*t + b;
        },
        easeOutCubic: function (x, t, b, c, d) {
            return c*((t=t/d-1)*t*t + 1) + b;
        },
        easeInOutCubic: function (x, t, b, c, d) {
            if ((t/=d/2) < 1) return c/2*t*t*t + b;
            return c/2*((t-=2)*t*t + 2) + b;
        },
        easeInQuart: function (x, t, b, c, d) {
            return c*(t/=d)*t*t*t + b;
        },
        easeOutQuart: function (x, t, b, c, d) {
            return -c * ((t=t/d-1)*t*t*t - 1) + b;
        },
        easeInOutQuart: function (x, t, b, c, d) {
            if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
            return -c/2 * ((t-=2)*t*t*t - 2) + b;
        },
        easeInQuint: function (x, t, b, c, d) {
            return c*(t/=d)*t*t*t*t + b;
        },
        easeOutQuint: function (x, t, b, c, d) {
            return c*((t=t/d-1)*t*t*t*t + 1) + b;
        },
        easeInOutQuint: function (x, t, b, c, d) {
            if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
            return c/2*((t-=2)*t*t*t*t + 2) + b;
        },
        easeInSine: function (x, t, b, c, d) {
            return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
        },
        easeOutSine: function (x, t, b, c, d) {
            return c * Math.sin(t/d * (Math.PI/2)) + b;
        },
        easeInOutSine: function (x, t, b, c, d) {
            return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
        },
        easeInExpo: function (x, t, b, c, d) {
            return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
        },
        easeOutExpo: function (x, t, b, c, d) {
            return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
        },
        easeInOutExpo: function (x, t, b, c, d) {
            if (t==0) return b;
            if (t==d) return b+c;
            if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
            return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
        },
        easeInCirc: function (x, t, b, c, d) {
            return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
        },
        easeOutCirc: function (x, t, b, c, d) {
            return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
        },
        easeInOutCirc: function (x, t, b, c, d) {
            if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
            return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
        },
        easeInElastic: function (x, t, b, c, d) {
            var s=1.70158;var p=0;var a=c;
            if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
            if (a < Math.abs(c)) { a=c; var s=p/4; }
            else var s = p/(2*Math.PI) * Math.asin (c/a);
            return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
        },
        easeOutElastic: function (x, t, b, c, d) {
            var s=1.70158;var p=0;var a=c;
            if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
            if (a < Math.abs(c)) { a=c; var s=p/4; }
            else var s = p/(2*Math.PI) * Math.asin (c/a);
            return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
        },
        easeInOutElastic: function (x, t, b, c, d) {
            var s=1.70158;var p=0;var a=c;
            if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
            if (a < Math.abs(c)) { a=c; var s=p/4; }
            else var s = p/(2*Math.PI) * Math.asin (c/a);
            if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
            return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
        },
        easeInBack: function (x, t, b, c, d, s) {
            if (s == undefined) s = 1.70158;
            return c*(t/=d)*t*((s+1)*t - s) + b;
        },
        easeOutBack: function (x, t, b, c, d, s) {
            if (s == undefined) s = 1.70158;
            return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
        },
        easeInOutBack: function (x, t, b, c, d, s) {
            if (s == undefined) s = 1.70158; 
            if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
            return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
        },
        easeInBounce: function (x, t, b, c, d) {
            return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
        },
        easeOutBounce: function (x, t, b, c, d) {
            if ((t/=d) < (1/2.75)) {
                return c*(7.5625*t*t) + b;
            } else if (t < (2/2.75)) {
                return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
            } else if (t < (2.5/2.75)) {
                return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
            } else {
                return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
            }
        },
        easeInOutBounce: function (x, t, b, c, d) {
            if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
            return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
        }
    });
    //}}}

    $.extend({
        // 转serializeArray为name为值{{{
        parseSerializeArr: function(arr) {
            returnArr = {};
            for (var i=0, len=arr.length; i<len; i++) {
                returnArr[arr[i].name] = arr[i].value;
            }
            return returnArr;
        },
        //}}}

        // 提交登陆{{{
        doSubmitLogin: function(postData, callback) {
            var returnArr = {status_code: 'post_success', status_msg:'提交成功'};
            callback = callback || function(){};
            if (postData) {
                if (!postData.code) {
                    returnArr.status_code = 'username_is_error';
                    returnArr.status_msg = '您输入的账号有误。';
                    return callback(returnArr);
                } else if (/^[a-z_][a-z_0-9]*$/i.test(postData.code)) {
                    if (postData.code.length > 20 || postData.code.length <3) {
                        returnArr.status_code = 'username_is_error';
                        returnArr.status_msg = '您输入的账号有误。';
                        return callback(returnArr);
                    }
                } else if (!(/^1(3|5|8|4|7)\d{9}$/.test(postData.code)) && !(postData.code.indexOf('@')>0)) {
                    returnArr.status_code = 'username_is_error';
                    returnArr.status_msg = '您输入的账号有误。';
                    return callback(returnArr);
                }

                if (!postData.password || postData.password.length < 6) {
                    returnArr.status_code = 'password_is_error';
                    returnArr.status_msg = '您输入的密码有误。';
                    return callback(returnArr);
                }

                if (typeof(hex_md5) == 'function') {
                    postData.password = hex_md5(postData.password);
                }

                $.ajax({
                    type: "POST",
                    url: window.WEBSERVER ? window.WEBSERVER+'/websiteAjax/op/login/' : '/websiteAjax/op/login/',
                    data: postData,
                    dataType: 'json',
                    success: function(result){
                        var returnArr = {};
                        if (result.status > 0) {
                            returnArr.status_code = 'login_success';
                            returnArr.status_msg = '登陆成功。';
                        } else if (result.msg == '对不起，登陆失败次数过多，请稍候再进行登陆。') {
                            returnArr.status_code = 'more_fail_login';
                            returnArr.status_msg = result.msg;
                        } else if (result.msg == 'IP禁止登陆。') {
                            returnArr.status_code = 'ip_banned';
                            returnArr.status_msg = result.msg;
                        } else if (result.msg == '对不起，密码错误。') {
                            returnArr.status_code = 'password_is_error';
                            returnArr.status_msg = '您输入的密码有误。';
                        } else {
                            returnArr.status_code = 'username_is_error';
                            returnArr.status_msg = '您输入的账号有误。';
                        }
                        callback(returnArr);
                        return false;
                    }
                });
            } else {
                returnArr.status_code = 'data_empty';
                returnArr.status_msg = '提交的数据不可为空。';
                return callback(returnArr);
            }
        }
        //}}}
    });

    $.fn.extend({

        // html select 自定义控件 {{{
        selectPlugin: function(options){
            var defaults = {
                dataId: 'data-id',                // 节点id所在属性名
                dataName: 'data-name',            // 节点节点所在属性名
                dataValue: 'data-value',          // 节点节点所在值
                valueName: 'value',               // 下拉项中值的属性名
                valueCls: 'selectMain',           // 节点值所在节点类
                listWrapCls: 'selectWrap',        // 列表下拉包裹类
                listItemSelectedCls: 'selected'   // 列表下拉项选中类
            };
            options = $.extend(defaults, options);
            $(this).each(function(){
                var $this = $(this);
                var openState = false;
                var $selectWrap = $this.find('.' + options.listWrapCls);
                var $valueItem = $this.find('.' + options.valueCls);

                var fn_close = function(){
                    $this.removeClass('selectShow');
                    if($valueItem.hasClass('selUp'))$valueItem.removeClass('selUp');
                    $selectWrap.hide();
                    openState = false;
                };
                var fn_open = function(){
                    $this.addClass('selectShow');
					$liWrap = $selectWrap.find('li').length;
					if($liWrap > 1) {
						$selectWrap.show();
						$valueItem.addClass('selUp');
					}

                    openState = true;
                    fn_makeScrollable()
                };

                var fn_makeScrollable = function(){
                    var extra = 50;
                    var $view = $selectWrap;
                    var $container = $selectWrap.find('ul');
                    var wrapperHeight = $view.height();
					$view.css({overflow: 'auto','overflow-x':'hidden'});
					/*if($valueItem.attr("isscroll") == 1) {
						$view.css({overflow: 'auto','overflow-x':'hidden'});
					} else {
						$view.css({overflow: 'hidden'});
						$view.scrollTop(0);
						$view.unbind('mousemove').bind('mousemove',function(e){
							var ulHeight = $container.outerHeight() + 2*extra ;
							var top = (e.pageY - $view.offset().top) * (ulHeight-wrapperHeight ) / wrapperHeight - extra;
							$view.scrollTop(top);
						});
					}*/
                };

                var fn_init = function(){
                    var name = $this.attr(options.dataName);
                    var value = $this.attr(options.dataValue);
                    if (typeof(name) != 'undefined') {
                        if (typeof(value) == 'undefined') {
                            $this.attr(options.dataValue, '');
                        }

                        var $item = $this.find('li a['+options.valueName+'='+value+']');
                        if ($item.length) {
                            $item.trigger('click');
                        } else {
                            $this.find('li a:eq(0)').trigger('click');
                        }
                    }

                };
                $this.bind('click', function(){
                    // 已打开，则关闭
                    if (openState) {
                        fn_close();
                    } else {
                        fn_open();
                    }
                }).delegate('ul li a', 'click', function(e){
                    var id    = $this.attr(options.dataId);
                    var name  = $this.attr(options.dataName);
                    var value = $(this).attr(options.valueName);
                    var txt   = $(this).text();
                    var $val  = $this.find('input[name='+name+']');
                    var defval= $val.val();

                    // 生成隐藏控件
                    if ($val.length) {
                        $val.val(value);
                    } else if (name) {
                        if (id) {
                            $val = $('<input type="hidden" value="'+value+'" id="'+id+'" name="'+name+'" />').appendTo($this);
                        } else {
                            $val = $('<input type="hidden" value="'+value+'" name="'+name+'" />').appendTo($this);
                        }
                    }

                    // 显示选择的值
                    $valueItem.attr(options.valueName, value).text(txt);
                    $this.find('li').removeClass(options.listItemSelectedCls).show();
                    $(this).parent().addClass(options.listItemSelectedCls).hide();
                    $selectWrap.hide();

                    // 是否改变值
                    if (value != defval) {
                        if ($val.length) {
                            $val.trigger('change', value);
                        }
                        $this.trigger('change', value);
                    }

					//移除“请选择”的下拉内容
					if($valueItem.attr("nodefault") == 1 && value != '' && $(this).parent().parent().find('a[value=""]').length) {
						$(this).parent().parent().find('a[value=""]').parent().remove();
					}

                    fn_close();
                    return false;
                }).bind('replaceAllOption', function(e, dataArr){
                    var def_value  = $(this).attr(options.dataValue);
                    var selectedVal = (typeof(def_value) == 'undefined') ? '' : def_value;
                    if (dataArr) {
                        var htmlTpl = [];
                        for (var i in dataArr) {
                            if (i == selectedVal) {
                                htmlTpl.push('<li class="selected" style="display:none;"><a '+options.valueName+'="' + i + '" href="javascript:;">' + dataArr[i] + '</a></li>');
                                htmlTplVal = [i,dataArr[i]];
                            } else {
                                htmlTpl.push('<li><a '+options.valueName+'="' + i + '" href="javascript:;">' + dataArr[i] + '</a></li>');
                            }
                        }
                        $selectWrap.find('ul').html(htmlTpl.join(''));
                        var $firstItem = $selectWrap.find('.selected a');
                        if (!$firstItem.length) {
                            $firstItem = $selectWrap.find('li a:eq(0)');
                        }
                        $firstItem.trigger('click');

                        return false;
                    }
                }).bind('selectOption', function(e, val){
                    $(this).find('li a[' + options.valueName + '="' + val + '"]').trigger('click');
                    return false;
                }).bind('selectOptionIndex', function(e, idx){
                    $(this).find('li:eq('+idx+') a').trigger('click');
                    return false;
                });

                // 初始化默认值
                fn_init();

                // 绑定点击隐藏下拉事件
                $(document).bind('click', function(e){
                    if (e.target != $valueItem.get(0)) {
                        fn_close();
                    }
                });
            });
        },
        //}}}

        // html checkbox 自定义控件 {{{
        checkbox: function(options){
            $(':checkbox+label', this).each(function(){
                var $label = $(this);
                var $checkbox = $label.prev();
                $label.addClass('checkbox');
                // 选中状态
                if ($checkbox.is(':disabled') == false) {
                    if ($checkbox.is(':checked')) {
                        $label.addClass("checked");
                    }
                } else {
                    $label.addClass('disabled');
                }
            }).bind('click', function(event){
                var $label = $(this);
                var $checkbox = $label.prev();

                // 更新选中状态
                if (!$checkbox.is(':checked')) {
                    $label.addClass("checked");
                    $checkbox[0].checked = true;
                } else {
                    $label.removeClass('checked');
                    $checkbox[0].checked = false;
                }
                return false;
            }).prev().hide();
        },
        //}}}

        // html radio 自定义控件 {{{
        hradio: function(options){
            var self = this;
            return $(':radio+span',this).each(function(){
                $(this).addClass('hRadio');
                if($(this).prev().is("checked"))
                    $(this).addClass('hRadio_Checked');
            }).click(function(event){
                $(this).siblings().removeClass("hRadio_Checked");
                if(!$(this).prev().is(':checked')){
                    $(this).addClass("hRadio_Checked");
                    $(this).prev()[0].checked = true;
                }   
                event.stopPropagation();
            })
            .prev().hide();
        },
        //}}}

        // 头部nav效果{{{
        navMove:function(options,callback){
            var defaults={
                navBox:'ul li',//导航列表
                navSpan:'span',//移动块
                navCur:'cur',//当前状态
                duration:500,//移动块移动时间
                easing:"swing",//移动块移动效果
                marLeft:""
            };

            var options = $.extend(defaults, options);
            var callback = callback || function(){};

            $(this).each(function(){
                var $this=$(this),
                    $navBox=$this.find(options.navBox),
                    $navSpan=$this.find(options.navSpan),
                    $navCur=options.navCur,
                    $duration=options.duration,
                    $easing=options.easing,
                    $marLeft=options.marLeft;

                    var w=$navBox.outerWidth(true);
                    var $cur=$("a.cur").parent().index();
                    var $default=$navSpan.css({"left":w*$cur+$marLeft});

                    if($('.'+$navCur).length<=0)
                    {
                        $navSpan.hide();
                    }

                    $navBox.hover(
                        function(){

                            if($('.'+$navCur).length<=0)
                            {
                                $navSpan.show();
                            }

                            //if($navSpan.is(":animated")) return;
                            $navSpan.stop(true).animate({"left":w*($(this).index())+$marLeft},{duration:$duration,easing:$easing});
                            if($(this).find("a").attr("class")!=$navCur)
                            {
                                $("."+$navCur).css({"color":"#383838"});
                            }
                            else
                            {
                                $("."+$navCur).css({"color":"#fff"});
                            }

                        },
                        function(){
                            if($('.'+$navCur).length<=0)
                            {
                                $navSpan.hide();
                            }

                            if($(this).find("a").attr("class")!=$navCur)
                            {
                                var $curIndex=$('.'+$navCur).parent().index();
                                $navSpan.stop(true).animate({"left":w*$curIndex+$marLeft},{duration:$duration,easing:$easing,complete:function(){$("."+$navCur).css({"color":"#fff"});}});  
                            }
                        }
                    );

                    /*
                    $navBox.click(function(){
                        $(this).find("a").addClass($navCur).parent().siblings().find("a").removeClass($navCur); 
                        $navSpan.css({"left":w*($(this).index())}+$marLeft);
                        if($(this).find("a").attr('class').indexOf('eAmg ')!=-1){$(this).find("a").parent().siblings().find(".eImgs").css({'opacity':0})}

                    })
                    */
            })
        }
        //}}}

    });
})(jQuery);

