var UTIL = {};
var HIDDEN ={"readme":"do not use in public"};

UTIL.getFrag=function(k, def, kbox){
	var url = DOMAIN.sso+'/ajax/getFrag.do?callback=?';
	var params = {"key":k};

	$.getJSON(url, params, function(data){
		var u = data.msg;
		if(u == null || u == "") {
			u = def;
		}
		$("#"+kbox).html(u);
	});
};

UTIL.getNewFrag=function(k, def, kbox){
	var url = DOMAIN.sso+'/fragAjax/queryFrag.do?callback=?';
	var params = {"key":k};

	$.getJSON(url, params, function(data){
		var u = data.msg;
		if((u == null || u == "") && def) {
			u = def;
		}
		if(u){
			$("#"+kbox).html(u);
		}
	});
};

UTIL.getLoginUser = function(loginedBox, notLoginBox, nameBox){
	var url = DOMAIN.sso+'/ajax/getLoginUser.do?callback=?';
	var params = {};
	$.getJSON(url, params, function(data){
		if(data.code==1) {
			var u = data.msg;
			$("#"+loginedBox).show();
			$("#"+notLoginBox).hide();
			$("#"+nameBox).html(u);
		}
	});
};

UTIL.countChar = function(textareaName,spanName,maxSize){
	if(!maxSize){
		maxSize = 200;
	}
	if(document.getElementById(textareaName).value.length > maxSize){
		EventUtil.alert("您输入的字数超过限制!");
		document.getElementById(textareaName).value = document.getElementById(textareaName).value.substring(0,maxSize);
		return false;
	}
	var curr = document.getElementById(spanName).innerHTML = maxSize - document.getElementById(textareaName).value.length;
	document.getElementById(spanName).innerHTML = curr.toString();
	document.getElementById(spanName).style="color:red;font-family:Constantia,Georgia;font-size:22px;";
    return true;
};

UTIL.sendScript=function(questionBox,tusernameBox,submitBtn) {
	var tusername = $("#"+tusernameBox).val();
    var question = $("#"+questionBox).val();
    if(question==""){
    	UTIL.alert("请输入您的问题！");
    	return;
    }

   var str = question.replace(/<script.*>.*?<\/script>/ig,"");
       str = str.replace(/<style.*>.*?<\/style>/ig,"");
       str = str.replace(/<.*?>/g,""); //去除所有内容
       str = str.replace(/[ | ]*\n/g,'\n'); //去除行尾空白
   	   str = str.replace(/\n[\s| | ]*\r/g,'\n');
   	   str=str.replace(/&nbsp;/ig,'');

    if(str.indexOf("function") > 0 || str.indexOf("var") > 0 || str.indexOf("text/javascript") > 0 ||
        str.indexOf("document") > 0 || str.indexOf("style") > 0 || str.indexOf("if") > 0 ||
		str.indexOf("onclick") > 0 || str.indexOf("window.") > 0 || str.indexOf("else") > 0 ||
		str.indexOf("return") > 0 || str.indexOf("this.") > 0 || str.indexOf("typeof") > 0 )
    {
    	UTIL.alert('不能包含非法字符！请修改后，重新提交！');
    }

    UTIL.buttonDisabled(submitBtn, 15000);
	var url = DOMAIN.group+'/ajax/sendScript.do?callback=?';
	var params = {"tUsername":tusername,"question":str};
	$.getJSON(url, params, function(data){
		if(data.code!=1) {
			$("#"+questionBox).val('');
			UTIL.alert(data.msg);
		}
		else {
			UTIL.alert(data.msg);
			//UTIL.showLoginForm();
		}
	});
};

/**
 * @param url 请求url
 * @param param 传入参数对象（可以是Array）
 * @param submitBtn 需要禁止的提交按钮
 * @param callBack 回调函数
 * @param time 限制时间
 */
UTIL.sendScriptBase=function(url,params,submitBtn,time,callBack) {
	if(submitBtn!=undefined){
		UTIL.buttonDisabled(submitBtn, time);
	}
	$.getJSON(url, params, callBack);
};

UTIL.showLoginForm=function() {
	var loginForm = $('#loginForm');
	if(loginForm == null || loginForm.length==0){
		loginForm = HIDDEN.buildLoginForm();
	}

	$.blockUI({ message: loginForm, css: {backgroundColor: ''}});
};

