/**
* This file contains common auxiliary methods.
**/

/* extending javascript String object */
String.prototype.trim = function(){
    return this.replace(/(^\s*)|(\s*$)/g, "");
}


/* Check if the value of the given object is an email */
function validEmail(val){

	var filter  = /^[a-zA-Z0-9][\w\.\_\+\-]*[a-zA-Z0-9\+]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]+$/;
	if (!filter.test(val)){
		return false;
	}
	return true;
}

/* Check if the value of the given object is a string */
function validString(val){
	return true;
}

/* Check if the value of the given object is an integer */
function validInt(val){
	var intRE = /^[0-9]*$/;
	
	if(!intRE.test(val)){
		return false;
	}
	return true;
}


/* Check if the value of the given object is a float */
function validFloat(val){
	var filter = /^\s*(\-)*\s*[(0-9|\.)]*\s*$/;
	var valid = true;
	
	if(!filter.test(val)){
		return false;
	}

	if(val.indexOf('.') != val.lastIndexOf('.')){
		return false;
	}
	return true;
}

/* Check if the value of the given object is a phone number */
function validPhone(val){
	return true;
}

function validPassword(val){
	return true;
}

function setStyle(obj, cssCls){
	var oldCls = obj.className;
	obj.setAttribute("xafclass", oldCls);
	obj.className = cssCls;
//	obj.addCSSClass(cssCls);
}

function resetStyle(obj){
	var prevCls = obj.getAttribute("xafclass");
	obj.className = prevCls;
//	obj.addCSSClass(prevCls);
}


/* validate date with the given date format */
/* date formate */
/* yyyy 	- year 
/* MM		- month
/* dd		- date
/* HH		- hour
/* mm		- min
/* ss		- second
/* SSS		- millisecond */
function validDate(dateformat, dateStr){
	var dfElemRE = "yyyy|MM|dd|HH|mm|ss|SSS";
	var nmRE = "[0-9]+";

	var year = 0;
	var month = 0;
	var date = 0;
	var hour = 0;
	var min = 0;
	var sec = 0;
	var milsec = 0;
	
	while(true){
	
		var match = dateformat.match(dfElemRE);
		var fnum = dateStr.match(nmRE);
		
		if(!match){
			break;
		}

		if(match == 'yyyy'){
			year = parseInt(fnum, 10);
		}else if(match == 'MM'){
			month = parseInt(fnum, 10);
		}else if(match == 'dd'){
			date = parseInt(fnum, 10);
		}else if(match == 'HH'){
			hour = parseInt(fnum, 10);
		}else if(match == 'mm'){
			min = parseInt(fnum, 10);
		}else if(match == 'ss'){
			sec = parseInt(fnum, 10);
		}else if(match == 'SSS'){
			milsec = parseInt(fnum, 10);
		}
		
		dateformat = dateformat.replace(match, '');
		dateStr = dateStr.replace(fnum, '');
	}

	var dateObj = new Date();
	dateObj.setFullYear(year, month - 1, date);
	dateObj.setHours(hour, min, sec, milsec);

	if(
		year != parseInt(dateObj.getFullYear(), 10)
		|| month != parseInt(dateObj.getMonth(), 10) + 1
		|| date != parseInt(dateObj.getDate(), 10)
		|| hour != parseInt(dateObj.getHours(), 10)
		|| min != parseInt(dateObj.getMinutes(), 10)
		|| sec != parseInt(dateObj.getSeconds(), 10)
		|| milsec != parseInt(dateObj.getMilliseconds(), 10)
	){
		return false;
	}
	
	/**
	alert(dateObj.getFullYear() + "," + dateObj.getMonth() + "," + dateObj.getDate()
	+ "," + dateObj.getHours() + "," + dateObj.getMinutes() + "," + dateObj.getSeconds()
	+ "," + dateObj.getMilliseconds() + "\n"
	+ year + "," + month + "," + date + "," + hour + "," + min + "," + sec + "," + milsec
	);
	**/

	return true;
}

/* return true if the date conforms to the given date format */
/* date formate */
/* yyyy 	- year 
/* MM		- month
/* dd		- date
/* HH		- hour
/* mm		- min
/* ss		- second
/* SSS		- millisecond */
function validDateFormat(dateformat, dateStr){
	var yearRE = "[0-9]{1,4}";
	var monthRE = "[0-9]{1,2}";
	var dateRE = "[0-9]{1,2}";
	
	var hourRE = "[0-9]{1,2}";
	var minRE = "[0-9]{1,2}";
	var secRE = "[0-9]{1,2}";
	
	var milsecRE = "[0-9]{1,3}";
	
	var nmRE = "[0-9]+";
	
	var dfRE;
	dfRE = dateformat.replace(/yyyy/, yearRE);
	dfRE = dfRE.replace(/MM/, monthRE);
	dfRE = dfRE.replace(/dd/, dateRE);
	dfRE = dfRE.replace(/HH/, hourRE);
	dfRE = dfRE.replace(/mm/, minRE);
	dfRE = dfRE.replace(/ss/, secRE);
	dfRE = dfRE.replace(/SSS/, milsecRE);
	
	if(!dateStr.match("^" + dfRE + "$")){
		return false;	
	}
	return true;
}


