/*-------------------------- Some JavaScript utilities --------------------------------
- isDigit : test it a character is a digit or not.
- isImage : test it a string is a image or not
- isNumber : test it a string is a number or not.
- trimLeft : cut leading blank spaces of a string.
- trimRight: cut trailing blank spaces of a string.
- trim: cut all leading and trailing blank spaces of a string
- isPosInt: test if a string has the format of a positive integer number or not.
- isPosReal: test if a string has the format of a positive real number or not. The decimal 
			 separator must be ".".
- isEmail: test if a string is a valid e-mail address or not
- isURL: test if a string is a valid url address or not
- isZip: test if a string has the format of a US zip code or not.
- getFileName: return the file name form the full file name.
- getFileExt: return the file extenstion from the full file name.
- isFloat: 
--------------------------------Implementation ---------------------------------------*/
/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;


/**
 * This array is used to remember mark status of rows in browse mode
 */
var marked_row = new Array;


/**
 * Sets/unsets the pointer and marker in browse mode
 *
 * @param   object    the table row
 * @param   integer  the row number
 * @param   string    the action calling this script (over, out or click)
 * @param   string    the default background color
 * @param   string    the color to use for mouseover
 * @param   string    the color to use for marking a row
 *
 * @return  boolean  whether pointer is set or not
 */
function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor)
{
    var theCells = null;

    // 1. Pointer and mark feature are disabled or the browser can't get the
    //    row -> exits
    if ((thePointerColor == '' && theMarkColor == '')
        || typeof(theRow.style) == 'undefined') {
        return false;
    }

    // 2. Gets the current row and exits if the browser can't get it
    if (typeof(document.getElementsByTagName) != 'undefined') {
        theCells = theRow.getElementsByTagName('td');
    }
    else if (typeof(theRow.cells) != 'undefined') {
        theCells = theRow.cells;
    }
    else {
        return false;
    }

    // 3. Gets the current color...
    var rowCellsCnt  = theCells.length;
    var domDetect    = null;
    var currentColor = null;
    var newColor     = null;
    // 3.1 ... with DOM compatible browsers except Opera that does not return
    //         valid values with "getAttribute"
    if (typeof(window.opera) == 'undefined'
        && typeof(theCells[0].getAttribute) != 'undefined') {
        currentColor = theCells[0].getAttribute('bgcolor');
        domDetect    = true;
    }
    // 3.2 ... with other browsers
    else {
        currentColor = theCells[0].style.backgroundColor;
        domDetect    = false;
    } // end 3

    // 3.3 ... Opera changes colors set via HTML to rgb(r,g,b) format so fix it
    if (currentColor.indexOf("rgb") >= 0)
    {
        var rgbStr = currentColor.slice(currentColor.indexOf('(') + 1,
                                     currentColor.indexOf(')'));
        var rgbValues = rgbStr.split(",");
        currentColor = "#";
        var hexChars = "0123456789ABCDEF";
        for (var i = 0; i < 3; i++)
        {
            var v = rgbValues[i].valueOf();
            currentColor += hexChars.charAt(v/16) + hexChars.charAt(v%16);
        }
    }

    // 4. Defines the new color
    // 4.1 Current color is the default one
    if (currentColor == ''
        || currentColor.toLowerCase() == theDefaultColor.toLowerCase()) {
        if (theAction == 'over' && thePointerColor != '') {
            newColor              = thePointerColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
            marked_row[theRowNum] = true;
            // Garvin: deactivated onclick marking of the checkbox because it's also executed
            // when an action (like edit/delete) on a single item is performed. Then the checkbox
            // would get deactived, even though we need it activated. Maybe there is a way
            // to detect if the row was clicked, and not an item therein...
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = true;
        }
    }
    // 4.1.2 Current color is the pointer one
    else if (currentColor.toLowerCase() == thePointerColor.toLowerCase()
             && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
        if (theAction == 'out') {
            newColor              = theDefaultColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
            marked_row[theRowNum] = true;
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = true;
        }
    }
    // 4.1.3 Current color is the marker one
    else if (currentColor.toLowerCase() == theMarkColor.toLowerCase()) {
        if (theAction == 'click') {
            newColor              = (thePointerColor != '')
                                  ? thePointerColor
                                  : theDefaultColor;
            marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
                                  ? true
                                  : null;
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = false;
        }
    } // end 4

    // 5. Sets the new color...
    if (newColor) {
        var c = null;
        // 5.1 ... with DOM compatible browsers except Opera
        if (domDetect) {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].setAttribute('bgcolor', newColor, 0);
            } // end for
        }
        // 5.2 ... with other browsers
        else {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].style.backgroundColor = newColor;
            }
        }
    } // end 5

    return true;
} // end of the 'setPointer()' function


