﻿var FL_DEBUG = true;
var FL_WIN_BORDER_HEIGHT = 28;

/**
 * 生成JS日历控件.
 * 仅仅选择日期，没有其它特殊功能。
 *
 * @param inputId 显示日期的元素id，一般是文本输入框
 * @param btnId 触发显示日历控件的元素id，一般是按钮或图片
 * @return 返回生成的日历对象
 */
function setupCalendar(inputId, btnId) {
	return new Zapatec.Calendar.setup({
				inputField     :    inputId,   // id of the input field
				button         :    btnId,  // What will trigger the popup of the calendar
				ifFormat       :    "%Y-%m-%d",       //  of the input field
				timeFormat     :    "24",
				showsTime      :     false,          //no time
				electric       :     false
			});
}

/**
 * 生成带时间的JS日历控件.
 * 用户需要在同一日期上点击2次才能自动关闭窗口，以允许用户选择时间。
 *
 * @param inputId 显示日期的元素id，一般是文本输入框
 * @param btnId 触发显示日历控件的元素id，一般是按钮或图片
 * @return 返回生成的日历对象
 */
function setupCalendarWT(inputId, btnId, fmt) {
	if(isNull(fmt)) fmt = "%Y-%m-%d %H:%M:%S";
	return new Zapatec.Calendar.setup({
				inputField     :    inputId,   // id of the input field
				button         :    btnId,  // What will trigger the popup of the calendar
				singleClick	   :    false,
				ifFormat       :    fmt,       //  of the input field
				timeFormat     :    "24",
				showsTime      :     true,          //no time
				electric       :     false
			});
}

/**
 * 清除select元素中指定的选项.
 * 
 * @param  oSelect 指定的select元素对象
 * @param startIndex 起始选项，为空或<0，则从第一个选项开始
 * @param endIndex 结束选项，为空或大于select的选项数，则表示到最后一个选项
 */
function clearOptions(oSelect, startIndex, endIndex) {
	if(endIndex == null || endIndex >= oSelect.options.length) {
		endIndex = oSelect.options.length - 1;
	}
	if(startIndex == null || startIndex < 0) {
		startIndex = 0;
	}
	
	for(i=endIndex; i>=startIndex; i--){
		oSelect.remove(i);
	}
}

/**
 * 添加选项到指定select元素的最后
 * 
 * @param oSelect 指定的select元素
 * @param optionValue option值
 * @param optionText option显示的内容
 * @return 返回刚生成的option
 */
function addOption(oSelect, optionValue, optionText) {
	var oOption = document.createElement("OPTION");
	oOption.text = optionText;
	oOption.value = optionValue;
	oSelect.options.add(oOption);

	return oOption;
}

/**
* 将下拉框的选项移出到另一个中去
* @param oSrc    源下拉框
* @param oTarget 目标下拉框
*/
function moveOption(oSrc, oTarget){
	for(i=0;i<oSrc.length;i++)
		if(oSrc[i].selected){
			oTarget.add(new Option(oSrc[i].text,oSrc[i].value));
		}
	for(i=oSrc.length-1;i>=0;i--)
		if(oSrc[i].selected)
			oSrc.remove(i);
}

/**
* 将下拉框的选项全部移出到另一个中去
* @param oSrc    源下拉框
* @param oTarget 目标下拉框
*/
function moveAllOption(oSrc, oTarget){
	for(i=0;i<oSrc.length;i++)
		oTarget.add(new Option(oSrc[i].text,oSrc[i].value));
	for(i=oSrc.length-1;i>=0;i--)
			oSrc.remove(i);
}

/*传入多选框name，返回已选框的值*/
function cboxSelect(name){
   var coll = document.getElementsByName(name);
   var returnString = '';
   for(var i = 0; i<coll.length; i++){
       if(coll[i].checked == true){
	       returnString += coll[i].value + ",";
	   }
   }
   returnString = returnString.substring(0,returnString.length-1);
   return returnString;
}

/*checkbox是否有选中的项*/
function hasChecked(cbName){
   if(cbName == undefined){
		return false;
	}
	if(cbName.length == undefined){
		if(cbName.checked){
			return true;
		}
	}
	for(var i=0; i<cbName.length; i++){
		if(cbName[i].checked){
			return true;
		}
	}
	return false;
}

/*x小时+y分钟 = z分钟*/
function getMinuteValue(hourValue,minuteValue){
	if(!isNumber(hourValue))
		hourValue =0;
	if(!isNumber(minuteValue))
		minuteValue = 0;
    return parseInt(hourValue)*60+parseInt(minuteValue)
}

/**
 * 通过value选择指定select元素
 * 
 * @param oSelect 指定的select元素或id
 * @param optionValue 需要选中的值或数组
 * @param optionText option显示的内容，如果指定optionText，则当指定列表
 * 中没有相应值时，在列表最后添加一个option
 */