/* Checks if the value of the given object is empty */
 function checkEmpty(obj){
	var val = getObjValue(obj);
	if(val == undefined || val == ''){
		return true;
	}
 	return false;
 }

/* Gets the value of the given object by id */
/* Assumes the coder to use the id only once ==> id must be unique */
/* The type of the object is automatically recognized */
/* Currenty, <select, <input, <textarea, are recognized */
 function getObjValueById(id){
    var obj = document.getElementById(id);
  	if(obj.tagName.toLowerCase() == 'input'){
		return obj.value;
 	}else if(obj.tagName.toLowerCase() == 'textarea'){
		return obj.value;
 	}else if(obj.tagName.toLowerCase() == 'select'){
 		var op = obj.options[obj.selectedIndex];
 		var val = op.value;
		return val;
 	}
 }

/* Gets the value of the given object */
/* The type of the object is automatically recognized */
/* Currenty, <select, <input, <textarea, are recognized */
 function getObjValue(obj){
 
  	var array = obj.length != undefined && obj.tagName == undefined;
 	
 	if(array){
  		if(obj[0].type.toLowerCase() == 'radio'){
  			var len = obj.length;
  			for(var i = 0; i < len; i++){
  				var r = obj[i];
  				if(r.checked){
  					return r.value;
  				}
  			}
		}		
 	}else if(obj.tagName.toLowerCase() == 'input'){
		return obj.value;
 	}else if(obj.tagName.toLowerCase() == 'textarea'){
		return obj.value;
 	}else if(obj.tagName.toLowerCase() == 'select'){
 		var op = obj.options[obj.selectedIndex];
 		var val = op.value;
		return val;
 	}else{
 		return obj.innerHTML;
 	}
 }

 function setObjValue(obj, val){
 	
  	var array = obj.length != undefined && obj.tagName == undefined;
 	
 	if(array){
 	  	if(obj[0].type == 'radio'){
			var len = obj.length;
			for(var i = 0; i < len; i++){
				var r  = obj[i];
				if(r.value == val){
					r.checked = true;
				}else{
					r.checked = false;
				}
			}
  		}
 	}else if(obj.tagName.toLowerCase() == 'input'){
  		var type = obj.type.toLowerCase();
  		
		if(type == 'checkbox'){
  			obj.checked = val;
  		}else{
			obj.value = val;
  		}
 	}else if(obj.tagName.toLowerCase() == 'textarea'){
		obj.value = val;
 	}else if(obj.tagName.toLowerCase() == 'select'){
 		for(var i = 0 ; i < obj.options.length; i++){
	 		var op = obj.options[i];	
	 		if(op.value == val){
				obj.selectedIndex = i;
				return;
	 		}
 		}
 	}else{
 		obj.innerHTML = val;
 	}
 }
 
 /* Clear the value of the given obj */
/* The type of object is automatically recognized and reset the value */
/* Currenty, <input, <select, <textare, are recognied */
 function clearValue(obj){
  	if(obj.tagName.toLowerCase() == 'input' && 
  		obj.type.toLowerCase() == 'text'){
		obj.value = '';
 	}else if(obj.tagName.toLowerCase() == 'textarea'){
		obj.value = '';
 	}else if(obj.tagName.toLowerCase() == 'select'){
		obj.options[0].selected = true;		 		
 	}
 	return false;
 }

/* Iterates through all input objects within the first form tag 
/* and call clearValue() function */
 function clearForm(){
  	var elements = document.forms[0].elements;
 	for(var i = 0; i < elements.length; i++){
 		var obj = elements[i];
		clearValue(obj);
 	}
 }
 
 
 function removeChildNodes(obj) {
    if (!obj) {
        return;
    }
    var len = obj.childNodes.length;
    while (obj.hasChildNodes()) {
        obj.removeChild(obj.firstChild);
    }
}

function formatDigits(num, dgt){
	var val = roundDecimal(num, dgt);
	val = new String(val);
	var idx = val.indexOf('.');
	var diff = 0;
	
	if(idx == -1){
		val += ".";
		diff = dgt;
	}else{
		diff = dgt - (val.length - idx - 1);
	}

	
	for(var i = 0; i < dgt; i++){
		val += "0";
	}

	return val;
}

function roundDecimal(num, dgt){
	var tens = Math.pow(10, dgt);
	return Math.round(num*tens)/tens;
}

function setCSSLink(cssname){
	var heads = document.getElementsByTagName('head');
	var head = heads[0];
	
	var link = document.createElement('link');
	link.rel = "stylesheet";
	link.type = 'text/css';
	link.href = cssname;
	
	head.appendChild(link);
}

function isEmpty(val){
	if(val == undefined){
		return true;
	}
	
	if(val == null){
		return true;
	}
	
	var valstr = new String(val);
	if(valstr.trim() == ''){
		return true;
	}
}

