
var LOAD_IMAGE = "<img src='/style/images/ajax_loading.gif' style='margin-left:20px;'/>";
var SAVING_IMAGE = "<img src='/style/images/ajax_saving.gif'/>";
var START_DATE = "_START_DATE"; //全局开始日期
var END_DATE = "_END_DATE";//全局结束日期
var SYSTEM_TIP = null;
var SYSTEM_TIP_INTERVAL = 5000;
var SYSTEM_ERROR_TIP_INTERVAL = 10000;
var JUMP_ANALYSIS_ASSETS = "JUMP_ANALYSIS_ASSETS";
var PORTLET_COOKIE = "PORTLET_COOKIE";

var MAIN_ID = "Main";

function callId(){
	var random = Math.floor(Math.random() * 10001);
  	var id = (random + "_" + new Date().getTime()).toString();
  	return id;
}

function firstDayInMonth(date){
	var curDate = new Date();
	if(typeof date =='object'){
		curDate.setTime(date.getTime());
	}
	curDate.setDate(1);
	curDate.setHours(0,0,0);

	return curDate;
}


function lastDayInMonth(date){
	var curDate = new Date();
	if(typeof date =='object'){
		curDate.setTime(date.getTime());
	}
	//将下月1号减一天得到当月最后一天
	curDate = firstDayInMonth(curDate);
	curDate.setMonth(curDate.getMonth()+1);
	curDate.setDate(1);
	curDate.setDate(curDate.getDate()-1);

	curDate.setHours(23,59,59);
	return curDate;
}
/*系统提示相关方法*/
function adjustTipPosition(){
	var scrollTop = document.body.scrollTop;
	if(document.getElementById("Main")){
		scrollTop = document.getElementById("Main").scrollTop
	}
	if(scrollTop>0){
		$("#idActionTip").css("top",scrollTop+"px");
	}else{
		$("#idActionTip").css("top","37px");
	}
}
function successTip(msg){
	$("#idActionTip").attr("className","success_tip").html(msg);
	SYSTEM_TIP = setInterval(clearTip,SYSTEM_TIP_INTERVAL);
	adjustTipPosition();
}

function failureTip(msg){
	$("#idActionTip").attr("className","failure_tip").html(msg);
	SYSTEM_TIP = setInterval(clearTip,SYSTEM_ERROR_TIP_INTERVAL);
	adjustTipPosition();
}

function savingTip(msg){
	$("#idActionTip").attr("className","success_tip").html(msg);
}

function clearTip(msg){
	$("#idActionTip").attr("className","").html("");
	clearInterval(SYSTEM_TIP);
	adjustTipPosition();
}

function fetchOffset(obj) {
	var left_offset = obj.offsetLeft;
	var top_offset = obj.offsetTop;
	while((obj = obj.offsetParent) != null) {
		left_offset += obj.offsetLeft;
		top_offset += obj.offsetTop;
	}
	return { 'left' : left_offset, 'top' : top_offset };
}
/**
 * 功能: 日期检验
 * @param 字符串
 * @return true 合法;false 非法
 * @type Boolean
 */