// added 2004-05-08 by Michael Keck <mail_at_michaelkeck_dot_de>
//   copy the checked from left to right or from right to left
//   so it's easier for users to see, if $cfg['ModifyAtRight']=true, what they've checked ;)
function copyCheckboxesRange(the_form, the_name, the_clicked)
{
    if (typeof(document.forms[the_form].elements[the_name]) != 'undefined' && typeof(document.forms[the_form].elements[the_name + 'r']) != 'undefined') {
        if (the_clicked !== 'r') {
            if (document.forms[the_form].elements[the_name].checked == true) {
                document.forms[the_form].elements[the_name + 'r'].checked = true;
            }else {
                document.forms[the_form].elements[the_name + 'r'].checked = false;
            }
        } else if (the_clicked == 'r') {
            if (document.forms[the_form].elements[the_name + 'r'].checked == true) {
                document.forms[the_form].elements[the_name].checked = true;
            }else {
                document.forms[the_form].elements[the_name].checked = false;
            }
       }
    }
}


// added 2004-05-08 by Michael Keck <mail_at_michaelkeck_dot_de>
//  - this was directly written to each td, so why not a function ;)
//  setCheckboxColumn(\'id_rows_to_delete' . $row_no . ''\');
function setCheckboxColumn(theCheckbox){
    if (document.getElementById(theCheckbox)) {
        document.getElementById(theCheckbox).checked = (document.getElementById(theCheckbox).checked ? false : true);
        if (document.getElementById(theCheckbox + 'r')) {
            document.getElementById(theCheckbox + 'r').checked = document.getElementById(theCheckbox).checked;
        }
    } else {
        if (document.getElementById(theCheckbox + 'r')) {
            document.getElementById(theCheckbox + 'r').checked = (document.getElementById(theCheckbox +'r').checked ? false : true);
            if (document.getElementById(theCheckbox)) {
                document.getElementById(theCheckbox).checked = document.getElementById(theCheckbox + 'r').checked;
            }
        }
    }
}



function setCheckboxes(the_form, name, do_check, type) { // name is element's name; type is disabled or checked
	//alert(do_check);
    var elts      = document.forms[the_form].elements[name];
	var elts_cnt  = (typeof(elts.length) != 'undefined')
                  ? elts.length
                  : 0;
	if (do_check == 0) do_check = ''; 
	if (elts_cnt) {
		for (var i = 0; i < elts_cnt; i++) {
			if (type == 'checked') elts[i].checked = do_check;
			else {
				elts[i].checked = do_check;			
				elts[i].disabled = do_check;
			}
		} // end for
	}
	else {
		if (type == 'checked') elts.checked        = do_check;
		else {
			elts.checked        = do_check;
			elts.disabled        = do_check;
		}
	}	
    return true;
} // end of the 'setCheckboxes()' function

function check_selected_checkbox(the_form, name, do_check, type, pos) { // name is element's name; type is disabled or checked
	//alert(do_check);
    var elts      = document.forms[the_form].elements[name];
	var elts_cnt  = (typeof(elts.length) != 'undefined')
                  ? elts.length
                  : 0;
	if (elts_cnt) {
		if (elts[pos].checked){
			elts[pos].checked = '';				  
		}
		else {
			elts[pos].checked = 'checked';				  
		}
	}
	else {
		if (elts.checked){
			elts.checked = '';
		}
		else {
			elts.checked = 'checked';
		}
	}
    return true;
	
} // end of the 'setCheckboxes()' function

