
function getValue(formName, fieldName) {
	
	var el = document.forms[formName].elements[fieldName];
	if (el) {
		return el.value;
	}
	
	return "";
}

function setFocusTo(formName, fieldName) {

	var el = document.forms[formName].elements[fieldName];
	if (el) {
		return el.focus();
	}

}

var dateRegexp = /^(0[1-9]|1[012])\/(3[01]|0[1-9]|[12]\d)\/(\d{4})$/;

function parseDate (dateStr) {

	// Parse in mm/dd/yyyy format
	// month: 0 followed by 1-9 or 1 followed by 0, 1, 2
	// day: 3 followed by 0 or 1, 0 followed by 1-9, or 1,2 followed by any digit
	// year: 4 digits
	if (dateRegexp.test (dateStr) == true) {
		dateArray = dateRegexp.exec (dateStr);
		return dateArray;
	} else {
		return null;
	}
}

// checks whether given date is a proper date
function validateDate (day, month, year) {
    if (month < 1 || month > 12 || day < 1 || day > 31 || year < 0) {
        return false;
    }
    if (day==31 && (month==4 || month==6 || month==9 || month==11)) {
        return false;
    }
    if (month==2) {
        if ((year%4==0) && (year%100!=0 || year%400==0)) {
            if (day>29) {
                return false;
            }
        } else {
            if (day>28) {
                return false;
            }
        }
    }
    return true;
}

// Returns true if earlierDate is earlier than 'laterDate'
function compareDates (earlierDate, laterDate) {

	if (earlierDate != null && laterDate != null) {

		var arr1 = parseDate (earlierDate);
		var arr2 = parseDate (laterDate);
		if (arr1 == null || arr2 == null) {
			return false;
		}

		var y1 = arr1 [3];
		var y2 = arr2 [3];

		if (y1 > y2) {
			// Year 1 is greater than Year 2
			// alert ('later date');
			return false;
		} else if (y1 == y2) {
			// Year is the same; Compare months.
			var m1 = arr1 [1];
			var m2 = arr2 [1];
			if (m1 > m2) {
				// alert ('month');
				return false;
			} else if (m1 == m2) {
				// Months are the same; compare dates
				var d1 = arr1 [2];
				var d2 = arr2 [2];
				if (d1 > d2) {
					// alert ('day');
					return false;
				} else {
					return true;
				}
			} else {
				return true;
			}
		} else {
			return true;
		}
	}
}

function validateDateStr (dateVal) {

	if (dateVal.length == 0) {
		return false;
	}

	if (dateVal.length > 0) {
		var datesArray = parseDate (dateVal);
		if (datesArray == null) {
			return false;
		} else {
			return validateDate (datesArray[2], datesArray[1], datesArray[3]);
		}
	} else {
		return false;
	}

	return true;
}

var jcErrEmailNotEntered = "Please enter the email address.";
var jcErrBlankSpaceInEmailAddr = "Sorry, blank spaces is not allowed in the email address.";
var jcErrAtSignMissingInEmailAddr = "Sorry, the email address is invalid. Please make sure that the '@' sign is present.";
var jcErrInvalidEmailAddr = "Sorry, the email address is invalid. Please verify it.";
var jcErrInvalidCharInEmailAddr = "Sorry, the email address contains invalid characters. Please verify it.";

var jcInvalidEmailChars = "\"|&;<>!*\\";

function validateEmailField (formName, emailField) {

	var emailValue;
		emailValue = document.forms[formName].elements[emailField].value;

	if (emailValue.length == 0) {
		alert (jcErrEmailNotEntered);
		setFocusTo (formName, emailField);
		return false;
	}

	if (!validateAsciiData (emailValue)) {
		alert (jcErrInvalidCharInEmailAddr);
		setFocusTo (formName, emailField);
		return false;
	}

	var invalidChars = jcInvalidEmailChars;
	// alert (invalidChars);
	for (var i = 0; i < invalidChars.length; i++) {
		if (emailValue.indexOf (invalidChars.charAt(i)) != -1) {
			alert (jcErrInvalidCharInEmailAddr);
			setFocusTo (formName, emailField);
			return false;
		}
	}

	if (emailValue.indexOf ("@") == -1) {
		alert (jcErrAtSignMissingInEmailAddr);
		setFocusTo (formName, emailField);
		return false;
	}

	if (emailValue.indexOf (" ") != -1) {
		alert (jcErrBlankSpaceInEmailAddr);
		setFocusTo (formName, emailField);
		return false;
	}
	
	if (window.RegExp) {
		var reg1str = "(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)";
		var reg2str = "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$";

		var reg1 = new RegExp (reg1str);
		var reg2 = new RegExp (reg2str);

		if (reg1.test (emailValue) || !reg2.test (emailValue)) {
			alert (jcErrInvalidEmailAddr);
			setFocusTo (formName, emailField);
			return false;
		}
	}

	return true;
}
function validateAsciiData (testStr) {
	for (var i = 0; i < testStr.length; i++) {
		if ((testStr.charAt(i) < " ") || (testStr.charAt (i) > "~")) {
			return false;
		}
	}
	return true;
}

/**
 * checkAll - checks or unchecks a group of checkboxes with the specified name
 *
 * @param formName the name of the form
 * @param checkAllCheckbox the 'Select All' checkbox
 * @param checkboxName the common name for the set of checkboxes
 */
