if (!window.Dahei) {
    window.Dahei = {};
};
window.debug = true;

// Dahei.Common {{{
Dahei.Common = {
    init: function()
    {
        // 下拉列表插件
        Dahei.Common.enableSelectPlugin();
        // 导航效果
        Dahei.Common.enableNavEffect();
        Dahei.Common.enableAddFavorite();
        // 复选框插件
        Dahei.Common.enableCheckBox();
        // 弹窗手动插件
        Dahei.Common.enableDragPlugin();
        // 返回顶部
        Dahei.Common.enableBackTop();
        // 全站需要的事件状态切换
        Dahei.Common.enableInputEvent();
        // 登陆框事件
        Dahei.Common.enableHeaderLogin();
        // 已登陆事件初始化
        Dahei.Common.enableHeaderLogon();
        // 显示激活
        Dahei.Common.enableVipUp();
        // ajax登陆
        Dahei.Common.enableAjaxLogin();
        // 右下角浮动层
        Dahei.Common.enableGetFloatRightBottom();
    },
    enableSelectPlugin: function()
    {
        var $this = $('.selectPlugin');
        if ($this.length) {
            $this.selectPlugin();
        }
    },
    enableNavEffect: function()
    {
        var $this = $('.topBox .nav');
        if ($this.length) {
            var $cur = $this.find('.cur');
            if ($cur.length) {
                if (window.DD_belatedPNG) {
                    window.DD_belatedPNG.fix('.topBox .nav .cur');
                }
                /*
                var nPos = $cur.position();
                $this.find('span').css('left', nPos.left + 'px');
                $this.navMove({});
                */
            }
        }
    },
    enableAddFavorite: function()
    {
        var $this = $('.addFavorite');
        if ($this.length) {
            $this.bind('click', function(){
                var urlStr = $this.attr('data-url');
                if (!(urlStr && urlStr.length>0)) {
                    urlStr = window.location + '';
                }
                var titleStr = $this.attr('data-title');
                if (!(titleStr && titleStr.length>0)) {
                    titleStr = document.title;
                }
                if (document.all) {
                    window.external.addFavorite(urlStr, titleStr);
                } else if (window.sidebar && window.sidebar.addPanel) {
                    window.sidebar.addPanel(titleStr, urlStr, '');
                } else {
                    alert('请按 ctrl+d 收藏。');
                }
            });
        }
    },
    enableCheckBox: function()
    {
        var $this = $('.check');
        if ($this.length) {
            $this.checkbox();
        }
    },
    enableDragPlugin: function()
    {
        if ($('.getPop').length) {
            var p1 = new Piled();
            p1.init('getPop','drag');
        }
    },
    enableBackTop: function()
    {
        var $this = $('#backTop');
        if ($this.length) {
            $this.children("a").click(function(){
                var _this=$(this);
                $("body,html").animate({scrollTop:0},{duration:500,easing:"easeInOutQuart"});
            });
            $(window).bind('scroll', function (){
                var oDiv=$("#backTop");
                var oDivH=oDiv.outerHeight();
                var winH=$(window).height();
                var docH=$(document).height();
                var scrollTop=$(window).scrollTop();
                var bottom =0;
                if (scrollTop>(winH/2)) {
                    oDiv.children("a").fadeIn();
                } else {
                    oDiv.children("a").fadeOut();
                }
            });
        }

        var $closeFloat = $('#closeFloat');
        if ($closeFloat.length) {
            $closeFloat.click(function(){
                $("#csFloat").fadeOut();
            });
        }
    },
    enableInputEvent: function()
    {
		$('body').delegate('input.i2', 'focus', function(){
            $(this).addClass('iOn');
			if($(this).hasClass('iErr')) {
				$(this).removeClass('iErr');
			}
        }).delegate('input.i2', 'blur', function(){
            if ($(this).val() && ((this.defaultValue && this.defaultValue.indexOf('请') == -1) || $(this).val() != this.defaultValue)) {
				$(this).addClass('ii2').removeClass('iOn');
			} else {
				$(this).removeClass('ii2').removeClass('iOn');
			}
        });


        var $button = $('button');
        $('body').delegate('button', 'mouseenter', function(){
            $(this).addClass('on');
        }).delegate('button', 'mouseleave', function(){
            $(this).removeClass('on');
        });

        var $liHover = $(".gameGuide ul li,.news ul li,.newSer ul li,.tabDiv ul li,.gameNews li,.bbsHot li,.newsList li,.giftBox li,.payQs li");
        if ($liHover.length) {
            $liHover.hover(
                function() {
                    $(this).addClass("lOn");
                },
                function() {
                    $(this).removeClass("lOn");
                }
            );
        }
        var $selobj = $('.sDiv');
        if($selobj.length) {
            $selobj.bind('change', function(){
                if($(this).find('.selectMain').hasClass('selErr')) {
                    $(this).find('.selectMain').removeClass('selErr');
                }
            });
        }
    },
    enableHeaderLogin: function()
    {
        var $this = $('.main .uc form');
        if ($this.length) {
            var $code = $this.find('input[name="code"]');
            $code.bind('focus', function(){
                var val = $(this).val();
                if ('请输入账号' == val) {
                    $(this).val('');
                }
            }).bind('blur', function(){
                var val = $(this).val();
                if ('' == val) {
                    $(this).val('请输入账号');
                }
            }).bind('keyup', function(){
                $(this).parent('p').removeClass('usErr').find('.sp_code').removeClass('sErr').html('');
            });

            var $password = $this.find('input[name="password"]');
            var ctime = 1;
            $password.bind('focus', function(){
                var val = $(this).val();
                $('#em_pwd').hide();
            }).bind('blur', function(){
                var val = $(this).val();
                if ('' == val) {
                    $('#em_pwd').show();
                }
            }).bind('click', function(){
                $(this).trigger('focus');
            }).bind('keyup', function(){
                $(this).parent('p').removeClass('psdErr').find('.sp_password').removeClass('sErr').html('');
            }).bind('fixpwd', function(){
                var fn_fixpwd = function(){
                    ++ctime;
                    var _val = $password.val();
                    if (_val) {
                        $('#em_pwd').hide();
                    } else if (ctime<=8) {
                        setTimeout(fn_fixpwd, 100*ctime);
                    }
                };
                fn_fixpwd();
                return false;
            });

			$('#em_pwd').bind('click', function(){
				$password.focus();
				return false;
			});

            var $submitBtn = $this.find('.submitBtn');
            if ($submitBtn.length) {
                $submitBtn.bind('click', function(){
                    $this.trigger('submit');
                    return false;
                });
            }
            $this.bind('submit', function(){
                $.doSubmitLogin($.parseSerializeArr($this.serializeArray()), function(result){
                    if (result.status_code == 'login_success') {
                        window.location = window.location + '';
                    } else if (result.status_code == 'ip_banned') {
                        if ($('#alpha2').length && window.waitshow) {
                            window.waitshow();
                        } else {
                            alert(result.status_msg);
                        }
                    } else if (result.status_code == 'password_is_error') {
                        $password.parent('p').addClass('psdErr').find('.sp_password').addClass('sErr').html(result.status_msg+'<var></var>');
                    } else if (result.status_code == 'username_is_error') {
                        $code.parent('p').addClass('usErr').find('.sp_code').addClass('sErr').html(result.status_msg+'<var></var>');
                    } else {
                        alert(result.status_msg);
                    }
                });
                return false;
            });

			var KEEPCODE = getCookie('KEEPCODE');
            if (KEEPCODE) {$code.val(KEEPCODE);}
			$password.trigger('fixpwd');
        }
    },
    enableHeaderLogon: function()
    {
        var $this = $('.main .uc .logon');
        if ($this.length) {
            // 当前登陆账号
            var login_code = getCookie('login_code');
            $this.find('.login_code').html(login_code);

            // 最近玩过的游戏或推荐游戏
            var $selectPlaygid = $('.selectPlaygid');
            if ($selectPlaygid.length) {
                $selectPlaygid.bind('change', function(evt){
                    var val = $('#playgid').val();
                    var htmlTpl = [];
                    if (playedServer && typeof(playedServer[val]) != 'undefined') {
                        var data = playedServer[val];
                        for (var i=0,len=data.length; i<len; i++) {
                            htmlTpl.push('<li><a value="' + data[i]['code'] + '" href="javascript:;">' + data[i]['name'] + '</a></li>');
                        }
                    }
                    var $selectPlaysid = $('.selectPlaysid');
                    $selectPlaysid.find('ul').html(htmlTpl.join(''));
                    // 更新选中，第一个
                    var $firstItem = $selectPlaysid.find('.selected a');
                    if (!$firstItem.length) {
                        $firstItem = $selectPlaysid.find('li a:eq(0)');
                    }
                    $firstItem.trigger('click');

                    return false;
                }).trigger('change');
            }

            // 进入玩过的游戏
            var $inBtn = $this.find('.inBtn');
            if ($inBtn.length) {
                $inBtn.bind('click', function(){
                    $(document).trigger('click');
                    var playgid = $('#playgid').val();
                    var playsid = $('#playsid').val();
                    if (!playgid) {
                        alert('请选择游戏。');
                    }
                    if (!playsid) {
                        alert('请选择区服。');
                    }
                    window.open(window.WEBSERVER + '/joinGame/code/' + playsid + '/');
                    return false;
                });
            }

            // 随机游戏
            var $aRandom = $this.find('.aRandom');
            if ($aRandom.length) {
                // 列表显示隐藏事件
                var $randPop = $this.find('.randPop');
                $randPop.bind('update', function(evt, label){
                    if (label == 'show') {
                        $(this).show().animate({"opacity":1,"top":"55px"},{duration:150,easing:"swing"});
                    } else {
                        $(this).animate({"opacity":0,"top":"75px"},{duration:150,easing:"swing",complete:function(){
                            $(this).hide();
                        }});
                    }
                    return false;
                }).find('.randClose').bind('click', function(){
                    $randPop.trigger('update', 'close');
                    return false;
                });


                // 获取随机游戏
                var gidArr= [];
                if (window.playedServer) {
                    for (var k in window.playedServer) {
                        gidArr.push(k);
                    }
                }
                $aRandom.bind('click', function(){
                    $.ajax({
                        type: 'GET',
                        url: window.WEBSERVER + '/websiteAjax/op/randomGame/',
                        data: 'gids=' + gidArr.join(','),
                        dataType: 'jsonp',
                        success: function(result) {
                            if (result.status) {
                                var tplArr = [], data = result.data;
                                for (var i=0,len=data.length; i<len; i++) {
                                    tplArr.push('<li>');
                                    tplArr.push('    <img width="16" height="16" src="' + window.WEBSERVER + '/images/game/' + data[i]['game']['code'] + '_ico2.jpg">');
                                    tplArr.push('    <a href="' + window.WEBSERVER + '/server/code/' + data[i]['game']['code'] + '.shtml" class="aName" target="_blank">' + data[i]['game']['name'] + '</a>');
                                    tplArr.push('    <a href="' + window.WEBSERVER + '/joinGame/code/' + data[i]['server']['code'] + '/" class="aSer" target="_blank">' + data[i]['server']['name'] + '</a>');
                                    tplArr.push('    <a href="' + window.WEBSERVER + '/joinGame/code/' + data[i]['server']['code'] + '/" class="aBtn" target="_blank">进入游戏</a>');
                                    tplArr.push('</li>');
                                }
                                $randPop.find('ul').html(tplArr.join(''));
                                $randPop.trigger('update', 'show');
                            }
                        }
                    });
                    return false;
                });
            }
        }
    },
    enableVipUp: function()
    {
        // 充值vip升级详细
        var $vipUp = $('.doVipUp');
        if ($vipUp.length) {
			var handle = '';
            $vipUp.bind('mouseover', function(){
				$(".hmipop").hide();
				$(this).show();
				if(handle)clearTimeout(handle);
				return false;
			}).bind('mouseout', function(){
				$this = $(this);
				handle = setTimeout(function() {
					$(".doVipUp").hide();
				}, 200);
				return false;
            });
        }

		var $hmUp = $('.hmipop');
		var hmhandle = '';
		if($hmUp.length) {
			var hmhandle = '';
            $hmUp.bind('mouseover', function(){
				$(".doVipUp").hide();
				$(this).show();
				if(hmhandle)clearTimeout(hmhandle);
				return false;
			}).bind('mouseout', function(){
				$this = $(this);
				hmhandle = setTimeout(function() {
					$(".hmipop").hide();
				}, 200);
				return false;
            });
		}

        // 充值vip升级链接更新
        var $vipRvip = $('input[name=_rvip]');
        if ($vipRvip.length) {
            var url = $('.vipRvipUrl').attr('href').replace(/\/_rvip\/[^/]+\//g, '/');
            $vipRvip.bind('update', function(){
                var val = $(this).val()
                $('.vipRvipUrl').attr('href', url + '_rvip/' + val + '/');
                return false;
            }).bind('click', function(){
                $(this).trigger('update');
            });
        }

        // 充值vip激活码
        var $vipAc = $('.vipAcBtn');
        if ($vipAc.length) {
            $vipAc.bind('click', function(){
                var $pop = $('#vippop');
                if (!$pop.length && $('.syspop').length) {
					$('.syspop').attr('id', 'vippop');
					$('#vippop').attr('class', 'getPop Pop0 ac syspop');
                }

                Notice.loadUidPop(window.WEBSERVER + '/rouse_vip/', 'vippop');
                return false;
            });
        }
    },
    enableAjaxLogin: function() {
        var $this = $('.ajax_login');
        if ($this.length && !$('#page_login').length) {
            $this.click(function(){
                var $popLogin = $('#popLogin');
                if (!$popLogin.length) {
                    $.ajax({
                        type: 'GET',
                        url: window.WEBSERVER + '/websiteAjax/op/login/',
                        dataType: 'jsonp',
                        cache: false,
                        success: function(data) {
                            if (data.status == 2) {
                                // 已登陆
                                window.location = window.location + '';
                            } else if (data.status == 0) {
                                $('body').append(data.msg);
                                Dahei.Common.window('#popLogin').open();
                                var p1 = new Piled();
                                p1.init('popLogin','popLoginDrag');
                            }
                        }
                    });
                } else {
                    $popLogin.show();
                    $('#popLogin').css('top', $(window).scrollTop() + $(window).height()*0.3);
                    $('#alpha').css('height', $(document).height()+'px').show();
                }
                return false;
            });
        }
    },
    enableGetFloatRightBottom: function() {
        var WEBSERVER = window.WEBSERVER;
        if (WEBSERVER == 'http://'+location.host) {
            $.ajax({
                type: 'GET',
                url: WEBSERVER + '/websiteAjax/op/getFloatRightBottom/',
                dataType: 'json',
                success: function(data) {
                    if (data.status) {
                        $('body').append(data.msg);
                    }
                    return false;
                }
            });
        }
    }
};
//}}}

// 弹窗window类{{{
Dahei.Common.windowList = {};
Dahei.Common.defaultOpt = {'closeCls': '.closePop'};
Dahei.Common.window = function(id, config) {
    if (!Dahei.Common.windowList[id]) {
        config = config || {};
        $.extend(config, Dahei.Common.defaultOpt);
        Dahei.Common.windowList[id] = new Dahei.Common.window.fn.init(id, config);
    }
    return Dahei.Common.windowList[id];
};
Dahei.Common.window.fn = Dahei.Common.window.prototype = {
    init: function(id, config) {
        var that = this;
        this.config = config;
        this.openState = false;
        this.lock = true;
        this.id = id;
        this.dom = $(id);
        config.closeCls && this.dom.delegate(config.closeCls, 'click', function(e){
            that.pre_close && that.pre_close.call(that);
            that.close();
            return false;
        });
    },
    open: function() {
        //if (this.openState) return;

        this.openState = true;

        this.dom.show();
        this.isShowMaskLayer();
    },
    close: function() {
        //if (!this.openState) return;

        // 隐藏
        this.openState = false;
        this.dom.hide();
        this.isShowMaskLayer();
        this.dom.trigger('close');
    },
    resize: function(){
        var that = this;
        if (that.dom.css('display') != 'none') {
            var nScrollTop = $(window).scrollTop();
            $('body').attr('data', nScrollTop);
            ((!that.config.overflow) ||  (that.config.overflow != 'auto')) && $('html,body').css('overflow', 'hidden');
            var nW = that.dom.width() / 2;
            var nTop = nScrollTop + ($(window).height() - that.dom.height())/2 - 20;
            nTop = nTop < nScrollTop ? nScrollTop : nTop;
            that.dom.css('top', nTop+'px');
        }
    },
    isShowMaskLayer: function(){
        var that = this;
        var isShow = false;
        $.each(Dahei.Common.windowList, function(key, thisWindow){
            if (thisWindow.openState && thisWindow.lock) {
                isShow = true;
            }
        });
        if (isShow) {
            var nScrollTop = $(window).scrollTop();
            $('body').attr('data', nScrollTop);
            ((!that.config.overflow) ||  (that.config.overflow != 'auto')) && $('html,body').css('overflow', 'hidden');
            var nW = this.dom.width() / 2;
            var nTop = nScrollTop + ($(window).height() - this.dom.height())/2 - 20;
            nTop = nTop < nScrollTop ? nScrollTop : nTop;
            this.dom.css('top', nTop+'px');
            var nLeft = ($(window).width() - this.dom.outerWidth()) / 2;
            this.dom.css({'left': nLeft +'px'});

            var alp=$("#alpha");
            //var alpH=(document.documentElement.clientHeight || document.body.clientHeight) + (document.documentElement.scrollTop || document.body.scrollTop) + 50;
            //alp.css({"opacity":0.8,"height":alpH+"px"});
            alp.css({"opacity":0.8,"height":"2220px"});
            $('#alpha').show();
        } else {
            $('html,body').attr('style', '');
            var bodyScrolltop = $('body').attr('data');
            if (bodyScrolltop && bodyScrolltop !='') {
                $(window).scrollTop(bodyScrolltop);
            }
            $('#alpha').hide();
        }
        $(window).bind('scroll', function(){
            $('.popscroll').each(function(){
                if ($(this).css('display') != 'none') {
                    var nScrollTop = $(window).scrollTop();
                    $('body').attr('data', nScrollTop);
                    ((!that.config.overflow) ||  (that.config.overflow != 'auto')) && $('html,body').css('overflow', 'hidden');
                    var nW = that.dom.width() / 2;
                    var nTop = nScrollTop + ($(window).height() - that.dom.height())/2 - 20;
                    nTop = nTop < nScrollTop ? nScrollTop : nTop;
                    $(this).css('top', nTop+'px');
                }
            });
        });
    }
};
Dahei.Common.window.fn.init.prototype = Dahei.Common.window.fn;
//}}}



//设置cookie{{{
function setCookie(name, value, time)
{
    var nameString = name + '=' + escape(value);
    var expiryString = "";
    if(time !== 0) {
        var expdate = new Date();
        if(time == null || isNaN(time)) time = 60*60*1000;
        expdate.setTime(expdate.getTime() +  time);
        expiryString = ' ;expires = '+ expdate.toGMTString();
    }
    var path = " ;path =/";
    document.cookie = nameString + expiryString + path;
};
//}}}

//获取cookie{{{
function getCookie(sName)
{
    var aCookie = document.cookie.split('; ');
    for (var i=0; i < aCookie.length; i++) {
        var aCrumb = aCookie[i].split('=');
        if (sName == aCrumb[0])
            return unescape(aCrumb[1]);
    }
    return '';
}
//}}}

// 剪切板函数{{{
function copyToClipboard(txt)
{
    if (!txt) return false;
    if (window.clipboardData) {
        window.clipboardData.clearData();
        window.clipboardData.setData("Text",txt);
        alert("复制成功。");
    } else if(navigator.userAgent.indexOf("Opera")!= -1) {
        window.location = txt;
    } else if (window.netscape) {
        try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        } catch (e) {
            alert("您的firefox安全限制限制您进行剪贴板操作，请打开'about:config'将signed.applets.codebase_principal_support'设置为true'之后重试");
            return false;
        }
        var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
        if (!clip) return false;
        var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
        if (!trans) return false;
        trans.addDataFlavor('text/unicode');
        var str = new Object();
        var len = new Object();
        var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
        var copytext = txt;
        str.data = copytext;
        trans.setTransferData("text/unicode",str,copytext.length*2);
        var clipid = Components.interfaces.nsIClipboard;
        if (!clip) return false;
        clip.setData(trans,null,clipid.kGlobalClipboard);
    }
};
//}}}