HIDDEN.buildLoginForm=function(){
	var loginFormHtml = '<div class="live_fucheng" id="loginForm" style="display:none;">';
	loginFormHtml += '<div class="pos">';
	loginFormHtml += '<h2><a href="javascript:;" onclick="$.unblockUI();"><img src="'+LOCATION.base+'/b/images/v2/live/closed.jpg"></a>提示信息</h2>';
	loginFormHtml += '<p>此信息需要您登录后才能使用</p>';
	loginFormHtml += '<ul>';
	loginFormHtml += '<li><span class="people">我已经注册了，现在要</span><input type="button" value="登录" onclick="window.open(\''+DOMAIN.sso+'/jryLogin.do\', \'_self\');"></li>';
	loginFormHtml += '<li><span class="heart">我刚刚来这里，还想再</span><input type="button" value="逛逛" onclick="$.unblockUI();"></li>';
	loginFormHtml += '<li><span class="house">我想加入百道网，我要</span><input type="button" value="注册" onclick="window.open(\''+DOMAIN.sso+'/jryLogin.do\', \'_self\');"></li>';
	loginFormHtml += '</ul></div></div>';

	var css = '<link href="'+LOCATION.base+'/b/css/v2/logintip.css" type="text/css" rel="stylesheet" />';
	$(css).appendTo("head");
	$(loginFormHtml).insertAfter("body");
	return $('#loginForm');
};


UTIL.checkLogin=function(url1){
	var url = DOMAIN.sso + "/checkLogin.do?callback=?";
	var params = {"t":new Date().getTime()};
	$.getJSON(url, params, function(data){
		if(data.code==0) {
			UTIL.showLoginForm();
		}
		else {
			window.open(url1, "_blank");
		}
	});
};

UTIL.loginUser=function(usernameBox, passwordBox, rememberMeBox){
	var username = $("#"+usernameBox).val();
	var password = $("#"+passwordBox).val();
	var rememberMe = $("#"+rememberMeBox).attr("checked");
	if(rememberMe=='checked') {
		rememberMe = "true";
	}
	var url = DOMAIN.sso + "/loginAjax.do?callback=?";
	var params = {"username":username, "password":password, "rememberMe":rememberMe, "t":new Date().getTime()};
	$.getJSON(url, params, function(data){
		if(!data.succes) {
			alert("登录失败，用户名或密码不正确");
		}
		else {
			$.unblockUI();
			UTIL.alert("登录成功");
			window.location.reload(true);
		}
	});
};

UTIL.alert=function(msg,title,time) {
	if(!title) title = "系统提示";
	if(!msg) msg = "请等待...";
	if(!time) time = 5000;

	$.growlUI(title, msg, time);
};

UTIL.scrollDown=function (target) {
	var cdiv = null;
	cdiv = document.getElementById(target);
	cdiv.scrollTop = cdiv.scrollHeight*2;
};

UTIL.alert=function(msg,title,time) {
	if(!title) title = "系统提示";
	if(!msg) msg = "请等待...";
	if(!time) time = 3000;

	$.growlUI(title, msg, time);
};