function checkAll (formName, checkAllCheckbox, checkboxName) {

   for (var i=0;i < document.forms[formName].elements.length;i++) {
      var e = document.forms[formName].elements[i];

      if (e.type == "checkbox") {
        if (checkboxName != null && e.name != checkboxName) {
            continue;
        }
          e.checked = checkAllCheckbox.checked;
      }
   }
}
/**
 * deleteCheckboxes - verifies that atleast ONE checkbox has been checked.
 *
 * The 'checkboxName' is used to match only the checkboxes belonging to
 * the specified group.
 *
 * @param formName the name of the form
 * @param confirmMsg the text displayed in the confirm alert
 * @param errMsg the text displayed in case of an error
 * @param checkboxName the name of the set of checkboxes
 */
function deleteCheckboxes (formName, confirmMsg, errMsg, checkboxName) {

     var flag = false;

     for(var i = 0 ; i < document.forms[formName].length ; i++) {
         var e = document.forms[formName].elements[i];
            if (e.type == "checkbox") {
                if (checkboxName != null && e.name != checkboxName) {
                    continue;
                }
                if (e.checked) {
                    flag = true;
                    break;
                }
            }
     }
    
     if (flag) {
		// show confirm only if specified
	 	if (confirmMsg == null) {
			return true;
		} else {
		  if(confirm (confirmMsg)) {
			 return true;
		  } else {
			 return false;
			}
		}
     } else {
        alert (errMsg);
        return false;
     }
}
function selectCheckboxes (formName , errMsg, checkboxName) {
     
     var flag = false;
     for(var i = 0 ; i < document.forms[formName].length ; i++) {
         var e = document.forms[formName].elements[i];
         if (e.type == "checkbox") {
            if (checkboxName != null && e.name != checkboxName) {
                   continue;
              }
            if (e.checked) {
           		 flag = true;
                  break;
            }
         }
     }
     if (!flag) {
		alert(errMsg);
		return false;
	}
    return true; 
}
function createWindow (url, name, x, y, w, h, props) {
	
	if (!x) { x = 100; }

	if (!y) { y = 100; }
	
	if (!w) { w = 650; }

	if (!h) { h = 500; }

	var properties = "toolbar=no,directories=no,resize=yes,resizable=yes,menubar=yes,location=no,scrollbars=yes,status=yes,";
	if (props != null) {
		properties = props;
	}
	properties += "screenX=" + x + ",screenY=" + y + ",";
	properties += "left=" + x + ",top=" + y + ",";
	properties += "width=" + w + ",height=" + h;

	/*
	if (document.all) {
		// append '/' only if not an absolute URL.
		if (url.indexOf ("https:") == -1 || url.indexOf ("http:") == -1) {
			url = "/" + url;
		}
	}
	*/

	myPopup = window.open(url, name, properties);
	if (!myPopup.opener) {
         myPopup.opener = self; 
    }
	if (window.focus) { myPopup.focus (); }
}

function showHideElement (id, show) {
	if (show) {
		showElement (id);
	} else {
		hideElement (id);
	}
}

function showElement (id) {
	var el = document.getElementById(id);
	if (el) {
		el.style.display = '';
	}
}

function hideElement (id) {
	var el = document.getElementById(id);
	if (el) {
		el.style.display = 'none';
	}
}
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

//returns the current width and height of the browser.
function getViewPort() {
	var vpw;
	var vph;

	if (typeof window.innerWidth != 'undefined'){
		vpw = window.innerWidth;
		vph = window.innerHeight;
	} else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined') {
		vpw = document.documentElement.clientWidth;
		vph = document.documentElement.clientHeight;
	} else {
		vpw = document.getElementsByTagName('body')[0].clientWidth;
		vph = document.getElementsByTagName('body')[0].clientHeight;
	}
	
	return {width: vpw, height: vph};
}

/**
 * Function to concat the dynamic values with the user messages. 
 * userMessage is the error message.
 * args is the dynamic variable name.
 */
function formatMessage(userMessage,args){
	if(args && args.length > 0) {
		for(var i=0; i<args.length; i++){
			//Regular Expression to match the pattern '{number}'
			var regStr = "\\{(\\s)*"+i+"(\\s)*\\}";
			var regExp = new RegExp (regStr,"g");
			userMessage = userMessage.replace(regExp, args[i]);
		}
	}
	
	if(userMessage && userMessage.length > 0) {
		return userMessage;
	}
}

/**
 * Method to show the message in the console.
 * @param msg message to be shown
 * @param obj value that is to be appended to the message
 * @return
 */
function showConsole(msg, obj){
	if(console){
		return console.log(msg+": "+obj);
	}
}

 /**
  * For example if the current URL is "...?opendocument&id=testid" then calling 
  * getURLParam("id") will return "testid".
  * @param strParamName
  * @return
  */
function getURLParam(strParamName){
	  var strReturn = "";
	  var strHref = window.location.href;
	  if ( strHref.indexOf("?") > -1 ){
	    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
	    var aQueryString = strQueryString.split("&");
	    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
	      if (aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
	        var aParam = aQueryString[iParam].split("=");
	        strReturn = aParam[1];
	        break;
	      }
	    }
	  }
	  return unescape(strReturn);
} 

//To create elements like "td, tr or div.."
function createHtmlElement(ele){
	if(ele != null && ele.length > 0){
			var ele = document.createElement(ele);
			return ele;
	}else{
		return "";
	}
}