// 幻灯片插件{{{
var slider=function(opt){
    //settings
    var settings=jQuery.extend({
        sliderBox:"#slider",//整个图片展示id
        sliderList:"#slider ul li",//图片列表
		sliderele:"slider",
        now:0,//默认选中标签下标
		arrow:{
				isBtn:false,//是否需要左右按钮
				leftBtn:"#",//左边按钮
				rightBtn:"#"//右边按钮
			},
		showsize:2,//主图显示个数
		isAutoPlay:false,//是否自动播放
		showTime:3000,//自动播放切换时间
		isSubNum:false,//是否增加数字导航
		hasTitle:false,//是否带标题
		smallImg:false,//是都带缩略图
		smallSize:3,//缩略图显示个数
		organWidth:0,//风琴效果---水平（宽度）
		organHeight:0,//风琴效果---垂直（高度）
		bind:"mouseover",//鼠标事件
		effect:"fade",//大图切换效果 left,top,fade,organ
		noto:false,
		callBack:false//回调
		
    },opt);
    var 
        $now=settings.now,
		aBtn=settings.arrow,
		$showsize=settings.showsize,
		isBtn=aBtn.isBtn,
		$leftBtn=$(aBtn.leftBtn),
		$rightBtn=$(aBtn.rightBtn),
		$sliderBox=$(settings.sliderBox),
        $sliderList=$(settings.sliderList),
		isAutoPlay=settings.isAutoPlay,
		isSubNum=settings.isSubNum,
		hasTitle=settings.hasTitle,
		smallImg=settings.smallImg,
		$smallSize=settings.smallSize,
		$organWidth=settings.organWidth,
		$organHeight=settings.organHeight,
		$bind=settings.bind,
		$effect=settings.effect,
		$showTime=settings.showTime,
        callBack=settings.callBack,
		sliderele=settings.sliderele,
		noto=settings.noto;
    var maxSize=$sliderList.size();//列表总条数
	var $liH=$sliderList.eq(0).outerHeight(true);
	var $liW=$sliderList.eq(0).outerWidth(true);//单张图片的宽度+（包括margin padding border的值）
	var $liW2=$sliderList.eq(0).outerWidth()//单张图片的宽度（包括padding border,不包括margin的值）
	var $liMargin=$liW-$liW2;//求出 margin 左右的值
	if($effect!="top")
	{
		$sliderList.parent().parent().css("width",$liW*$showsize-$liMargin+'px');//图片展示区域尺寸
	}
	
	//$sliderList.parent().css("width",maxSize*$liW);//图片列表的总宽度
	imgEffect($now);
	
	function imgEffect(index)
	{
		switch($effect)
		{
			case "left":
			            $sliderList.parent().css({position:"absolute",top:"0",width:maxSize*$liW+'px',height:$liH+'px'});
						$sliderList.css({"float":"left"});
						$sliderList.parent().stop(true).animate({"left":-$liW*index+'px'},{duration:1000,easing:"easeInOutCubic"});
						break;
			case "top":	
			           $sliderList.parent().css({width:$liW+'px',height:maxSize*$liH+'px'});
					   $sliderList.parent().stop(true).animate({"marginTop":-$liH*index+'px'},{duration:500,easing:"easeInOutCubic"});
					   break;	
			case "fade": 
					   $sliderList.parent().css({position:"relative",width:$liW+'px',height:$liH+'px'});
					   $sliderList.css({"position":"absolute",left:0,top:0,zIndex:1});
					   $sliderList.eq(index).show().stop(true).css({zIndex:99}).animate({opacity:1},{duration:800,easing:"swing"}).siblings("li").animate({opacity:0},{duration:800,easing:"swing"}).hide();
					   break;

			case "organ":
					   $sliderList.find(".divHand").bind($bind,function(){
						  $(this).parent().addClass("liOn").siblings().removeClass("liOn");
						 // $(this).siblings().show().stop(true).animate({height:$organHeight+'px'},{duration:500,easing:"easeOutQuad",queue:false});
						 // $(this).parent().siblings().find(".drapBox").stop(true).animate({height:0},{duration:500,easing:"easeOutQuad", queue:false,complete:function(){$(this).hide()}})
						  $(this).siblings().show().css({height:$organHeight+'px'});
						  $(this).parent().siblings().find(".drapBox").css({height:0,"display":"none"})
					   })
					   break;		   
		}
	}	
	
	
	if(hasTitle)
	{
		var subNumHtml='<div id="subTitle"></div>';
		$sliderBox.append(subNumHtml);
		var imgName=$sliderList.find("img").eq(0).attr("name"); 
		var imgLink=$sliderList.find("a").eq(0).attr("href"); 
		var titleListHtml='<span><a href="'+imgLink+'" target="_blank">'+imgName+'</a></span>';	
		$("#subTitle").append(titleListHtml);	
	}
	
	if(isSubNum)//判断如果有数字导航时执行
	{
		if(hasTitle)
		{
			var subNumHtml='<div id="subNum"><div id="subTitle"></div><div id="subList"></div></div>';
			$sliderBox.append(subNumHtml);
			var imgName=$sliderList.find("img").eq(0).attr("name"); 
			$("#subTitle").html(imgName);
		}
		else
		{
			var subNumHtml='<div id="subNum"><div id="subList"></div></div>';
			$sliderBox.append(subNumHtml);
		}
		
		for(var i=0;i<maxSize;i++)
			{
				var numListHtml='<span></span>'
				$("#subList").append(numListHtml);	
			}
			$("#subList").find("span").eq(0).addClass("sOn");
			
		$("#subList").find("span").bind($bind,
			function(){
				$(this).addClass("sOn").siblings().removeClass("sOn");
				var index=$("#subList span").index($(this))
				    $now=index;	
				    imgEffect($now);
					//$sliderList.parent().stop(true).animate({"left":-$liW*index+'px'},{duration:1000,easing:"easeInOutCubic"});
			});
	};
	
	
	if(smallImg)   //判断是否带缩略图
	{

		var smallImgHtml='<div id='+sliderele+'><ul></ul></div>'
		$sliderBox.append(smallImgHtml);
		$sliderList.each(function(){
			var bigSrc=$(this).find("img").attr("src");
			bigSrc=bigSrc.split(".");		
			var smallImgList='<li><a href="javascript:void(0)"><img src="'+bigSrc[0]+'b.png" /></a><span></span></li>';
			
		$("#"+sliderele).children("ul").append(smallImgList);
		
		});
		
		var smallUl=$("#"+sliderele).children("ul");
		var smallLi=$("#"+sliderele).children("ul").children("li");
		var smallLiW=$("#"+sliderele).children("ul").children("li").eq(0).outerWidth(true);
		var smallLiW2=$("#"+sliderele).children("ul").children("li").eq(0).outerWidth();
		var smallLiMargin=smallLiW-smallLiW2;
		var smallLiH=$("#"+sliderele).children("ul").children("li").eq(0).outerHeight(true);
		var smallLiH=$("#"+sliderele).children("ul").children("li").eq(0).addClass("lOn");
		if(noto)
		{
		}else{
        $("#smallImg").css({
			width:smallLiW*$smallSize-smallLiMargin+'px',
			height:smallLiH+"px",
			overflow:"hidden"
		});
		
		smallUl.css({
			width:maxSize*smallLiW+'px',
			height:smallLiH+"px",
			position:"absolute",
			left:0,
			top:0	
		});
		}
		smallLi.bind($bind,
			function(){
				var index=$(this).index();
				    smallLi.removeClass("lOn");
				    $(this).addClass("lOn");
					if(maxSize-$smallSize>index-1)
					{
						smallUl.stop(true).animate({"left":-smallLiW*index+'px'},{duration:1000,easing:"easeInOutCubic"});	
					}	
					else if(index>=maxSize-1)
					{
						smallUl.stop(true).animate({"left":-smallLiW*(maxSize-$smallSize)+'px'},{duration:1000,easing:"easeInOutCubic"});	
					}
					
					else if(index>maxSize)
					{
						smallUl.stop(true).animate({"left":0},{duration:1000,easing:"easeInOutCubic"});
					}

					if(hasTitle)
					{
						var imgName=$sliderList.find("img").eq(index).attr("name"); 
						var imgLink=$sliderList.find("a").eq(index).attr("href"); 
						var titleListHtml='<span><a href="'+imgLink+'" target="_blank">'+imgName+'</a></span>';	
						$("#subTitle").html(titleListHtml);
					}
					
						
					if($now!=index)
					{
						imgEffect(index);
					}
					if(noto)
					{
						
					}else{
					$sliderList.parent().stop(true).animate({"left":-$liW*index+'px'},{duration:1000,easing:"easeInOutCubic"});	
					}
					$now=index;	
					
			});
			
	}
	
	if(isBtn==true)//判断如果有左右箭头时执行
	{
		if(maxSize>$showsize)
		{
			var arrowHtml='<a class="aleft lLast" href="javascript:void(0)">向左</a><a class="aright" href="javascript:void(0)">向右</a>';
			$sliderBox.append(arrowHtml);
			$leftBtn=$(aBtn.leftBtn);
			$rightBtn=$(aBtn.rightBtn);
			$rightBtn.click(clickRight);
			$leftBtn.click(clickLeft);
		}	
	}	
	
	
   //图片滚动的位置
	function imgPosition()
	{
		if(smallImg)
		{
			 smallLi.removeClass("lOn");
		     smallLi.eq($now).addClass("lOn");
			//if(maxSize-$smallSize>$now-1)
//			{
//				smallUl.stop(true).animate({"left":-smallLiW*$now+'px'},{duration:1000,easing:"easeInOutCubic"});	
//			}	
//
//			else if($now>=maxSize-1)
//			{
//				smallUl.stop(true).animate({"left":-smallLiW*(maxSize-$smallSize)+'px'},{duration:1000,easing:"easeInOutCubic"});	
//			}
//			
//			else if($now>maxSize)
//			{
//				smallUl.stop(true).animate({"left":0},{duration:1000,easing:"easeInOutCubic"});
//			}	
		}
		imgEffect($now);
		//$sliderList.parent().stop(true).animate({"left":-$liW*$now+'px'},{duration:1000,easing:"easeInOutCubic"});
	}
	
	//点击左箭头
	function clickLeft()
	{   
	    if($sliderList.parent().is(":animated")){return;}
		$rightBtn.removeClass("rLast");

      
	  	if(isBtn==true&&$now==1)
			{
				$now=0;
				$leftBtn.addClass("lLast");
			}

		else if($now<=0)
		{
			if(isBtn==true)
			{
				$now=0;
			}
			else
			{
				$now=maxSize-$showsize;
			}
	
		}
		else
		{
			$now--;
		}

		imgPosition();
	}
	
	
	//点击右箭头
	function clickRight()
	{   
		if($sliderList.parent().is(":animated")){return;}
		$leftBtn.removeClass("lLast");

        if(isBtn==true&&$now==(maxSize-$showsize)-1)
			{
				$now=maxSize-$showsize;
				$rightBtn.addClass("rLast");
			}

		else if($now>=maxSize-$showsize)
		{
			if(isBtn==true)
			{
				$now=maxSize-$showsize;
			}
			else
			{
				$now=0;	
			}
			
		}
		else
		{
			$now++;
		}
		
		if(hasTitle)
		{
			var imgName=$sliderList.find("img").eq($now).attr("name"); 
			var imgLink=$sliderList.find("a").eq($now).attr("href"); 
		    var titleListHtml='<span><a href="'+imgLink+'" target="_blank">'+imgName+'</a></span>';	
			$("#subTitle").html(titleListHtml);
		}
		
		if(isSubNum==true)
		{
			if(hasTitle==true)
			{
				var imgName=$sliderList.find("img").eq($now).attr("name"); 
				$("#subTitle").html(imgName);
			}	
			$("#subList").find("span").removeClass("sOn").eq($now).addClass("sOn");	
		}
		
		imgPosition();
			
	}
	
	//自动播放
	var timer=null;
	function autoPlay()
	{
		clearInterval(timer);
		timer=setInterval(clickRight,$showTime);		
	}
	if(isAutoPlay)
	{
		autoPlay();
		$sliderBox.hover(
		function(){clearInterval(timer);},
		function(){autoPlay();})
	}
};
//}}}