////////////////////////////////////////////////////////////////////////////////
function IsEmpty(strValue){
	if(strValue=="")
		return true;
	var strValueTest = new String(strValue);
	while(strValueTest.search(" ")!= -1)
		strValueTest = strValueTest.replace(" ", "");
	return (strValueTest.length== 0);
}
////////////////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////////////////
function isDate(strValue, dateFormat){ //dateFormat is mm/dd/yyyy or dd/mm/yyyy

	if(IsEmpty(strValue))return true;
	
	var arrDate = strValue.split("/");
	if(arrDate.length < 3) return false;
	
	if (dateFormat == 'mm/dd/yyyy') { 
		var strDay = arrDate[1];
		var strMonth = arrDate[0];
		var strYear = arrDate[2];

	}
	else {
		var strDay = arrDate[0];
		var strMonth = arrDate[1];
		var strYear = arrDate[2];
	}
		
	if(strYear.charAt(0) != 1&&strYear.charAt(0) != 2){
		if(strYear.charAt("0") == 0){
			strYear = "20" + strYear;
		}
		else{
			strYear = "19" + strYear;
		}
	}

	//alert("strYear="+strYear);
	//alert("strMonth = "+strMonth);
	//alert("strDay = "+ strDay);		

	/*
	var testDate = new Date(strYear, strMonth, strDay);
	alert(testDate.getYear());
	alert(testDate.getMonth());	
	alert(testDate.getDate());	
	*/	

	if(strYear < 90 || strYear > 2100) return false;
	else if (strMonth < 1 || strMonth > 12) return false;
	else if (strDay < 1 || strDay > 31) return false;
	
	return true;
	//alert(testDate.getMonth());
	/*
	alert(testDate.getMonth() + 1);
	alert(strMonth);
	if(testDate.getMonth() + 1 == strMonth){
		return true;
	} 
	else{
		return false;
	}
	*/
	
}


/*
    compare two date.
    return :
        start <= end    :   true
        start > end     :   false
*/
function compareDate(start, end, dateFormat){
    
    //check data pass
   // if((start.length == 0) || (end.length==0) ) return false;
    
    //create two Date objects
	/*
    var s = new Date(start);
    var e = new Date(end);
    
    //get month, year, date of date objects
    var s_y = parseInt(s.getYear());
    var s_m = parseInt(s.getMonth());
    var s_d = parseInt(s.getDate());
    
    var e_y = parseInt(e.getYear());
    var e_m = parseInt(e.getMonth());
    var e_d = parseInt(e.getDate());
	*/
	
	var arrDate = start.split("/");
	if(arrDate.length < 3) return false;
	
	if (dateFormat == 'mm/dd/yyyy') { 
		var s_d = arrDate[1];
		var s_m = arrDate[0];
		var s_y = arrDate[2];

	}
	else {
		var s_d = arrDate[0];
		var s_m = arrDate[1];
		var s_y = arrDate[2];
		//alert(strDay);
		
	}

	var arrDate = end.split("/");
	if(arrDate.length < 3) return false;
	
	if (dateFormat == 'mm/dd/yyyy') { 
		var e_d = arrDate[1];
		var e_m = arrDate[0];
		var e_y = arrDate[2];

	}
	else {
		var e_d = arrDate[0];
		var e_m = arrDate[1];
		var e_y = arrDate[2];
		//alert(strDay);
		
	}

	//alert(s_m);
	//alert(e_m);

    //compare year , month and day of them
    if( s_y <= e_y){ // compare year
        if(s_y == e_y){
            if(s_m <= e_m){//compare month
                if(s_m == e_m ){
                    if(s_d <= e_d){// compare date
                        return true;
                    }else{
                        return false;
                    }//end compare date
                }
                return true;
            }else{
                return false;
            }// end compare month
        }    
        return true;
    }else{
        return false
    }// end compare year
            
}



function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}


function isFloat(obj_val){
	var number_format = "0123456789.";
	for (var i = 0; i < obj_val.length; i++)
	{
		check_char = number_format.indexOf(obj_val.charAt(i))
		if (check_char < 0)
			return false;
	}
	var pos = obj_val.indexOf('.');
	if (pos==0 || (pos>0 && obj_val.indexOf('.',pos+1)>=0))
		return false;
	return true;
}