UTIL.requestValue=function(params){
	var url = location.href;
	var paraString = url.substring(url.indexOf("?")+1,url.length).split("&");
	var paraObj = {};
	for (var i=0; j=paraString[i]; i++){
		paraObj[j.substring(0,j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=")+1,j.length);
	}
	var returnValue = paraObj[params.toLowerCase()];
	if(typeof(returnValue)=="undefined"){
		return "";
	}else{
		return returnValue;
	}
};

UTIL.buttonDisabled=function(btnId, time){
	var btn = $("#"+btnId);
	btn.attr("disabled", "true");
	var count = time/1000;
	var origText = btn.val();
	var code = "HIDDEN.buttonValueChange('"+btnId+"', '"+count+"', '"+origText+"')";
	setTimeout(code, 1000);
};

HIDDEN.buttonValueChange=function(btnId, count, origText) {
	var btn = $("#"+btnId);
	btn.val(origText+"("+count+")");
	count --;
	var code = null;
	if(count > 0) {
		code = "HIDDEN.buttonValueChange('"+btnId+"', '"+count+"', '"+origText+"')";
	}
	else {
		code = "HIDDEN.buttonOk('"+btnId+"', '"+origText+"')";
	}
	setTimeout(code, 1000);
};

HIDDEN.buttonOk=function(btnId, origText) {
	var btn = $("#"+btnId);
	btn.val(origText);
	btn.removeAttr("disabled");
};

Date.prototype.format = function(format){
	var o ={
		"M+" : this.getMonth()+1, //month
		"d+" : this.getDate(), //day
		"h+" : this.getHours(), //hour
		"m+" : this.getMinutes(), //minute
		"s+" : this.getSeconds(), //second
		"q+" : Math.floor((this.getMonth()+3)/3), //quarter
		"S" : this.getMilliseconds() //millisecond
	};

	if(/(y+)/.test(format)) {
		format=format.replace(RegExp.$1,(this.getFullYear()+"").substr(4 - RegExp.$1.length));
	}
	for(var k in o) {
		if(new RegExp("("+ k +")").test(format)) {
			format = format.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
		}
	}
	return format;
};

function setCookie(c_name,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
};

function getCookie(c_name) {
	if (document.cookie.length>0) {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1){
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
				return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}

(function(window){
    var width;
    var height;
    var onloadId;
    var margintop;
    var timer = null;
    var speed = 500;
    var test = false;
    var number = 100;
    var progressDiv = null;
    var innerDiv = null;
    var outDiv = null;
    var textConnent = '';
    var timeaa=null;
    var eightTimer = null;
    var eightT = 0;

    var Progress=function(optition){
      width = 325+'px';
      height = 15+'px';
      margintop = optition.margintop || (document.documentElement.clientHeight/2-125)
      onloadId = optition.id;
      this.init(onloadId)
    }

    Progress.prototype = {
      init:function(ele){
        var self = this;
        bodyColorDiv = document.createElement('DIV');
        outDiv = document.createElement('DIV');
        progressDiv = document.createElement('DIV');
        innerDiv = document.createElement('DIV');
        textConnent = document.createElement('SPAN') 
        this.addStyle(textConnent,{fontSize:'20px',color:'rgb(200,90,31)',display:'block',position:'absolute',top:'20px',fontFamily:'arial',left:'150px'})
        this.addStyle(bodyColorDiv,{height:document.documentElement.clientHeight+'px'
          ,width:document.documentElement.clientWidth+'px',background:'#161616',overflow:'hidden'})
        this.addStyle(innerDiv,{width:width,height:height,position:'absolute',top:0,right:'-2px',background:'url("images/progressBg1.png") right'})
        this.addStyle(progressDiv,{width:width,height:height,position:'relative',background:'url("images/progressBg2.png")'})
        this.addStyle(outDiv,{width:width,margin:'0 auto',background:'url("images/server-16.png") center no-repeat','paddingTop':'110px','marginTop':margintop+'px'})
        textConnent.innerHTML = '0%'
        progressDiv.appendChild(textConnent)
        progressDiv.appendChild(innerDiv)
        outDiv.appendChild(progressDiv)
        bodyColorDiv.appendChild(outDiv)
        document.body.appendChild(bodyColorDiv)
        $(ele).hide();
        this.ready();
        this.eightTimeBeggin()
        timer = setInterval(function(){
          return self.step.call(self)
        },speed)
      },
      step:function(){
        if(test){
          clearInterval(timer);
        }
        else{
          width = parseInt(width)
          width-=Math.floor(Math.random()*width*(number--)/(number*15))
          width = width<=5 ? 5 : width
          textConnent.innerHTML = parseInt((325-width)*100/325)+'%'
          $(innerDiv).css('width',width+'px')
        }
      },
      eightTimeBeggin:function(){
        eightTimer = setInterval(function(){
          if(eightT++>=6){
            clearInterval(eightTimer)
            $(bodyColorDiv).hide();
            $(onloadId).show();           
          }
        },1000)
      },
      addStyle:function(ele,css){
        for(var i in css){
          ele.style[i] = css[i]
        }
      },
      stepFast:function(callback){
        // $(innerDiv).animate({'width':'0'},500,callback)
        this.widthReduce(callback)
      },
      widthReduce:function(callback){
        width = parseInt($(innerDiv).css('width'))
        timeaa = setInterval(function(){
          if(width>=1){
            width = width-5
            $(innerDiv).css('width',width)
            textConnent.innerHTML = parseInt((325-width)*100/325)+'%'
          }
          else{
            clearInterval(timeaa);
            callback()
          }
        },20)
      },  
      ready:function(){
        var self = this;
        var img = document.createElement('IMG');
        window.onload = function(){
          test = true;    
		  // document.body.srcoll='no';
          self.stepFast(function(){
             $(bodyColorDiv).hide();
             $(onloadId).show()
          })
        }
      }
    }
    this.progress = Progress;
  })(window)