//拖动插件{{{
function Piled(){
    this.iZindex = 1000;
}
Piled.prototype = {
    init : function(id,drag){
        //this.oParent = document.getElementById(id);
        //this.oMove= document.getElementById(drag);
        this.widthAll = document.documentElement.clientWidth;
        this.doc=document;
        this.heightAll = document.documentElement.clientHeight;
        this.oParent = this.getByClass(id);
        this.oDrag = this.getByClass(drag);
        for(var i=0;i<this.oParent.length;i++)
        {  
            if (this.oDrag[i]) {
                this.drag(this.oDrag[i],this.oParent[i]);
            }
        }
        
    },
    getByClass : function(sClass)
    {
        var oEla=this.doc.getElementsByTagName("*");
        var sResult=[];
        for(var i=0; i<oEla.length;i++)
        {
           if(oEla[i].className.indexOf(sClass)!=-1)
           {
              sResult.push(oEla[i]);
           }
        }
        return sResult;
    }, 
    drag : function(obj,oPa){
        var disX = 0;
        var disY = 0;
        
        var This = this;
        
        var nowL = 0;
        var nowT = 0;
        obj.onmousedown = function(ev){
            var ev = ev || window.event;
            disX = ev.clientX - oPa.offsetLeft;
            disY = ev.clientY - oPa.offsetTop;
            
            //nowL = obj.offsetLeft;
            //nowT = obj.offsetTop;
        
            oPa.style.zIndex = This.iZindex++;
        
            if(obj.setCapture){
                obj.setCapture();
            }
        
            document.onmousemove = function(ev){
                var ev = ev || window.event;
                var top=document.body.scrollTop || document.documentElement.scrollTop;
                var l=ev.clientX-disX;
                var t=ev.clientY-disY;
                if(l<0)
                {
                    l=0;
                }
                else if(l>This.widthAll-oPa.offsetWidth)
                {
                    l=This.widthAll-oPa.offsetWidth;
                }
                if(t<0)
                {
                    t=0;
                }
                else if(t>top+This.heightAll-oPa.offsetHeight)
                {
                    t=top+This.heightAll-oPa.offsetHeight;
                }
                oPa.style.left = l + 'px';
                oPa.style.top = t + 'px';
            };
            
            document.onmouseup = function(){
                document.onmousemove = null;
                document.onmouseup = null;
                if(obj.releaseCapture){
                    obj.releaseCapture();
                }
                
            };
            
            return false;
        };
    }
};
//}}}