/*
isDigit
Check if a character is a digit or not
*/
function isDigit(c){
	if((c=='0')||(c=='1')||(c=='2')||(c=='3')||(c=='4')||(c=='5')||(c=='6')||(c=='7')||(c=='8')||(c=='9'))
		return true;
	else
		return false;
}
/*
isNumber
Check if a string is a number
*/
function isNumber(str){
	var check_char;
	var number_format = "0123456789.";
	for (var i = 0; i < str.length; i++)
	{
		check_char = number_format.indexOf(str.charAt(i));
		if (check_char < 0){
			return false;
		}
	}
	return true;
}

function is_instr_schars(str){
	var check_char;
	var special_char = "`~!@#$%^&*()+={}[]|\":;\",<>.?/";
	for (var i = 0; i < str.length; i++){
		check_char = special_char.indexOf(str.charAt(i));
		if (check_char > 0){
			return false;
		}
	}
	return true;

}


/*
isCharacter
*/
function isCharacter(str)
{
	for (var i = 0; i < str.length; i++)
	{
		check_char = number_format.indexOf(str.charAt(i));
		if (check_char < 0){
			return false;
		}
	}
	return true;
}
/*-------End check number------------------*/
/*
 trimLeft
 Remove all spaces at the beginning of a string
*/
function trimLeft(s)
{
 var i;
 i=0;
 var n;
 n = s.length;
 while((i<n)&&(s.charAt(i)==' ')) i++;
	s = s.substring(i);
 return(s);
} 

/*
 trimRight
 Remove all spaces at the end of a string
*/
function trimRight(s)
{
 var n;
 n = s.length;
 var i;
 i = s.length-1;
 while((i>=0)&&(s.charAt(i)==' ')) i--;
	s = s.substring(0,i+1);
 return(s);
}

/* 
 trim
 Remove all leading and trailing spaces in a string
*/
function trim(s){
 s = trimLeft(s);
 s = trimRight(s);
 return(s);
}  

/*
 isPosInt
 check if a string is a valid positive integer
*/
function isPosInt(s){
 var n;
 n = s.length
 if(n==0) return false;
 for(i=0;i<n;i++)
	if(!isDigit(s.charAt(i))) return false;
 return true;
}

/*
 isPosReal
 check if  a string is a valid positive real number or not (. as decimal number)
*/
function isPosReal(s){
 var dot;
 s = trim(s);
 dot =0;
 for(i=0;i<s.length;i++)
	if(!isDigit(s.charAt(i))) 
		{
			if(s.charAt(i)=='.') 
				{
					dot++;
					if(i==s.length-1) return false;
					if(dot>1) return false;
				}
			else return false;	
		}
 return true;
}





/*
 isEmail
 check if an email address is valid (format only) 
*/
function isEmail(strEmail)
{
 var intlen;
 var ctmp;
 strEmail = trim(strEmail);
 if(strEmail=='') return false;
 intlen=strEmail.length;
 if(intlen<5) return false;
 if(strEmail.indexOf('@')==-1) return false;
 if(strEmail.indexOf('.')==-1) return false;
 if(intlen - strEmail.lastIndexOf('.') -1 > 5) return false; 
 if((strEmail.indexOf("_")!=-1) && (strEmail.lastIndexOf("_") > strEmail.lastIndexOf("@"))) return false;
 if(strEmail.lastIndexOf(".") <= strEmail.lastIndexOf("@")+1)  return false;
 if(strEmail.indexOf("@")!=strEmail.lastIndexOf("@")) return false;
 if(intlen -1 == strEmail.lastIndexOf('.')) return false;
 if(strEmail.charAt(strEmail.indexOf('@')+1)=='.') return false;
 if(strEmail.indexOf(" ")!=-1) return false;
 if(strEmail.indexOf("..")!=-1) return false;
 if(strEmail.indexOf(";")!=-1) return false;
 
 strEmail=strEmail.toLowerCase();
 for(intcnt=0;intcnt<intlen;intcnt++)
	{
	 ctmp = strEmail.charAt(intcnt)
	 if((!isDigit(ctmp))&& ((ctmp>'z')||(ctmp<'a')) && (ctmp!='-') && (ctmp!='.') && (ctmp!='@') && (ctmp!='_')) return false;
	}

return true	;
}

