﻿
function isEmailAddr(str) {
  // res = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; 
  res = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,3}|\d+)$/;

  var re = new RegExp(res);
  return !(str.match(re) == null);
}

// Trim() , Ltrim() , RTrim() 
String.prototype.Trim = function() 
{ 
    return this.replace(/(^\s*)|(\s*$)/g, ""); 
} 

String.prototype.LTrim = function() 
{ 
    return this.replace(/(^\s*)/g, ""); 
} 

String.prototype.RTrim = function() 
{ 
    return this.replace(/(\s*$)/g, ""); 
} 


function isvalidrequired()
{
    var thisform = document.aspxform1;
    var str=thisform._required.value;
    var arr=str.split(',');
    
    for(var i=0;i<arr.length;i++)
    {
       var obj = document.getElementById(arr[i]);
       if(obj==null || obj.value==null || obj.value.Trim()==0)
       {
           alert("Please complete all required fields. ");
           obj.focus();          
           return false;
           break;
       }
        if(obj.name.toLowerCase().indexOf("email")>-1)
        {
            if(!isEmail(obj.value.Trim()))
            {
                alert("Please enter a valid email address. ");
                obj.focus();
                return false;
            }
        }
    }
    return true;
}


function getfiletype(str,type)
{
    if(str=="")
    {
        alert("You can not upload this type of file.");
        return false;
    }    
    if(str!=null && str.Trim().length!=0)
    {
        if(str.indexOf(".")>-1)
        {
            var have=false;
            var fileExtension=str.substring(str.indexOf(".")+1,str.Trim().length);
            var arr=type.split(",");
            for(var i=0;i<arr.length;i++)
            {
                if(arr[i].toLowerCase()==fileExtension.toLowerCase())
                {
                    have=true;
                    break;
                }
            }
            if(!have)
            {
                alert("You can not upload this type of file.");
                return false;
            }
        }
    }
    return true;
}

  function getElementsByNameA(name, formid) {
    var objArray, obj, objName;
    objArray = new Array();
    m = 0;
    if (formid != null && formid.length != 0 && document.forms[formid] != undefined && document.forms[formid] != null) {
      for (i = 0; i < document.forms[formid].elements.length; i++) {
        obj = document.forms[formid].elements[i];
        objName = obj.name.toLowerCase();
        if (objName.indexOf(name.toLowerCase()) >= 0) {
          objArray[m] = obj;
          m++;
        }
      }
    }
    else {
      for (i = 0; i < document.all.length; i++) {
        obj = document.all[i];
        objName = obj.name.toLowerCase();
        if (objName.indexOf(name.toLowerCase()) >= 0) {
          objArray[m] = obj;
          m++;
        }
      }
    }
    return objArray;
  }

  function getUploadFileField(formId) {
    var objList = getElementsByNameA("File", formId);
    if (objList != undefined && objList.length > 0) {
      return objList[0];
    }
    else return null;
  }

function validEmail(email) 
{
	invalidChars = " /:,;"
	if (email == "") {	// cannot be empty
	  //alert("Please enter your email address.");
	  return false
        }
	for (i=0; i<invalidChars.length; i++) 
	{	// does it contain any invalid characters?
		badChar = invalidChars.charAt(i)
		if (email.indexOf(badChar,0) > -1) 
		{
			return false
		}
  }
  atPos = email.indexOf("@",1)	// there must be one "@" symbol
  if (atPos == -1) 
  {
		return false
  }
  if (email.indexOf("@",atPos+1) != -1) 
  {	// and only one "@" symbol
		return false
  }
  periodPos = email.indexOf(".",atPos)
  if (periodPos == -1) 
  {			// and at least one "." after the "@"
		return false
  }
  if (periodPos+3 > email.length)	
  { // must be at least 2 characters after the "."
		return false
  }
  return true
}


//######### ValidateForm #########/////////////////////
//This function performs form validation for required fields. 
//The required fields are indicated by the hidden field "_required". 
//The value is a list of the field ids plus the question number, 
//separated by comma. Note that here we use field ids so that we can 
//group fields have the different names but the same ids, for example, 
//a group of checkboxes. 
function ValidateForm(thisform) {
if (thisform._required != null) {
	if (Trim(thisform._required.value).length != "") {
	var fieldnames = thisform._required.value.split(",");
	var errormsg = "The form can not be submitted. Please complete all required information.";
		for (m=0; m<fieldnames.length; m++) {
			fieldname = Trim(fieldnames[m]);
			if (thisform.elements[fieldname].length===undefined) {
				if (Trim(thisform.elements[fieldname].value).length=="") {
		   		alert(errormsg);
				thisform.elements[fieldname].focus();
				return false;
					}
				emailfield = fieldname.toLowerCase();
				if (emailfield.indexOf("email")>-1) {
					if (validEmail(Trim(thisform.elements[fieldname].value))==false) {
					alert("Please enter a valid email address.");
					thisform.elements[fieldname].focus();
					return false;
						}
					}
				}
			else {
				thischecked = -1
				for (i=0; i<thisform.elements[fieldname].length; i++) {
					if (thisform.elements[fieldname][i].checked || (thisform.elements[fieldname][i].selected && thisform.elements[fieldname][i].value.length!="")) {
					thischecked = i;
						}
					}
				if (thischecked == -1) {
					alert(errormsg);
					return false;
					thisform.elements[fieldname][0].focus;
					}
				
				}
			}
		}
	}
}

//######### ValidateForm #########/////////////////////