//判断字符串{{{
function cutLen(str, width) {
    var realLength = 0, len = str.length, charCode = -1;
    for (var i = 0; i < len; i++) {
        charCode = str.charCodeAt(i);
        if (charCode >= 0 && charCode <= 128) {
            realLength += 1;
        } else {
            realLength += 2;
        }
        if (width <= realLength) {
            return str.substr(0, i+1) + '...';
        }
    }
    return str;
};
//}}}

/*时间格式化{{{
 * 和PHP一样的时间戳格式化函数
 * @param  {string} format    格式
 * @param  {int}    timestamp 要格式化的时间 默认为当前时间
 * @return {string}           格式化的时间字符串
 */
date_format = function(format, timestamp) {
    var a, jsdate=((timestamp) ? new Date(timestamp*1000) : new Date());
    var pad = function(n, c){
        if((n = n + "").length < c){
            return new Array(++c - n.length).join("0") + n;
        } else {
            return n;
        }
    };
    var txt_weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    var txt_ordin = {1:"st", 2:"nd", 3:"rd", 21:"st", 22:"nd", 23:"rd", 31:"st"};
    var txt_months = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; 

    var f = {
        // Day
        d: function(){return pad(f.j(), 2)},
        D: function(){return f.l().substr(0,3)},
        j: function(){return jsdate.getDate()},
        l: function(){return txt_weekdays[f.w()]},
        N: function(){return f.w() + 1},
        S: function(){return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th'},
        w: function(){return jsdate.getDay()},
        z: function(){return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0},

        // Week
        W: function(){
            var a = f.z(), b = 364 + f.L() - a;
            var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;
            if(b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b){
                return 1;
            } else{
                if(a <= 2 && nd >= 4 && a >= (6 - nd)){
                    nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");
                    return date("W", Math.round(nd2.getTime()/1000));
                } else{
                    return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
                }
            }
        },

        // Month
        F: function(){return txt_months[f.n()]},
        m: function(){return pad(f.n(), 2)},
        M: function(){return f.F().substr(0,3)},
        n: function(){return jsdate.getMonth() + 1},
        t: function(){
            var n;
            if( (n = jsdate.getMonth() + 1) == 2 ){
                return 28 + f.L();
            } else{
                if( n & 1 && n < 8 || !(n & 1) && n > 7 ){
                    return 31;
                } else{
                    return 30;
                }
            }
        },

        // Year
        L: function(){var y = f.Y();return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0},
        //o not supported yet
        Y: function(){return jsdate.getFullYear()},
        y: function(){return (jsdate.getFullYear() + "").slice(2)},

        // Time
        a: function(){return jsdate.getHours() > 11 ? "pm" : "am"},
        A: function(){return f.a().toUpperCase()},
        B: function(){
            // peter paul koch:
            var off = (jsdate.getTimezoneOffset() + 60)*60;
            var theSeconds = (jsdate.getHours() * 3600) + (jsdate.getMinutes() * 60) + jsdate.getSeconds() + off;
            var beat = Math.floor(theSeconds/86.4);
            if (beat > 1000) beat -= 1000;
            if (beat < 0) beat += 1000;
            if ((String(beat)).length == 1) beat = "00"+beat;
            if ((String(beat)).length == 2) beat = "0"+beat;
            return beat;
        },
        g: function(){return jsdate.getHours() % 12 || 12},
        G: function(){return jsdate.getHours()},
        h: function(){return pad(f.g(), 2)},
        H: function(){return pad(jsdate.getHours(), 2)},
        i: function(){return pad(jsdate.getMinutes(), 2)},
        s: function(){return pad(jsdate.getSeconds(), 2)},
        //u not supported yet

        // Timezone
        //e not supported yet
        //I not supported yet
        O: function(){
            var t = pad(Math.abs(jsdate.getTimezoneOffset()/60*100), 4);
            if (jsdate.getTimezoneOffset() > 0) t = "-" + t; else t = "+" + t;
            return t;
        },
        P: function(){var O = f.O();return (O.substr(0, 3) + ":" + O.substr(3, 2))},
        //T not supported yet
        //Z not supported yet

        // Full Date/Time
        c: function(){return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P()},
        //r not supported yet
        U: function(){return Math.round(jsdate.getTime()/1000)}
    };

    return format.replace(/[\\]?([a-zA-Z])/g, function(t, s){
        if( t!=s ){
            // escaped
            ret = s;
        } else if( f[s] ){
            // a date function exists
            ret = f[s]();
        } else{
            // nothing special
            ret = s;
        }
        return ret;
    });
};
//}}}

//错误正确提示    
function setSucOrWarn(obj, classnames, isreal, msg)
{
    var showmsg = msg ? msg : '&nbsp';
    if($('#'+obj).length) {
        document.getElementById(obj).className = classnames;
        $("#"+obj).html(showmsg);
        if(classnames == 'warn') {
            if($("#"+obj).prev('input').length) {
                $("#"+obj).prev('input').addClass('iErr');
            } else if($("#"+obj).prev('.sDiv').length){
                $("#"+obj).prev('.sDiv').find('.selectMain').addClass('selErr');
            } else if($("#"+obj).prev('textarea').length) {
                $("#"+obj).prev('textarea').addClass('iErr');
            }
        }
    }
    if(isreal) {
        return msg ?  true : false;
    } else {
        if(msg) {
            //alert(msg);
            return false;
        }
        return true;
    }
    return false;
}

function waitshow()
{
    if($('#alpha2').length && $('.loading').length) {
        $('#alpha2').height((document.documentElement.clientHeight || document.body.clientHeight) + (document.documentElement.scrollTop || document.body.scrollTop) + 200 + 'px').show();
        $('.loading').show();
        document.documentElement.style.overflow = 'hidden';
        document.body.style.overflow = "hidden";
    }
}

function waithide()
{
    if($('#alpha2').length && $('.loading').length) {
        $('#alpha2').height('0px').hide();
        $('.loading').hide();
        document.documentElement.style.overflow = 'auto';
        document.body.style.overflow = "auto";
    }
}

// 初始化
$(document).ready(function(){
    if (!window.WEBSERVER) {
        window.WEBSERVER = '';
    }
    Dahei.Common.init();
});