/*
 isURL
 check if an url address is valid (format only) 
*/
function isURL(strURL)
{
	strURL = trim(strURL);
	if( strURL.indexOf(" ") >= 0 ) return false;
	if(strURL.indexOf("..") >= 0) return false;
	if(strURL.indexOf('\\') >= 0 ) return false;
	if(strURL.indexOf('\"') >= 0) return false;
	if(strURL.indexOf('http://') < 0 && strURL.indexOf('https://') < 0) return false;	
	if(strURL.length < 8 ) return false;	
	return true;
}


/*
getFileName
receive a full path file name, return only the file name
	ex: input = C:\Windows\myfile.txt
	output = myfile.txt
*/
function getFileName(str)
{
 var bpos
 var filename
 if((str=='')||(str.indexOf("\\")==-1)) return(str);
 bpos = str.lastIndexOf("\\");
 filename = str.substring(bpos+1,str.length)
 return(filename);
}

/* 
 getFileType
 receive a full path file name, return only the file extension
 ex: input = C:\Windows\myfile.txt
  	 output = txt
*/
function getFileType(str)
{
 var filename;
 var fileext;
 var dotpos;
 fileext ='';
 filename = getFileName(str);
 dotpos = filename.lastIndexOf(".");
 
 if(dotpos!=-1)
	{
		fileext = filename.substring(dotpos+1,filename.length);
		fileext = fileext.toLowerCase();
	}
 else
	{
		fileext = '';
	}
 return(fileext);
}



function isImage(str){
	str = str.toLowerCase();
	if (!/(\.(gif|jpg|jpeg|bmp|png|psd))$/i.test(str)){
		return false;
	}
	return true;
}

//check media
function isMedia(str){
	str = str.toLowerCase();
	if (!/(\.(wmv|avi|mp4|dat|mpg|mpeg|mp3|wma|asf|mid))$/i.test(str)){
		return false;
	}
	return true;

}
//end media


function is_upload_file(str){
	str = str.toLowerCase();
	//alert(isImage(str));
	if (!isImage(str) && !/(\.(doc|xls|ppt|zip|rar|ace|tar|txt|csv|psd|avi|dat|mpeg|mpg|wmv|mp3|mp4|mid|asf|mid))$/i.test(str)) {
		return false;	
	}
	return true;
}



function isVCode(str){
	str = trim(str);
	if (str.length != 5) return false;
	return true;
	
}


//check API Key	
function isAPIKey(str){
	var API_Key_Len = 19;
	if (str.length != API_Key_Len ) return false;
	else if (str.indexOf(" ") > 0) return false;
	else if (str.indexOf("-") < 0) return false;
	//else if (str.indexOf(symbol) < 0) return false;
	else return true;
}	

//confirm deleting
function confirm_onclick(str, url){
	//if (str == '') str = 'Do you really want to delete selected item(s)? Click OK to continue, click Cancel to return.';
	if (url != '') { 
		if (confirm(str)) window.location.href=url;
		else return false;
	}
	else return confirm(str);
		
}


function force_checkbox(theForm, pos, maxpos){
	//if (maxpos == 9999) maxpos = theForm.elements.length;
	var iCo = 0;
	if (theForm.length > 0) {
		for (var i=pos; i< maxpos; i++) {
			if (theForm.elements[i].checked==true)
			{
				iCo++;
			}		
		}
	}
	else {
		iCo = 1;
	}
			
	if (iCo < 1){
		//alert(str);
		return false;
	}
	return true;
}

function checkDoDelete(theForm,pos){
	var iCo = 0;
	if (theForm.length > 0) {
		for (var i=pos; i< theForm.elements.length;i++) {
			if (theForm.elements[i].checked==true)
			{
				iCo++;
			}		
		}
	}
	else {
		iCo = 1;
	}
	
	if (iCo>0)
	{
		return confirm("Do you really want to delete selected item(s)? Click OK to continue, click Cancel to return.");
	}
	else
	{
		alert("Please select item(s) to delete!");
		return false;
	}
}

/*
function open_diff_window(URL){
	var ran_number = Math.floor(Math.random()*50); 
	window.open(URL, ran_number);
}
*/

function new_window(URL, width, height){
	window.open (URL, "new_window", "width="+ width + ", height="+ height +", resizable=1, scrollbars=1");
}


function copy_to_clipboard(formName, fieldName){
	Copied = eval("document.forms." + formName + "." + fieldName + ".createTextRange()");
	Copied.execCommand("Copy");
}