//Fuctions to mimmick LTrim,  RTrim, and Trim...
//==================================================================
//LTrim(string) : Returns a copy of a string without leading spaces.
//==================================================================
function LTrim(str)
/*
  PURPOSE: Remove leading blanks from our string.
  IN: str - the string we want to LTrim
*/
{
  var whitespace = new String(" \t\n\r");
  var s = new String(str);
  if (whitespace.indexOf(s.charAt(0)) != -1) 
  {
    // We have a string with leading blank(s)...
    var j=0, i = s.length;
    // Iterate from the far left of string until we
    // don't have any more whitespace...
    while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
        j++;
    // Get the substring from the first non-whitespace
    // character to the end of the string...
    s = s.substring(j, i);
	}
  return s;
}


//==================================================================
//RTrim(string) : Returns a copy of a string without trailing spaces.
//=================================================================//=
function RTrim(str)
/*
  PURPOSE: Remove trailing blanks from our string.
  IN: str - the string we want to RTrim
*/
{
  // We don't want to trip JUST spaces, but also tabs,
  // line feeds, etc.  Add anything else you want to
  // "trim" here in Whitespace
  var whitespace = new String(" \t\n\r");
  var s = new String(str);
  if (whitespace.indexOf(s.charAt(s.length-1)) != -1) 
  {
    // We have a string with trailing blank(s)...
    var i = s.length - 1;       // Get length of string
    // Iterate from the far right of string until we
    // don't have any more whitespace...
    while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
        i--;
    // Get the substring from the front of the string to
    // where the last non-whitespace character is...
    s = s.substring(0, i+1);
  }
  return s;
}


//=============================================================
//Trim(string) : Returns a copy of a string without leading or trailing spaces
//=============================================================
function Trim(str)
/*
  PURPOSE: Remove trailing and leading blanks from our string.
  IN: str - the string we want to Trim

  RETVAL: A Trimmed string!
*/
{
  return RTrim(LTrim(str));
}

function ShowAlert(thisform,controlID,msg)
{
    if(thisform.controlID.value.length==0)
    {
        alert(msg);
        thisform.elements[controlID].focus();
        return false;
    }
    return true;
}


///////////////////////////////////////ajax////////////

var Request = new Object();

Request.reqList = [];

function getAjax()
{
    var ajax=false;
    try
    {
     ajax = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
     {
      try
      {
      ajax = new ActiveXObject("Microsoft.XMLHTTP");
      }
     catch (E)
      {
      ajax = false;
      }
    }
    if (!ajax && typeof XMLHttpRequest!='undefined')
    {
     ajax = new XMLHttpRequest();
    }
    return ajax;
}

Request.send = function(url, method, callback, data, urlencoded, callback2)
 {
    var req=getAjax();  
    req.onreadystatechange = function()
    {
    if (req.readyState == 4)
    {
            if (req.status < 400)
            {
            if(callback)
                callback(req,data);
            }
            else
            {
                if (callback2)
                callback2(req,data);
            }
            
            try {
                delete req;
                req = null;
            } catch (e) {}
        }
    }
    if (method=="POST")
     {
        req.open("POST", url, true);
        if (urlencoded)
            req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');        
        req.send(data);
        Request.reqList.push(req);
    }
     else
    {
        req.open("GET", url, true);
        req.send(null);
        Request.reqList.push(req);
    }
    
    return req;
}

Request.clearReqList = function()
{
    var ln = Request.reqList.length;
    for (var i=0; i<ln; i++) {
        var req = Request.reqList[i];
        if (req)
        {
        try
        {
            delete req;
        } catch(e) {}
        }
    }
    Request.reqList = [];
}

Request.sendPOST = function(url, data, callback, clear, callback2)
{
    if (clear)
        Request.clearReqList();
    Request.send(url, "POST", callback, data, true, callback2);
}

Request.sendGET = function(url,args, callback,clear, callback2)
{
    if (clear)
        Request.clearReqList();
    return Request.send(url, "GET", callback, args, false, callback2);
}
////////////////////////////////ajax end//////////////////////////////////



function $(id)
{
    return document.getElementById(id);
}


function isEmail(thisform,htmlId,str) {
    str = str.toLowerCase();
    res = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,3}|\d+)$/;
    var re = new RegExp(res); 
    if(str.match(re) == null)
    {
	    alert("Please enter a valid email address.");
	    thisform.elements[htmlId].focus();
	    return false;
    }
    return true;
} 

function isPhone(thisform,htmlId,str)
{
    res=/^[0-9]*([-]*|[_]*)[0-9]+$/;
    var re = new RegExp(res); 
    if(str.match(re) == null)
    {
	    alert("Please enter valid phone number.");
	    thisform.elements[htmlId].focus();
	    return false;
    }
    return true;
} 

function ShowAlert(thisform,controlID,msg)
{
    if(thisform.elements[controlID].value.length==0)
    {
        alert(msg);
        thisform.elements[controlID].focus();
        return false;
    }
    return true;
}

function VerifyMultiEmails(email) 
{
	invalidChars = " /:,;"
	var multi=false;
	var tag=false;
	if (email == "") {
	  return false
        }
	for (i=0; i<invalidChars.length; i++) 
	{	
		var splitChar = invalidChars.charAt(i)
		if (email.indexOf(splitChar,0) > -1) 
		{   
		    multi=true;
		    var emails=email.split(splitChar);
		    for(var k=0;k<emails.length;k++)
		    {
		        if(!isEmailAddr(emails[k]))
		        {
		            tag=true;
		            return false;
		            break;
		        }
		    }
		    if(tag)
		        break;
		}
     }
     if(!multi)
     {
        if(!isEmailAddr(email))
        {
            return false;
        }
     }
     return true;
}


function AddOnChangeFun()
{
    var thisform=document.forms[0];
    for(var i=0;i<thisform.length;i++)
    {
        if(thisform[i].type.toLowerCase()=="file")
        {
            thisform[i].onchange=runFun;
            break;
        }
    }
}