function selectOption(oSelect, optionValue, optionText) {
	var o = $(oSelect);
	if(o == null || typeof o.options == "undefined") return;
	var selected = 0;

	for (var j = 0; j < o.options.length; j++) {
		var option = o.options[j];
		if (optionValue instanceof Array) {
			option.selected = (optionValue.indexOf(option.value) > -1);
		} else {
			option.selected = (option.value == optionValue);
			if(option.value == optionValue) selected++;
		}
	}

	if(selected == 0 && typeof optionText != "undefined") {
		var opt = addOption(o, optionValue, optionText);
		opt.selected = true;
	}
}

/**
 * 根据val选择对应的radio box
 *
 * @param rdName radio box名
 * @param val 指定的值
 */
function selectRadioBox(rdName, val) {
	$$("input[type=radio][name="+rdName+"]").each(function(o){if(o.value==val) o.checked=true;})
}

/**
 * 根据val选中对应的checkbox
 *
 * @param cbName checkbox的name
 * @param val 指定的值或数组
 * @param bNotChecked 是否需要返回没有对应checkbox的值，缺省为false
 * @return 如果bNotChecked=true，则返回没有找到对应checkbox的值数组，
 * 如果所有指定的值都有对应的checkbox，则返回长度为0的数组；否则返回null
 */
function selectCheckBox(cbName, val, bNotChecked) {
	bNotChecked = checkTrue(bNotChecked);
	var notChecked = null;
	if(bNotChecked) {
		if(val instanceof Array) notChecked = val.clone();
		else notChecked = [val];
	}
	
	$$("input[type=checkbox][name="+cbName+"]").each(function(o){
		if (val instanceof Array) {
			o.checked = (val.indexOf(o.value) > -1);
		} else o.checked = (o.value ==val);
		if(o.checked && bNotChecked) notChecked = notChecked.without(o.value);
	})
	
	return notChecked;
}

/**
 * 全选或去选指定name的一组checkbox.
 * 需要包含prototype.js
 *
 * @param cbName 一组checkbox名字
 * @param bCheck =true: 全选；=false: 去选
 */
function checkAll(cbName, bCheck) {
	//var coll = $$('input[type=checkbox][name='+cbName+']').each(function(o){o.checked=bCheck;});
	if(cbName == undefined){
		return;
	}
	if(cbName.length == undefined){
		if(!cbName.disabled){
			cbName.checked = bCheck;
		}
	}
	for(var i=0; i<cbName.length; i++){
		if( !cbName[i].disabled ){
			cbName[i].checked = bCheck;
		}
	}
}

/**
 * 获取指定名字的一组CheckBox对象数组。
 *
 * @param cbName 指定的名字
 * @return 返回具有相同名字的CheckBox对象数组
 */
function getCBs(cbName) {
	return $$('input[type=checkbox][name='+cbName+']');
}

/**
 * 获取指定名字的一组CheckBox的值(Value)数组。
 * 可以指定返回一组CheckBox所有值，或者仅返回选中的CheckBox的值。
 * 缺省返回选中的CheckBox的值。
 *
 * @param cbName 指定CheckBox的Name属性
 * @param bAll =true, 返回所有的值；=false，仅返回选中的值，缺省值。
 */
function getCBValues(cbName, bAll) {
	if(bAll == null) bAll = false;

	if(bAll) return getCBs(cbName).pluck("value");
	
	return getCBs(cbName).findAll(function(o){return o.checked;}).pluck("value");
}

/**
 * 获取指定一组RadioBox中选中的值。
 *
 * @param rdName 指定的RadioBox名字
 * @return 返回选中的RadioBox的值。
 */
function getRadioValue(rdName) {
	var arr = $$("input[type=radio][name="+rdName+"]").findAll(function(o){return o.checked;}).pluck("value");
	if(arr.length == 0) return null;
	
	return arr[0];
}

/**
 * 用指定的值替代占位符.
 * 占位符以{0}, {1}...的形式表示。如果bRestore=true，且在源字符串中必须使用
 * 类似{n}的字符串(n为数字)，则需要使用{{n}来表示，本方法返回时将把{{n}还原
 * 成{n}的形式。
 *
 * @param str 需要替换的字符串
 * @param val 用来替换的值，可以是一个值或者数组。如果指定的值是数组，
 * 则按照数组下标逐一替换；否则仅替换第一个占位符。
 * @param bRestore 是否还原{{n}形式的字符，=true，还原；否则{{n}将被替换成
 * {val的形式，缺省bRestore=true。
 * @return 返回替换好的字符串。
 * @author whj
 */