function findPos(elem){
	
    var left = 0;
    var top = 0;
    while (elem) {
      left += elem.offsetLeft - elem.scrollLeft;
      top += elem.offsetTop - elem.scrollTop;
      elem = elem.offsetParent;
    }
    
    return [left, top];
}

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)
}

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 null
}


function byId(id){
	return document.getElementById(id);
}

function byName(name){
	return document.getElementsByName(name);
}

/********************************/
/* Auto Resize Iframe */
/*********************************/
var autoResizeIframeTimer;
var resizableIframeId;

function autoResizeIframeTimer(iframeId, interval){
	resizableIframeId = iframeId;
	autoResizeIframeTimer = setInterval('_resizeIframe()', interval);
}

function autoResizeIframe(iframeId){
	resizableIframeId = iframeId;
}

function _resizeIframe(){
	var frame = parent.document.getElementById(resizableIframeId);
	var innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
		
	
	var objToResize = (frame.style) ? frame.style : frame;
	
	if(parseFloat(objToResize.width) >= parseFloat(innerDoc.body.scrollWidth) &&
		parseFloat(objToResize.height) >= parseFloat(innerDoc.body.scrollHeight))
	{   
		if(autoResizeIframeTimer){
		
			clearInterval(autoResizeIframeTimer);
		}
	}else{
		objToResize.width = innerDoc.body.scrollWidth;
		objToResize.height = innerDoc.body.scrollHeight + 20;
		
	}
}

var autoResizeWindowTimer;
function autoResizeWindow(interval){
	
	var w = document.body.scrollWidth;
	var h = document.body.scrollHeight;
	
	w = Math.max(w, 300);
	h = Math.max(h, 300);	
	
	window.resizeTo(w + 100, h + 100);
	
//	if (!interval) {
//		interval = 500;
//	}
	
	//autoResizeWindowTimer = setInterval('_autoResizeWindow', interval);
}

function _autoResizeWindow()
{
	var isWidthOkay = parseFloat(document.width) >= parseFloat(document.body.scrollWidth) + 10;
	var isHeightOkay = parseFloat(document.height) >= parseFloat(document.body.scrollHeight) + 10;
	
	if(isWidthOkay && isHeightOkay)
	{
		if(autoResizeWindowTimer){
			clearInterval(autoResizeWindowTimer);
		}
	} else {
		
		var xIncrease = isWidthOkay?0:10;
		var yIncrease = isHeightOkay?0:10;
		
		window.resizeBy(xIncrease, yIncrease);
	}
}

function autoAdjustHeight(){
	var w = document.body.scrollWidth;
	var h = document.body.scrollHeight;
	
	w = Math.min(w, 800);
	
	window.resizeTo(w, h);
}

/* simple map */

var SimpleMap = function(){
	this.idmap = new Object();
	this.idxmap = new Object();
	this.array = new Array();
}

SimpleMap.prototype.exist = function(rowid){
	return this.idmap[rowid] == true;
}

SimpleMap.prototype.add = function(rowid){
	if(this.exist(rowid)){
		this.array.splice(this.indexOf(rowid), 1, rowid);
	}else{
		this.idmap[rowid] = true;	
		this.idxmap[rowid] = this.array.length;
		this.array.push(rowid);
	}
}

SimpleMap.prototype.get = function(idx){
	return this.array[idx];
}

SimpleMap.prototype.indexOf = function(rowid){
	return this.idxmap[rowid];
}

SimpleMap.prototype.remove = function(rowid){
	if(this.exist(rowid)){
		this.idmap[rowid] = undefined;
		this.array.splice(this.idxmap[rowid], 1);
		this.idxmap[rowid] = undefined;
	}
}

SimpleMap.prototype.toString = function(){
	return this.array.toString();
}

SimpleMap.prototype.length = function(){
	return this.array.length;
}

function GetCookie(sName)
{
  // cookies are separated by semicolons
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)
  {
    // a name/value pair (a crumb) is separated by an equal sign
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0]) 
      return unescape(aCrumb[1]);
  }

  // a cookie with the requested name does not exist
  return null;
}

// Create a cookie with the specified name and value.
// The cookie expires at the end of the 21st century.
function SetCookie(sName, sValue, exp)
{
	var expstr = "expires=Fri, 31 Dec 2099 23:59:59 GMT";
	if(exp){
		expstr = "expires=" + exp;
	}
  document.cookie = sName + "=" + escape(sValue) + "; " + expstr + ";";
  
}
function validateDate(yearObj, monthObj, dateObj){
	var date = getObjValue(dateObj);
	var month = getObjValue(monthObj);
	var year = getObjValue(yearObj);
	
	if (date == '-'){
		setObjValue(dateObj, date);
		return;
	}
	
	if (month == '-'){
		setObjValue(monthObj, month);
		return;
	}
	
	if (year == '-'){
		setObjValue(yearObj, year);
		return;
	}
	
	var billDate = new Date();
	billDate.setFullYear(year,parseInt(month) - 1, date);
	
	setObjValue(dateObj, billDate.getDate());
	setObjValue(monthObj, billDate.getMonth() + 1);
	setObjValue(yearObj, billDate.getYear());
}