function valiDate( strValue ){
    var objRegExp = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
      //check to see if in correct format
      if(strValue=="") return true;
      //else if(!objRegExp.executeSearch(strValue))
      else if(!objRegExp.test(strValue))
        return false; //doesn't match pattern, bad date
      else{
        var arrayDate = strValue.split(RegExp.$1); //split date into month, day, year
        var intDay = parseInt(arrayDate[2],10);
        var intYear = parseInt(arrayDate[0],10);
        var intMonth = parseInt(arrayDate[1],10);
        //window.alert(intYear+"?"+intMonth+"?"+intDay+"?");
        if(intYear<1900) {
            return false;
        }
        //check for valid month
        if(intMonth > 12 || intMonth < 1) {
            return false;
        }

        //create a lookup for months not equal to Feb.
        var arrayLookup = { '01' : 31,'03' : 31, '04' : 30,'05' : 31,'06' : 30,'07' : 31,'08' : 31,
             '09' : 30,'10' : 31,'11' : 30,'12' : 31,'1' : 31,'3' : 31, '4' : 30,'5' : 31,'6' : 30,
             '7' : 31,'8' : 31,'9' : 30}

        //check if month value and day value agree
        if(arrayLookup[arrayDate[1]] != null) {
            if(intDay <= arrayLookup[arrayDate[1]] && intDay != 0)
                return true; //found in lookup table, good date
        }

        //check for February
        var booLeapYear = (intYear % 4 == 0 && (intYear % 100 != 0 || intYear % 400 == 0));
        if( ((booLeapYear && intDay <= 29) || (!booLeapYear && intDay <=28)) && intDay !=0){
            return true; //Feb. had valid number of days
        }
      }
      return false; //any other values, bad date
}
/**表格排序部分*/
/**
 * 表格排序
 * tableId 表格ID
 * cellIndex 排序列索引
 * dataType 数据类型默认为text
 * desc 排列顺序 默认为升序
 */
function sortTable(tableId,cellIndex,dataType,desc){
	var $table = $("#"+tableId);
	var direction = desc || 1;
	dataType =  dataType || "text";
	var rows = $table.children('tbody').children('tr').get();
	$.each(rows, function(index, row) {
		var text = $(row).children('td').eq(cellIndex).text();
		switch(dataType.toUpperCase()){
			case "DATE":
				var temp = text.split("-");
				row.sortKey = new Date(temp[0],temp[1],temp[2]);
				break;
			case "NUMBER":
				row.sortKey = parseFloat(text);
				break;
			default :
				row.sortKey = text;
				break;
		}
	});
	rows.sort(
		function(a, b) {
			if (a.sortKey < b.sortKey) return -direction;
			if (a.sortKey > b.sortKey) return direction;
			return 0;
		}
	);
	$.each(rows,
		function(index, row) {
			$table.children('tbody').append(row);
			row.sortKey=null;
		}
	);
}
/**
 * 清除排序列标题图片
 * tableId 表格ID
 * columnIndex 排序列索引
 */
function clearSortImage(tableId,columnIndex){
	$("#"+tableId+" > thead th").eq(columnIndex).find("img").remove();
}
/**
 * 设置排序列标题图片
 * tableId 表格ID
 * columnIndex 排序列索引
 * direction 排序类型 1为升序 其他为降序
 */
function setSortImage(tableId,columnIndex,direction){	
	var img = (direction==1)?"tableUp.gif":"tableDown.gif";
	img = "<img src='/style/images/"+img+"'/>"
	$("#"+tableId+" > thead th").eq(columnIndex).append(img);
}

/*监听浏览器srcoll行为*/
if($.browser.msie){
	window.attachEvent('onscroll',adjustTipPosition);
}else if($.browser.mozilla){
	window.addEventListener('scroll',adjustTipPosition,false);
}

/*******以下为校验方法********/
function isNull( str ){
	if ( str == "" ) return true;
	var regu = "^[ ]+$";
	var re = new RegExp(regu);
	return re.test(str);
}

function isInteger( str ){

var regu = /^[-]{0,1}[0-9]{1,}$/;

return regu.test(str);

}



function isDecimal( str,precision ){
	if(isInteger(str)) return true;
	var pointIdx = str.indexOf(".");
	if(pointIdx==0 || pointIdx==str.length-1 || str.length-pointIdx-1 > precision){
		return false;
	}
	var re = /^\-?(\d+)[\.]+(\d{1,4})$/;
	if (re.test(str)) {
		if(RegExp.$1<0&&RegExp.$2==0){
			return false;
		}else{
			return true;
		}
	} else {
		return false;
	}
}


