/**
 * ---------------------------------------------------------------------------
 * Public Utils
 * ---------------------------------------------------------------------------
 */

/**
 * Trim String
 * 
 * @param str
 *            String
 * @return String
 */
function trimString(str) {
	if (str != null && str.length > 0) {
		str = str.replace(/(^\s*)|(\s*$)/g, "");
	}
	return str;
}

/**
 * Escape HTML
 * 
 * @param str
 *            String
 * @return String
 */
function escapeHTML(str) {
	if (str != null && str.length > 0) {
		str = str.replace(/&/g, "&amp;");
		str = str.replace(/</g, "&lt;");
		str = str.replace(/>/g, "&gt;");
		str = str.replace(/\"/g, "&quot;");
		str = str.replace(/\'/g, "&#39;");
	}
	return str;
}

/**
 * replace \n To br
 * 
 * @param str
 *            String
 * @return String
 */
function formatHtmlReLineTag(str) {
	if (str != null && str.length > 0) {
		str = str.replace(/\n/g, "<br/>");
	}
	return str;
}

/**
 * Index of Array
 * 
 * @param array
 *            Array
 * @param obj
 *            Object
 * @return int
 */
function indexOfArray(array, obj) {
	if (array != null) {
		for ( var i = 0; i < array.length; i++) {
			if (obj != array[i]) {
				continue;
			}
			return i;
		}
	}
	return -1;
}

/**
 * Extend Obj
 * 
 * @param obj0
 *            Object
 * @param obj1
 *            Object
 */
function extendObj(obj0, obj1) {
	if (obj0 == null && obj1 == null) {
		return {};
	} else if (obj0 == null) {
		return obj1;
	} else if (obj1 == null) {
		return obj0;
	}
	for ( var key in obj1) {
		obj0[key] = obj1[key];
	}
	return obj0;
}

/**
 * Call Each Element
 * 
 * @param eleList
 *            Object or Array
 * @param callback
 *            function
 */
function eachElement(eleList, callback) {
	if (eleList == null) {
		return 0;
	}
	var listSize = eleList.length;
	if (typeof (listSize) == "undefined") {
		listSize = 1;
		if (callback != null) {
			callback(eleList);
		}
	} else {
		if (callback != null) {
			for ( var i = 0; i < listSize; i++) {
				callback(eleList[i]);
			}
		}
	}
	return listSize;
}

function createNewWin(name, url, isIgnoreScrollBar) {
	var scrollBarAttr = "scrollbars=yes";
	if (isIgnoreScrollBar) {
		scrollBarAttr = "scrollbars=no";
	}
	var screenWidth = screen.width * 0.8;
	var screenHeight = screen.height * 0.8;
	return window.open(url, name, "width=" + Math.round(screenWidth)
			+ ",height=" + Math.round(screenHeight) + "," + scrollBarAttr
			+ ",resizable=yes");
}

function gotoUrl(url) {
	window.location.href = url;
}

function gotoUrlByPost(url, data, target) {
	var formObj = document.createElement("form");
	formObj.method = "POST";
	formObj.action = url;
	formObj.style.display = "none";
	if (target != null) {
		formObj.target = target;
	}
	document.body.appendChild(formObj);
	if (data != null) {
		for ( var name in data) {
			var hiddenObj = document.createElement("input");
			hiddenObj.type = "hidden";
			hiddenObj.name = name;
			hiddenObj.value = data[name];
			formObj.appendChild(hiddenObj);
		}
	}
	formObj.submit();
}

function submitToNewWin(myform, action) {
	mf = eval("document." + myform);
	mf.action = action;
	mf.target = "newWin";
	createNewWin("newWin", "");
	mf.submit();
}

function submitToSameWin(myform, action) {
	mf = eval("document." + myform);
	mf.action = action;
	mf.target = "";
	mf.submit();
}

function allSelectX(formName, clickOn, checkboxColumnName, callback) {
	var allCmd = eval("document." + formName + "." + clickOn);
	var arrayCmd = eval("document." + formName + "." + checkboxColumnName);
	if (allCmd == null || arrayCmd == null) {
		return;
	}
	var allCmdChecked = allCmd.checked;
	eachElement(arrayCmd, function(obj) {
		obj.checked = allCmdChecked;
		if (callback != null) {
			callback(obj);
		}
	});
}

function cancelAllSelectX(formName, clickOn, checkboxColumnName) {
	var allCmd = eval("document." + formName + "." + clickOn);
	var arrayCmd = eval("document." + formName + "." + checkboxColumnName);
	if (allCmd == null || arrayCmd == null) {
		return;
	}
	eachElement(arrayCmd, function(obj) {
		if (!obj.checked) {
			allCmd.checked = false;
		}
	});
}

function clearAllOption(formName, checkboxColumnName) {
	var arrayCmd = eval("document." + formName + "." + checkboxColumnName);
	if (arrayCmd == null) {
		return;
	}
	eachElement(arrayCmd, function(obj) {
		obj.checked = false;
	});
}

function toggleDiv(container, imgObj, plusImg, minusImg) {
	if (container.style.display == "none") {
		container.style.display = "";
		imgObj.src = minusImg;
	} else {
		container.style.display = "none";
		imgObj.src = plusImg;
	}
}

/**
 * Get Select Options Value
 * 
 * @param selectObj
 *            Object or elementId
 * @param defaultValue
 *            String
 */
function getSelectOptionsValue(selectObj, defaultValue) {
	if (typeof (selectObj) == "string") {
		selectObj = document.getElementById(selectObj);
	}
	if (!defaultValue) {
		defaultValue = "";
	}
	return (selectObj != null && selectObj.options != null
			&& selectObj.options.length > 0 ? selectObj.options[selectObj.selectedIndex].value
			: defaultValue);
}

function stopBubble(_event) {
	_event = (_event ? _event : window.event);
	if (_event) {
		if (_event.stopPropagation) {
			_event.stopPropagation();
		} else {
			_event.cancelBubble = true;
		}
	}
}

/**
 * ---------------------------------------------------------------------------
 * jQuery Utils
 * ---------------------------------------------------------------------------
 */

/**
 * Make JQuery Slice Selector
 * 
 * @param startIndex
 *            int
 * @param endIndex
 *            int
 */
function makeJQuerySliceSelector(startIndex, endIndex) {
	return (endIndex >= 0 ? (":lt(" + (endIndex + 1) + ")") : "")
			+ (startIndex > 0 ? (":gt(" + (startIndex - 1) + ")") : "");
}

/**
 * ---------------------------------------------------------------------------
 * Private Utils
 * ---------------------------------------------------------------------------
 */

/* submit the form using tagName */
function submitTag(myform, tagName) {

	mf=eval("document." + myform);

	mf.tag.value=tagName;

	mf.submit();
}

function submitSearchBy(myform, searchByValue) {

	mf=eval("document." + myform);

	mf.search_by.value=searchByValue;

	mf.submit();
}

/* submit the form using tagName with an attachment key*/
function submitAttachmentKeyTag(myform, aKey, tagName) {

	mf=eval("document." + myform);

	mf.attachment_key.value=aKey;

	mf.tag.value=tagName;

	mf.submit();
}

/* submit the form using tagName with an item_index */
function submitItemIndexTag(myform, itemIndex, tagName) {

	mf=eval("document." + myform);

	mf.item_index.value=itemIndex;

	mf.tag.value=tagName;

	mf.submit();
}

/* submit the form using tagName with a product_key */
function submitProductKeyTag(myform, productKey, tagName) {

	mf=eval("document." + myform);

	mf.product_key.value=productKey;

	mf.tag.value=tagName;

	mf.submit();
}

/* Prompt the user to confirm before submitting the form */
function confirmSubmitTag(msg, myform, tagName) {

	returnValue = confirm(msg);

	if (returnValue == true) {

		submitTag(myform, tagName);

	}
}

/* check if an item is selected in a list before submitting a form */
function checkListSubmitTag(myform, tagName, list, msg) {

	i = list.selectedIndex;

	if (i != -1 && list.options[i].value > "") {

		submitTag(myform, tagName);

	} else {

		alert(msg);	

	}
}

function submitTagWithBuf(myform, col, buf, tagName){

	sourceList = document.forms[myform].elements[col];

	val = "";

	for (i=0;i<sourceList.length;i++) {

		if (i!=0) { val += ","; }

		val += sourceList[i].value;

	} 



	mf=eval("document." + myform);

	buffer = document.forms[myform].elements[buf];

	buffer.value = val;

	mf.tag.value=tagName;

	mf.submit();
}

function moveUp(col) {

	sl = col.selectedIndex;

	if (sl != -1 && col.options[sl].value > "") {

    	oText = col.options[sl].text;

    	oValue = col.options[sl].value;

    	if (col.options[sl].value > "" && sl > 0) {

      		col.options[sl].text = col.options[sl-1].text;

      		col.options[sl].value = col.options[sl-1].value;

      		col.options[sl-1].text = oText;

      		col.options[sl-1].value = oValue;

      		col.selectedIndex--;

    	} 

	} else {

    	alert("Please select an item first");

	}
}

function moveDown(col) {

	sl = col.selectedIndex;

	if (sl != -1 && col.options[sl].value > "") {

		oText = col.options[sl].text;

		oValue = col.options[sl].value;

		if (sl < col.length-1 && col.options[sl+1].value > "") {

			col.options[sl].text = col.options[sl+1].text;

			col.options[sl].value = col.options[sl+1].value;

			col.options[sl+1].text = oText;

			col.options[sl+1].value = oValue;

			col.selectedIndex++;

		}

	} else {

		alert("Please select an item first");

	}
}

function viewNote(url) {

	/*

    attr="scrollbars=yes, resizable=yes, height=150, width=600"

    win = window.open(url, "_blank", attr);

	*/

	openWindow(url, 150, 600);
}

function openWindow(url, ht, wh) {

    attr="scrollbars=yes, resizable=yes";

	attr += " height=" + ht + ",";

	attr += " width=" + wh;

    win = window.open(url, "_blank", attr);
}

/* Determine image size and show it in proper size */
/* 12/02/02 hctu: this function is retired and is replaced

   by server size through com.ctu.crm.servlet.ImageUtil.

*/
function imageSize(path, srcFile, alt, minSize) {

    img = new Image();

    img.src = path+'/'+srcFile;



    var ht = img.height;

    var wh = img.width;

    if (ht>wh) base="w";

    else base="h";



    tmp="<img src=\"" + path + "/" + srcFile + "\"";

    if (base == "w" && wh > minSize) {

        newWidth=minSize;

        newHeight=ht*(newWidth/wh);

    } else if (base == "h" && ht > minSize) {

        newHeight = minSize;

        newWidth = wh * (newHeight/ht);

    } else {

        newWidth = wh;

        newHeight = ht;

    }

    /* The following is used when the image has not been

       fully loaded and the dimension is not available. */

    if (newWidth < 1 || newHeight < 1) {

        newWidth = minSize;

        newHeight = minSize;

        /* alert ("newWidth = minSize and newHeight = minSize"); */

    }



    tmp += " width=\"" + newWidth+ "\" height=\"" + newHeight + "\"";

    tmp += " border=0 alt=\"" + alt+"\">";

    /* alert ("ht="+ht+"   wh=" + wh + "  link=" + tmp); */

    document.write(tmp);
}

/*
// PickList II script (aka Menu Swapper)- By Phil Webb (http://www.philwebb.com)
// Visit JavaScript Kit (http://www.javascriptkit.com) for this JavaScript and 100s more
// Please keep this notice intact
*/
function move(fbox, tbox) {

     var arrFbox = new Array();

     var arrTbox = new Array();

     var arrLookup = new Array();

     var i;

     for(i=0; i<tbox.options.length; i++) {

          arrLookup[tbox.options[i].text] = tbox.options[i].value;

          arrTbox[i] = tbox.options[i].text;

     }

     var fLength = 0;

     var tLength = arrTbox.length

     for(i=0; i<fbox.options.length; i++) {

          arrLookup[fbox.options[i].text] = fbox.options[i].value;

          if(fbox.options[i].selected && fbox.options[i].value != "") {

               arrTbox[tLength] = fbox.options[i].text;

               tLength++;

          } else {

               arrFbox[fLength] = fbox.options[i].text;

               fLength++;

          }

     }

     arrFbox.sort();

     arrTbox.sort();

     fbox.length = 0;

     tbox.length = 0;

     var c;

     for(c=0; c<arrFbox.length; c++) {

          var no = new Option();

          no.value = arrLookup[arrFbox[c]];

          no.text = arrFbox[c];

          fbox[c] = no;

     }

     for(c=0; c<arrTbox.length; c++) {

     	var no = new Option();

     	no.value = arrLookup[arrTbox[c]];

     	no.text = arrTbox[c];

     	tbox[c] = no;

     }
}

function moveSortedByOptValue(fbox, tbox) {
	for(i=0; i<fbox.options.length; i++) {
		if(fbox.options[i].selected && fbox.options[i].value != "") {
			var opt = new Option();
			opt.value = fbox.options[i].value;
			opt.text = fbox.options[i].text;
			tbox.options[tbox.options.length] = opt;
			fbox.remove(i--);
		}
	}
	sortSelectOptByValue(fbox);
	sortSelectOptByValue(tbox);
}

function sortSelectOptByValue(selectObj) {
	var valueM2Text = new Array();
	var valueList = new Array();
	for(var i=0; i < selectObj.options.length; i++) {
		valueM2Text[selectObj.options[i].value] = selectObj.options[i].text;
		valueList[i] = selectObj.options[i].value;
	}
	valueList.sort();
	selectObj.length = 0;
	for(var i = 0; i < valueList.length; i++) {
		var opt = new Option();
		opt.value = valueList[i];
		opt.text = valueM2Text[opt.value];
		selectObj[i] = opt;
	}
}

function selectAll(box1, box2, box3) {

     for(var i=0; i<box1.length; i++) {

     	box1[i].selected = true;

     }
	if(box2!=null){
	     for(var i=0; i<box2.length; i++) {
	
	     	box2[i].selected = true;
	
	     }
	}
	if(box3!=null){
	     for(var i=0; i<box3.length; i++) {
	
	     	box3[i].selected = true;
	
	     }
	}
}

function select_repeat_month_type(i){
	var item = document.event_form.repeat_month_type;
	if(item != null){
		item[i].checked=true;
	}
}

function select_day_in_month(i,j) { 
	var item = document.event_form.day_in_month_type;
	if(item != null){
		item[i].checked=true;
	}
	item = document.event_form.repeat_type;
	if(item != null){
		item[j].checked=true;
	}
}

function select_repeat_type(i) { 

	document.event_form.repeat_type[i].checked=true;

}

function select_day_in_week(j) { 
    
	document.event_form.repeat_type[j].checked=true;

}

function select_email(form_name, field_name, value1, hidden_field_name) {
    
	if (window.opener && !window.opener.closed) {
		var form1 = window.opener.document.forms[form_name];
		if (form1 != null) {
			var field = form1.elements[field_name];
			var hidden_field = form1.elements[hidden_field_name];
         		if (field != null && hidden_field != null) {
				var emails = "";
				var hidden_emails = "";
				var i;
				for(i = 0; i < value1.options.length; i++) {
					emails = emails + value1.options[i].text + ",";
					if(value1.options[i].value.indexOf('@') == -1)
						hidden_emails = hidden_emails + value1.options[i].value + ",";
				}
				form1.elements[field_name].value = emails;
				form1.elements[hidden_field_name].value = hidden_emails;
            		}
			field.focus();
		}
	}
	window.close();
}

function setEmailList(form_name, field, value, hidden_field) {
	
	if (window.opener && !window.opener.closed) {
		var tfield = window.opener.document.forms[form_name].elements[field];
		var thidden_field = window.opener.document.forms[form_name].elements[hidden_field];
		if (tfield != null && thidden_field != null) {
			thidden_field.value = "";
			var strings = tfield.value.split(",");
			value.value = value.value.substring(0, value.value.length - 1);
			var projectMembers = value.value.split(",");
			var i;
			var j;
			for(i = 0; i < strings.length; i++)
				if(strings[i] != "" && strings[i].indexOf("@") == -1) {
					for(j = 0; j < projectMembers.length; j++) {
						var temp = projectMembers[j].split("/");
						if(temp[0] == strings[i]) {
							thidden_field.value = thidden_field.value + temp[1] + ",";
							break;
						}
					}
					if(j == projectMembers.length)
						strings[i] = "";
				}
			tfield.value = "";
			for(i = 0; i < strings.length; i++) {
				if(strings[i] != "")
					tfield.value = tfield.value + strings[i] + ",";
			}
		}
	}
}

function setEmailListThisPage(form_name, field, value, hidden_field) {
	
		var tfield = document.forms[form_name].elements[field];
		var thidden_field = document.forms[form_name].elements[hidden_field];
		if (tfield != null && thidden_field != null) {
			thidden_field.value = "";
			var strings = tfield.value.split(",");
			value.value = value.value.substring(0, value.value.length - 1);
			var projectMembers = value.value.split(",");
			var i;
			var j;
			for(i = 0; i < strings.length; i++)
				if(strings[i] != "" && strings[i].indexOf("@") == -1) {
					for(j = 0; j < projectMembers.length; j++) {
						var temp = projectMembers[j].split("/");
						if(temp[0] == strings[i]) {
							thidden_field.value = thidden_field.value + temp[1] + ",";
							break;
						}
					}
					if(j == projectMembers.length)
						strings[i] = "";
				}
			tfield.value = "";
			for(i = 0; i < strings.length; i++) {
				if(strings[i] != "")
					tfield.value = tfield.value + strings[i] + ",";
			}
		}
}

function MoveEmail(fbox, tbox) {

	var arrTbox = new Array();//save value
	var arrTboxText = new Array(); //save text
	var add = true;
	var i, j;

	for(i = 0; i < tbox.options.length; i++) {
		arrTbox[i] = tbox.options[i].value;
		arrTboxText[i] = tbox.options[i].text;
	}
	var tLength = arrTbox.length
	for(i = 0; i < fbox.options.length; i++)
     		if(fbox.options[i].selected && fbox.options[i].value != "") {
			fbox.options[i].selected = false;
			for(j = 0; j < tLength; j++)
				if(fbox.options[i].value == arrTbox[j])
					add = false;
			if(add) {
				arrTbox[tLength] = fbox.options[i].value;
				arrTboxText[tLength++] = fbox.options[i].text;
			}
			add = true;
		}
	i = tbox.options.length - 1;
	if(i < 0)
		i = 0;
	for(; i < arrTbox.length; i++) {
		var no = new Option();
		no.value = arrTbox[i];
		if(arrTboxText[i].indexOf("@") != -1)
			no.text = arrTbox[i];
		else
			no.text = arrTboxText[i];
		tbox[i] = no;
	}
}

function emailDelete(e, target) {
	
	var keynum;
	var i = 0, j = 0;
	var arrNotSelectText = new Array();
	var arrNotSelectValue = new Array();

	if(window.event) { // IE
	  keynum = e.keyCode;
	}
	else if(e.which) { // Netscape/Firefox/Opera
	  keynum = e.which;
	}
	if(keynum == 46) {
		for(i = 0; i < target.length; i++)
			if(!target.options[i].selected) {
				arrNotSelectText[j] = target.options[i].text;
				arrNotSelectValue[j] = target.options[i].value;
				j++;
			}
		target.length = 0;
		for(i = 0; i < arrNotSelectText.length; i++) {			
			var no = new Option();				
			no.text = arrNotSelectText[i];
			no.value= arrNotSelectValue[i];				
			target[i] = no;
		}
	}
}

function checkAlso(clickOn,target){
	if(clickOn.checked){
		target.checked=true;
	}
}

function uncheckAlso(clickOn,target){
	if(! clickOn.checked){
		target.checked=false;
	}
}

var getFFVersion = navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1];
// extra height in px to add to iframe in FireFox 1.0+ browsers
var FFextraHeight = (getFFVersion >= 0.1 ? 16 : 0);

function dyniframesize(iframename) {
  var pTar = null;
  if (document.getElementById){
    pTar = document.getElementById(iframename);
  }
  else{
    eval('pTar = ' + iframename + ';');
  }
  if (pTar && !window.opera){
    //begin resizing iframe
    pTar.style.display="block"
    
    if (pTar.contentDocument && pTar.contentDocument.body.offsetHeight){
      //ns6 syntax
      pTar.height = pTar.contentDocument.body.offsetHeight+FFextraHeight; 
    }
    else if (pTar.Document && pTar.Document.body.scrollHeight){
      //ie5+ syntax
//      pTar.height = pTar.Document.body.scrollHeight;
      pTar.height = screen.availHeight;;
    }
  }
}

function select_knowledges(form_name, field_name, hidden_field_name, kmBoxList, keyToName) {
	select_knowledges(form_name, field_name, hidden_field_name, kmBoxList, keyToName, '');
}

function select_knowledges(form_name, field_name, hidden_field_name, kmBoxList, keyToName, doc_version_rule_field_name) {
	if (window.opener && !window.opener.closed) {
		var form1 = window.opener.document.forms[form_name];
    
		if (form1 != null) {
			var field = form1.elements[field_name];
			var hidden_field = form1.elements[hidden_field_name];

			if (field != null) {
				var knowledgeShowList = new Array();
				var knowledgesList = new Array();

        if(kmBoxList.length==null){
          if(kmBoxList.checked){
            knowledgeShowList.push(keyToName.value);
					  knowledgesList.push(kmBoxList.value);
          }
        }else{
          for ( var i = 0; i < kmBoxList.length; i++) {
					if (!kmBoxList[i].checked) {
						continue;
					}
					 knowledgeShowList.push(keyToName[i].value);
					 knowledgesList.push(kmBoxList[i].value);
				  }
        }

				

				field.value = knowledgeShowList.join();
				hidden_field.value = knowledgesList.join();
			}
		}
		/* catch focus error when field display=none */
		try {
			field.focus();
		} catch (e) {
		}
	}

	if (doc_version_rule_field_name != null && doc_version_rule_field_name != '') {
		if (window.opener.updateDocVersionRule != undefined) {
			window.opener.updateDocVersionRule(form_name, hidden_field_name, doc_version_rule_field_name);
		}
	}

	window.close();
}

function resetNotifyees(_element_id) {
	var element = null;

	element = document.getElementById("notification_flag_0");
	if (element != null) {
		element.checked = false;
		element.disabled = false;
	}
	element = document.getElementById("notification_flag_1");
	if (element != null) {
		element.checked = true;
		element.disabled = false;
	}
	element = document.getElementById("managerName");
	if (element != null) {
		element.value = "";
		element.size = 55;
	}
	element = document.getElementById("workerName");
	if (element != null) {
		element.value = "";
		element.size = 55;
	}
	element = document.getElementById("orgName");
	if (element != null) {
		element.value = "";
		element.size = 55;
	}
	for ( var i = 1; i < 10; i++) {
		element = document.getElementById(_element_id + "_" + i);
		if (element == null) {
			continue;
		}
		if (i < 5 || i > 7) {
			element.checked = false;
			element.disabled = false;
		} else {
			element.style.display = "none";
		}
	}
}

function updateTableRowNumber(target_table){
	updateTableRowNumberComplete(target_table, 0, 1, "");
}

function updateTableRowNumberAndSaveNextNo(target_table, save_next_no_at_element_id){
	updateTableRowNumberComplete(target_table, 0, 1, save_next_no_at_element_id);
}

function updateTableRowNumberComplete(target_table, add_cell_number, from_row_number, save_next_no_at_element_id){
	var no = 1;
	for(var i=from_row_number; i<target_table.rows.length; i++){
		target_table.rows[i].cells[add_cell_number].innerHTML = no;
		no++;
	}
	if (save_next_no_at_element_id != null && save_next_no_at_element_id.length > 0) {
		var element = document.getElementById(save_next_no_at_element_id)
		element.value = no;
	}
}