function updateParameters(str, val, bRestore) {
	if(isNull(str)) return;
	var ret = str;

	if(typeof(bRestore) != "boolean" || bRestore) bRestore = true;
	else bRestore = false;

	if(!isNull(val)) {
		var a = val;

		if(!(val instanceof Array)) {
			a = new Array();
			a[0] = val;
		}

		if(bRestore) {
			a.each(function(v, index){
					var r = new RegExp("([^{])\\{"+index+"}","g");
					ret = ret.replace(r, "$1"+v);
					r = new RegExp("^\\{"+index+"}","gm");
					ret = ret.replace(r, v);
			});
		} else {
			a.each(function(v, index){
					var r = new RegExp("\\{"+index+"}","g");
					ret = ret.replace(r, v);
			});
		}
	}

	if(bRestore){
		ret = ret.replace(/\{\{(\d+})/g, "{$1");
	} 

	return ret;
}

/**
 * 检测参数是否为null或者undefined.
 *
 * @param o 待检测的参数
 * @return 如果为null或者undefined，返回true；否则返回false。
 */
function isNull(o) {
	return typeof o == "undefined" || o == null;
}

/**
 * 检测元素是否指定的类型
 *
 * @param o 待检测的参数，如果为空，则返回false
 * @param tagName 指定的类型，如果为空或不是string，则返回false
 * @return 如果是指定的类型，返回true；否则返回false。
 */
function isElement(o, tagName) {
	if(isNull(o) || typeof(o) != "object" 
	|| isNull(o.tagName) || typeof(o.tagName) != "string"
	|| isNull(tagName) || typeof(tagName) != "string") return false;

	return o.tagName.toUpperCase() == tagName.toUpperCase();
}

/**
 * 打开窗口。
 * 并将其居中。注意：如果跨站点调用则会出错。
 */
function openWindow(url,wName,w,h,scrollbars,bResizable){
	var newwindow = openWindowEx(url,wName,w,h,scrollbars,bResizable);

	if(newwindow != null) {
		newwindow.moveTo(getWinCenterX(w),getWinCenterY(h)/2);
		newwindow.focus();
	}

	return newwindow;
}

function openWindow2(url,wName,w,h,scrollbars,bResizable,floatX,floatY){   //与父窗口错开
	var newwindow = openWindowEx(url,wName,w,h,scrollbars,bResizable);

	if(newwindow != null) {
		newwindow.moveTo(getWinCenterX(w)+floatX,getWinCenterY(h)/2+floatY);
		newwindow.focus();
	}

	return newwindow;
}


/**
 * 打开一个窗口。
 * 但不改变窗口位置和大小。从而允许跨站点调用。
 */
function openWindowEx(url,wName,w,h,scrollbars,bResizable){
	var newwindow;
	if(w==null || w==0){w=400}
	if(h==null || h==0){h=370}
	var feature="width="+w+",height="+h;
	if(scrollbars!=null && scrollbars){feature+=",scrollbars=yes"}
	if(bResizable!=null && bResizable)
	{
		feature+=",resizable=yes"
	}
	else
	{
		feature+=",resizable=no"
	}

	return window.open(url,wName,feature);
}

function maximizeIt() {
	window.resizeTo(window.screen.width,window.screen.height-FL_WIN_BORDER_HEIGHT);
	window.moveTo(0,0);
	window.focus();
}

function centerIt() {
	window.moveTo(getWinCenterX(w),getWinCenterY(h)/2);
	window.focus();
}

function getSize() {
	if(!FL_DEBUG) return;
	
	alert("sw:"+document.body.scrollWidth+";sh:"+document.body.scrollHeight+"\r\n"+
		"top:"+document.body.clientTop+";left:"+document.body.clientLeft);
}

function getWinCenterX(w) {
	return (window.screen.width - w) / 2;
}

function getWinCenterY(h) {
	return (window.screen.height - h - FL_WIN_BORDER_HEIGHT) / 2;
}


/*---------------------------zhaotiejun-----------------------*/
/*---------------------------2007-04-19-----------------------*/
/* ignore whitespace */
function isEmpty(s) {
    return !Boolean(s.replace(/^\s*|\s*$/g, "").length);
}
/* ignore whitespace */
function isNonEmpty(s) {
    return Boolean(s.replace(/^\s*|\s*$/g, "").length);
}
/* -0.01, 10, 10.45 - ok
   01, 00.1, .1, 0.0.0 - bad */
function isNumber(s) {
    if (s.length && s.charAt(0) == "-") { return isNumber(s.substr(1)); }
    if (!(/^[\d.]+$/.test(s))) { return false; }
    if (s.indexOf(".") != -1 && (s.indexOf(".") != s.lastIndexOf("."))) { return false; }
    if (s.charAt(0) == ".") { return false; }
    if (s.length >= 2 && s.charAt(0) == "0" && s.charAt(1) != ".") { return false; }
    return !isNaN(s);
}
function isEmail(s) {
    return (/^\w+@\w+\.[\w.]+$/.test(s) && s.charAt(s.length-1) != ".");
}

/**
 * 判断是否是4位的时间 HHMM
 * 2007-4-19 by zhaotiejun
 */
function isNumber4(s) {
  return new RegExp("^([0-1]\\d|2[0-3])[0-5]\\d$").test(s);
}
/**
 * 字符串替换函数
 * 2007-4-19 by zhaotiejun
 */
function replaceStr(str,oldStr,newStr){
	var tmpStr="";
	var pos1,pos1;
	pos1=str.indexOf(oldStr);
	pos2=pos1+oldStr.length;
	if(pos1<0){
	tmpStr=str;
	return tmpStr;
	}
	while(pos1>=0){
	tmpStr += str.substring(0,pos1);
	tmpStr += newStr;
	str = str.substring(pos2);

	pos1=str.indexOf( oldStr );
	pos2=pos1+oldStr.length;
	}

	tmpStr += str;
	//alert(tmpStr)
	return tmpStr;
}

/**
 * 字符串转整数
 * 如果字符串为空，或者非法的字符串，则返回缺省值
 *
 * @param str 待装换的字符串
 * @param def 缺省值，不指定，则为0
 * @rteurn 返回装换后的整数或缺省值
 * @author whj
 */
function toInt(str, def) {
	def = parseInt(def);
	if(isNaN(def)) def = 0;

	var i = parseInt(str);
	if(isNaN(i)) i = def;

	return i;
}

/**
 * 字符串转浮点数
 * 如果字符串为空，或者非法的字符串，则返回缺省值
 *
 * @param str 待装换的字符串
 * @param def 缺省值，不指定，则为0
 * @rteurn 返回装换后的数值或缺省值
 * @author whj
 */
function toFloat(str, def) {
	def = parseFloat(def);
	if(isNaN(def)) def = 0;

	var f = parseFloat(str);
	if(isNaN(f)) f = def;

	return f;
}

/**
 * 去掉头部的0
 */
function stripHeadingZero(str) {
	if(str == null) return null;
	return str.strip().replace(/^0+/, "");
}

/**
 * 检查一个值是否为true.
 * 该值可以是boolean, string或整数。如果是string，且未指定vTrue, 则1, true, 
 * yes表示true，其它均为false，否则只有等于vTrue的值表示true，其它为false；
 * 如果是整数，且未指定vTrue，则1表示true，其它均为false，否则只有等于vTrue的
 * 值才表示true，其它为false。
 *
 * @param v 待检测的值
 * @param bDefault 如果v不是boolean, string或整数时的缺省值，缺省为false。
 * @param vTrue 表示代表true的值
 * @return 返回待检测的值是否为true。
 * @author whj
 */
function checkTrue(v, bDefault, vTrue) {
	var ret = false;
	if(typeof(bDefault) == 'boolean') ret = bDefault;

	switch (typeof(v)) {
		case 'boolean': ret = v; break;
		case 'string': 
			if(typeof(vTrue) == "string") ret = (v == vTrue);
			else ret = (v == true || v == "1" || v == "true" || v == "yes"); 
			break;
		case 'number': 
			if(typeof(vTrue) == "number") ret = (parseInt(v) == vTrue);
			else ret = (parseInt(v) == 1); 
			break;
	}

	return ret;
}

/**
 * 将焦点放到指定表单元素上
 * 并将该元素移动到窗口中。如果该元素为text或password，还将高亮显示原来的输入值
 *
 * @param o 指定的元素id或对象
 */
function focusIt(o) {
	var obj = $(o);
	if(obj == null) return;
	obj.focus();
	//obj.scrollTo(); // 由于有些页面超宽，滚动后会导致页面显示不正常(如飞行日志)，暂时注释，2007-6-26 by whj
	if(isElement(obj, "input") 
	&& (obj.type.toLowerCase() == "text" || obj.type.toLowerCase() == "password")) {
		obj.select();
	}
}

	//数字判断函数
function isInteger(str) 
{
	var digits = "0123456789";
	var i = 0;
	if(str==null) return false;
	var sLength = str.length;
    if(sLength==0)  return false;
	while ((i < sLength))
	{
	var c = str.charAt(i);
	if (digits.indexOf(c) == -1) return false;
	i++;
	}
	
	return true;
}

function formatText(textfield){
	alert(textfield.value);
	var cc = textfield.value;
	cc = "    " + cc;
	cc = cc.replace(/\s*/, "    ");
	cc = cc.replace(/\n\s*/g, "\n    ");
	textfield.value = cc;
}