function formatNumber(str){
 	if(isNull(str)==true){
 		return "0";
 	}
 	if(str.indexOf(".")>1){
		str = str.substring(0,str.indexOf(".")+2);
 	}
 	re=/(\d{1,3})(?=(\d{3})+(?:$|\.))/g;
	alert(str.replace(re,"$1,"));
	return str;
 }

 function deFormatNumber(str){
	str = str.replace(",","");
	return str;
 }
function isEmail(str){
	var re = /^[\w-]+(\.[\w-]{1,})*@[\w-]+(\.[\w-]{2,6})+$/;
	return re.test(str);
}

 Date.prototype.toDateString = function(){
 	var month = this.getMonth()+1;
 	var day = this.getDate();
 	if(month < 10){
 		month = "0"+month;
 	}
 	if(day < 10){
 		day = "0"+day;
 	}
 	return this.getFullYear()+"-"+month+"-"+day;
 }

/**
 * 判断输入的信息是否超过合法的长度。传入参数中，nLen为允许输入的英文字符个数
 *
 * @param {String} str 待检测的字符串
 * @param {Number} maxLength 允许输入的英文字符个数
 * @return true if str's length<=maxLength, false otherwise.
 * @type Boolean
 */
function isLegal( str, maxLength ) {
    var realLength = getStringLength(str);
    return (realLength <= maxLength);
}


/**
 * Return the length of a string in ISO-8859 format. This is because the
 * disunity of different encodings under different platforms. Eg. getStringLength("ABC")
 * will get 3, getStringLength("中文") will get 4. Note you'd better add a line of meta
 * information to your html so as the browser can detect what encoding it should
 * employ. eg. <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
 *
 * @param {String} str 待检测的字符串
 * @return str的长度(英文字符个数)
 * @type Number
 */
function getStringLength(str) {
    if (str == null || str.length == 0) {
        return 0;
    }
    var strLong = 0;
    var browserLen  = str.length;
    var result      = 0;
    var charCode    = 0;
    for (i=0; i<browserLen; i++) {
        charCode = str.charCodeAt(i);
        if (charCode > 255) {
               strLong += 2;
        } else {
            strLong += 1;
        }
    }
    return strLong;
}

function isDigit(num) {
    var string="1234567890";
    if (string.indexOf(num) != -1) {
        return true;
    }
    return false;
}

//对时间进行格式化
function formatdate(strDate,strSep){
	var strRet="";

	var strYear=strDate.substr(0,4);
	var strMonth="";
	var strDay="";
	if(isDigit(strDate.substr(6,1))){
		strMonth=strDate.substr(5,2);
		strDay=strDate.substr(8,strDate.length);
	}else{
		strMonth="0"+strDate.substr(5,1);
		strDay=strDate.substr(7,strDate.length);
	}

	if(strDay.length<2)strDay="0"+strDay;

	strRet=strYear+strSep+strMonth+strSep+strDay;

	return strRet;
}

//比较时间的大小
function comparedate(strDate1,strDate2){
	if(formatdate(strDate1,"-") == formatdate(strDate2,"-")){
		return 0;
	}else{
		if(formatdate(strDate1,"-") > formatdate(strDate2,"-")){
			return -1;
		}else{
			return 1;
		}
	}
}
 
/*
===========================================
//对字符串进行Html编码
===========================================
*/
function toHtmlEncode(str){
    str=str.replace(/&/g,"&amp;");
    str=str.replace(/</g,"&lt;");
    str=str.replace(/>/g,"&gt;");
    str=str.replace(/\'/g,"&apos;");
    str=str.replace(/\"/g,"&quot;");
    str=str.replace(/\n/g,"<br>");
    str=str.replace(/\ /g,"&nbsp;");
    str=str.replace(/\t/g,"&nbsp;&nbsp;&nbsp;&nbsp;");
    return str;
}

/*
===========================================
//对字符串进行Html编码
===========================================
*/
function toUtf8Encode(str){
    str=str.replace(/&amp;/g,"&");
    str=str.replace(/&lt;/g,"<");
    str=str.replace(/&gt;/g,">");
    str=str.replace(/&apos;/g,"\'");
    str=str.replace(/&quot;/g,"\"");
    str=str.replace(/<br>/g,"\n");
    str=str.replace(/<BR>/g,"\n");
    str=str.replace(/&nbsp;/g,"\ ");
    str=str.replace(/&nbsp;&nbsp;&nbsp;&nbsp;/g,"\t");
    return str;
}

/**
 * 组装URL参数，用于排序分页等的传参
 * @param url 无参URL
 * @param parameters 上次使用的参数串
 * @param addParameters 需要调整的参数串（有可能在parameters串中不存在）
 */
function buildURLParam(url, parameters, addParameters){
	var newUrl = url;
	var removeParams = "";
	if(parameters != ""){
		var paramArry = parameters.split("&");
		for(i=0;i<paramArry.length; i++){
			var param = paramArry[i].split("=");
			if(addParameters[param[0]] != undefined){
				param[1] = addParameters[param[0]];
				removeParams+=param[0];
			}
			if(param[1] != "undefined"){
				if(i==0){
					newUrl+="?";
				}
				newUrl+=param[0]+"="+param[1]+"&";
			}
		}
	}
	for(var pro in addParameters){
		value = addParameters[pro];
		if(removeParams.indexOf(pro) == -1){
			newUrl += pro+"="+value+"&";
		}
	}
	if(newUrl.lastIndexOf("&") == newUrl.length-1){
		newUrl = newUrl.substr(0,newUrl.length-1);
	}
	return newUrl;
}

/**
 * 从带参URL中提取出参数串
 * @param url 带参URL
 */
function urlToParam(url){
	var param = "";
	var startIdx = url.indexOf("?")+"?".length;
	if(startIdx != 0){
		param = url.substr(startIdx);
	}
	return param;
}

/**
 * 初始化最大化和最小化按钮
 */
function initMinMaxIcon() {
	$('a.toggle').click(function(){
			var $content = $(this).parent('div').parent('div').next('div');
			if ($content.css('display') == 'none'){
				$content.css('display', '');
			} else {
				$content.css('display', 'none');
			}
			var str = $(this).children('img').attr('src')
			str = str.substring(str.lastIndexOf('/'));
			// 展开与收起操作
			if (str == '/max.gif'){
				$(this).children('img').attr('src', '/style/images/min.gif');
				removePortletCookie($(this).attr('id'));
			} else {
				$(this).children('img').attr('src', '/style/images/max.gif');
				addPortletCookie($(this).attr('id'));
			}
			return false;
		}
	);
	
	$(".title img").hover(function(){
	  $(this).addClass("mouseover");
	},function(){
	  $(this).removeClass("mouseover");
	}).css("cursor","pointer");
	
	// 将cookie中已隐藏的portal执行隐藏操作
	var strPortlet = $.cookie(PORTLET_COOKIE);
	if (strPortlet != null && strPortlet != '' && strPortlet != undefined) {
		var portletArray = strPortlet.split(',');
		for (var i = 0; i < portletArray.length; i++) {
			if (portletArray[i] != "" && document.getElementById(portletArray[i]) != null) {
				// 自动展开与隐藏操作
				$('#' + portletArray[i]).parent('div').parent('div').next('div').toggle();
				var str = $('#' + portletArray[i]).children('img').attr('src')
				str = str.substring(str.lastIndexOf('/'));
				// 展开与收起操作
				if (str == '/max.gif'){
					$('#' + portletArray[i]).children('img').attr('src', '/style/images/min.gif');
				} else {
					$('#' + portletArray[i]).children('img').attr('src', '/style/images/max.gif');
				}
			}
		}
	}
}

/**
 * 添加cookie到portlet里
 * @param cookieName 保存到cookie的名称
 */
function addPortletCookie(cookieValue){
	var strPortlet = $.cookie(PORTLET_COOKIE);
	if (strPortlet == null || strPortlet == undefined) {
		strPortlet = '';
	}
	strPortlet = strPortlet  + cookieValue + ',';
	$.cookie(PORTLET_COOKIE, strPortlet);
}

/**
 * 移除cookie
 * @param cookieName 保存到cookie的名称
 */
function removePortletCookie(cookieValue){
	var strPortlet = $.cookie(PORTLET_COOKIE);
	$.cookie(PORTLET_COOKIE, strPortlet.replace(cookieValue + ',', ''));
}

/**
*工具条调整事件
*/
function adjustToolbar(){
	var random = Math.ceil(Math.random()*100);
	var toolbar = document.getElementById("ToolBar");
	var scrollWith = 16;
	if($.browser.msie){
		scrollWith = 20;
	}
	toolbar.style.width = document.body.offsetWidth-scrollWith;	
	initToolbar();		
}
/**
*初始化工具条
*/
function initToolbar(){
	$.get('/about/loadToolbarBulletin.do',{},
			function(json){	
				if(json.count>0){
					bltTitleArray = json.title.split(",");
					bltIdArray = json.id.split(",");
					showBulletin();
//					window.setInterval(showBulletin, 10000);
				}
			},"json"
		);
	getReceiveMessageCount();
}

var bltTitleArray = null;
var bltIdArray = null;
var firstShow = false;
function showBulletin(){	
	var radom = Math.ceil(Math.random()*100)%bltIdArray.length;	
	var title = bltTitleArray[radom];
	var id = bltIdArray[radom];
	//第一次显示第一条记录
	if(firstShow==false){
		title = bltTitleArray[0];
		id = bltIdArray[0];
		firstShow=true;
	}
	var ahref="http://bbs.zonezu.com/topic-16-thread-"+id+"-1.html";
	var ahtml = "<a href=\""+ahref+"\" target=\"_blank\">"+title+"</a>";
	$("#bulletinDiv").html(ahtml);
}

function getReceiveMessageCount(){
	$.getJSON("/user/getReceiveMessageCount.do",{callId:callId()},
		function(json){
			if(json.unreadMessage>0){				
				$("#ToolBar .message").html("<a href='/user/userMessage.do' style='color:red'>您有"+json.unreadMessage+"条新消息</a>");
				$("#ToolBar .message").show();
				playSound("/style/newmessage.wav");
			}else{
				$("#ToolBar .message").hide();
			}
		}
	);	
}

function refreshMessage(){
	$.getJSON("/user/getReceiveMessageCount.do",{callId:callId()},
		function(json){
			if(json.unreadMessage>0){				
				$("#ToolBar .message").html("<a href='/user/userMessage.do' style='color:red'>您有"+json.unreadMessage+"条新消息</a>");
				$("#ToolBar .message").show();				
			}else{
				$("#ToolBar .message").hide();
			}
		}
	);	
}

function playSound(src){ 
	var _s = document.getElementById('snd'); 	
	if(src!='' && typeof src!=undefined){ 
		_s.src = src; 
	} 
}

/*监听浏览器srcoll行为*/
if(document.getElementById("ToolBar")){
	if($.browser.msie){
		window.attachEvent('onresize',adjustToolbar);
	}else if($.browser.mozilla){		
		window.addEventListener('resize',adjustToolbar,false);
	}
}

function loadUserMessage(){
	$.getJSON("/user/getReceiveMessageCount.do",{callId:callId()},
		function(json){
			if(json.unreadMessage>0){				
				$("#messageHref").html("收件夹(<font color=red>"+json.unreadMessage+"</font>/"+json.messageCount+")");
			}else{
				$("messageHref").html("收件夹("+json.messageCount+")");
			}
		}
	);	
}