/* This function is used to change the style class of an element */
function swapClass(obj, newStyle) {
    obj.className = newStyle;
}

function isUndefined(value) {   
    var undef;   
    return value == undef; 
}

function checkAll(theForm) { // check all the checkboxes in the list
  for (var i=0;i<theForm.elements.length;i++) {
    var e = theForm.elements[i];
		var eName = e.name;
    	if (eName != 'allbox' && 
            (e.type.indexOf("checkbox") == 0)) {
        	e.checked = theForm.allbox.checked;		
		}
	} 
}
function checkPostalCode(postalcode)
{
		postalcode = postalcode.value
		var alphanum=/^[a-zA-Z0-9 /-]+$/; //This contains A to Z , 0 to 9 and a to z valid punctuation is a space or hyphen.
		if(postalcode.match(alphanum)){
			return true;
		}
		return false;
}

/*Funstion for time validation */

function validatetime(strval)
 {
    if(strval==""){
		return true;
	}

  //lenght must be 5. example 12:25
  if(strval.length < 5)
  {
   alert("Invalid time. Time format should be HH:MM");
   return false;
  }
        
  var pos1 = strval.indexOf(':');
  if(pos1 < 0 )
  {
   alert("Invalid time. A colon(:) is missing between hour and minute.");
   return false;
  }
  else if(pos1 != 2 )
  {
   alert("Invalid time. Time format should be HH:MM.");
   return false;
  }
  
  //Checking hours
  var horval =  strval.substring(0,pos1);
  if(!IsNumericTime(horval))
  {
   alert("Invalid time. Hour should contain only integer value (0-23).");
   return false;
  }
      
  if(horval > 23)
  {
   alert("Invalid time. Hour can not be greater that 23.");
   return false;
  }
  else if(horval < 0)
  {
   alert("Invalid time. Hour can not be hours less than 0.");
   return false;
  }
  //Completes checking hours.
  
  //Checking minutes.
  var minval =  strval.substring(pos1+1,pos1 + 3);
  
  if(!IsNumericTime(minval))
  {
   alert("Invalid time. Minute should have only integer value (0-59).");
   return false;
  }
    
  if(minval > 59)
  {
     alert("Invalid time. Minute can not be more than 59.");
     return false;
  }   
  else if(minval < 0)
  {
   alert("Invalid time. Minute can not be less than 0.");
   return false;
  }
   
  return true;
  
  
 }

 function IsNumericTime(strString) 
{ 
    var strValidChars = "0123456789"; 
    var strChar; 
    var blnResult = true; 
    //test strString consists of valid characters listed above 
    if (strString.length == 0) 
        return false; 
    for (i = 0; i < strString.length && blnResult == true; i++) 
    { 
        strChar = strString.charAt(i); 
        if (strValidChars.indexOf(strChar) == -1) 
        { 
            blnResult = false; 
        } 
     } 
return blnResult; 
}



/*  Added by Payal Patel on 26 April ,2006
	Added on: 26/04/07
	Description:Function to enabled disabled Form elements in div
	paramater : id Id of the Div
				flag true or false[To enable or disable Form element]
*/
function enableDisableComponents(id, flag){
	var obj = document.getElementById(id); 
    
    var elements=obj.getElementsByTagName("input");  
	for(e = 0; e < elements.length ; e++)	{
		if(flag){
			if(elements[e].type=="text") {
				elements[e].value="";
			}else if(elements[e].type=="radio") {
				elements[e].checked=false;
			}else if(elements[e].type=="checkbox") {
				elements[e].checked=false;
				
			}
		}
		if(elements[e].type=="checkbox") {
			elements[e].disabled=flag;
        }
        if(elements[e].type=="radio") {
			elements[e].disabled=flag;
        }
		elements[e].readOnly=flag;
	}
	elements=obj.getElementsByTagName("select"); 
     
	for(e = 0; e < elements.length ; e++){
		if(flag){
			if(elements[e].type=="select-one") {
				elements[e].selectedIndex=0;
			}else if(elements[e].type=="select-multiple"){
				elements[e].selectedIndex=-1;
			}
		}
		//elements[e].readonly=flag;
		if(flag){
			freezeList(elements[e]);
		 }
		 else {
			defreezeList(elements[e]);
		 }
	}
	var elements=obj.getElementsByTagName("textarea");  
	for(e = 0; e < elements.length ; e++){
	    if(flag){
			elements[e].value="";
         } 
		 elements[e].readOnly=flag;
	}	
 }

function freezeList(whichList){

	var chosen=whichList.options.selectedIndex;
	whichList.onchange=function(){
		whichList.options.selectedIndex=chosen;
	}
	whichList.style.color="#999999";
}

function defreezeList(whichList){

	var chosen=whichList.options.selectedIndex;
	whichList.onchange=null;
	whichList.style.color="";
}

/* Function to clear a form of all it's values */
function clearForm(frmObj) {
	for (var i = 0; i < frmObj.length; i++) {
        var element = frmObj.elements[i];
		if(element.type.indexOf("text") == 0 || 
				element.type.indexOf("password") == 0) {
					element.value="";
		} else if (element.type.indexOf("radio") == 0) {
			element.checked=false;
		} else if (element.type.indexOf("checkbox") == 0) {
			element.checked = false;
		} else if (element.type.indexOf("select") == 0) {
			for(var j = 0; j < element.length ; j++) {
				element.options[j].selected=false;
			}
            element.options[0].selected=true;
		}
	} 
}

/* Function to get a form's values in a string */
function getFormAsString(frmObj) {
    var query = "";
	for (var i = 0; i < frmObj.length; i++) {
        var element = frmObj.elements[i];
        if (element.type.indexOf("checkbox") == 0 || 
            element.type.indexOf("radio") == 0) { 
            if (element.checked) {
                query += element.name + '=' + escape(element.value) + "&";
            }
		} else if (element.type.indexOf("select") == 0) {
			for (var j = 0; j < element.length ; j++) {
				if (element.options[j].selected) {
                    query += element.name + '=' + escape(element.value) + "&";
                }
			}
        } else {
            query += element.name + '=' 
                  + escape(element.value) + "&"; 
        }
    } 
    return query;
}

/* Function to hide form elements that show through
   the search form when it is visible */
function toggleForm(frmObj, iState) // 1 visible, 0 hidden 
{
	for(var i = 0; i < frmObj.length; i++) {
		if (frmObj.elements[i].type.indexOf("select") == 0 || frmObj.elements[i].type.indexOf("checkbox") == 0) {
            frmObj.elements[i].style.visibility = iState ? "visible" : "hidden";
		}
	} 
}

/* Helper function for re-ordering options in a select */
function opt(txt,val,sel) {
    this.txt=txt;
    this.val=val;
    this.sel=sel;
}

/* Function for re-ordering <option>'s in a <select> */
function move(list,to) {     
    var total=list.options.length;
    index = list.selectedIndex;
    if (index == -1) return false;
    if (to == +1 && index == total-1) return false;
    if (to == -1 && index == 0) return false;
    to = index+to;
    var opts = new Array();
    for (i=0; i<total; i++) {
        opts[i]=new opt(list.options[i].text,list.options[i].value,list.options[i].selected);
    }
    tempOpt = opts[to];
    opts[to] = opts[index];
    opts[index] = tempOpt
    list.options.length=0; // clear
    
    for (i=0;i<opts.length;i++) {
        list.options[i] = new Option(opts[i].txt,opts[i].val);
        list.options[i].selected = opts[i].sel;
    }
    
    list.focus();
} 

/*  This function is to select all options in a multi-valued <select> */
function selectAll(elementId) {
    var element = document.getElementById(elementId);
	len = element.length;
	if (len != 0) {
		for (i = 0; i < len; i++) {
			element.options[i].selected = true;
		}
	}
}

/* This function is used to select a checkbox by passing
 * in the checkbox id
 */
function toggleChoice(elementId) {
    var element = document.getElementById(elementId);
    if (element.checked) {
        element.checked = false;
    } else {
        element.checked = true;
    }
}

/* This function is used to select a radio button by passing
 * in the radio button id and index you want to select
 */
function toggleRadio(elementId, index) {
    var element = document.getElementsByName(elementId)[index];
    element.checked = true;
}

/* This function is used to open a pop-up window */
function openWindow(url, winTitle, winParams) {
	winName = window.open(url, winTitle, winParams);
    winName.focus();
}


/* This function is to open search results in a pop-up window */
function openSearch(url, winTitle) {
    var screenWidth = parseInt(screen.availWidth);
    var screenHeight = parseInt(screen.availHeight);

    var winParams = "width=" + screenWidth + ",height=" + screenHeight;
        winParams += ",left=0,top=0,toolbar,scrollbars,resizable,status=yes";

    openWindow(url, winTitle, winParams);
}

/* This function is used to set cookies */
function setCookie(name,value,expires,path,domain,secure) {
  document.cookie = name + "=" + escape (value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
}

/* This function is used to get cookies */
function getCookie(name) {
	var prefix = name + "=" 
	var start = document.cookie.indexOf(prefix) 

	if (start==-1) {
		return null;
	}
	
	var end = document.cookie.indexOf(";", start+prefix.length) 
	if (end==-1) {
		end=document.cookie.length;
	}

	var value=document.cookie.substring(start+prefix.length, end) 
	return unescape(value);
}

/* This function is used to delete cookies */
function deleteCookie(name,path,domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

// This function is for stripping leading and trailing spaces
function trim(str) { 
    if (str != null) {
        var i; 
        for (i=0; i<str.length; i++) {
            if (str.charAt(i)!=" ") {
                str=str.substring(i,str.length); 
                break;
            } 
        } 
    
        for (i=str.length-1; i>=0; i--) {
            if (str.charAt(i)!=" ") {
                str=str.substring(0,i+1); 
                break;
            } 
        } 
        
        if (str.charAt(0)==" ") {
            return ""; 
        } else {
            return str; 
        }
    }
} 

// This function is used by the login screen to validate user/pass
// are entered. 
function validateRequired(form) {                                    
    var bValid = true;
    var focusField = null;
    var i = 0;                                                                                          
    var fields = new Array();                                                                           
    oRequired = new required();                                                                         
                                                                                                        
    for (x in oRequired) {                                                                              
        if ((form[oRequired[x][0]].type == 'text' || form[oRequired[x][0]].type == 'textarea' || form[oRequired[x][0]].type == 'select-one' || form[oRequired[x][0]].type == 'radio' || form[oRequired[x][0]].type == 'password') && form[oRequired[x][0]].value == '') {
           if (i == 0)
              focusField = form[oRequired[x][0]]; 
              
           fields[i++] = oRequired[x][1];
            
           bValid = false;                                                                             
        }                                                                                               
    }                                                                                                   
                                                                                                       
    if (fields.length > 0) {
       focusField.focus();
       alert(fields.join('\n'));                                                                      
    }                                                                                                   
                                                                                                       
    return bValid;                                                                                      
}

// This function is a generic function to create form elements
function createFormElement(element, type, name, id, value, parent) {
    var e = document.createElement(element);
    e.setAttribute("name", name);
    e.setAttribute("type", type);
    e.setAttribute("id", id);
    e.setAttribute("value", value);
    parent.appendChild(e);
}

function confirmDelete(obj) {   
    var msg = "Are you sure you want to delete this " + obj + "?";
    ans = confirm(msg);
    if (ans) {
        return true;
    } else {
        return false;
    }
}

function confirmDeselect(obj) {   
    var msg = obj;
    ans = confirm(msg);
    if (ans) {
        return true;
    } else {
        return false;
    }
}

function highlightTableRows(tableId) {
    var previousClass = null;
    var table = document.getElementById(tableId); 
    var tbody = table.getElementsByTagName("tbody")[0];
    var rows;
    if (tbody == null) {
        rows = table.getElementsByTagName("tr");
    } else {
        rows = tbody.getElementsByTagName("tr");
    }
    // add event handlers so rows light up and are clickable
    for (i=0; i < rows.length; i++) {
        rows[i].onmouseover = function() { previousClass=this.className;this.className+=' over' };
        rows[i].onmouseout = function() { this.className=previousClass };
        rows[i].onclick = function() {
            var cell = this.getElementsByTagName("td")[0];
            var link = cell.getElementsByTagName("a")[0];
            location.href = link.getAttribute("href");
            this.style.cursor="wait";
        }
    }
}

function highlightFormElements() {
    // add input box highlighting
    addFocusHandlers(document.getElementsByTagName("input"));
    addFocusHandlers(document.getElementsByTagName("textarea"));
}

function addFocusHandlers(elements) {
    for (i=0; i < elements.length; i++) {
        if (elements[i].type != "button" && elements[i].type != "submit" &&
            elements[i].type != "reset" && elements[i].type != "checkbox" && elements[i].type != "radio") {
            if (!elements[i].getAttribute('readonly') && !elements[i].getAttribute('disabled')) {
                elements[i].onfocus=function() {this.style.backgroundColor='#ffd';};//this.select() commentd to slove issue While switiching between windows,the text field gets selected
                elements[i].onmouseover=function() {this.style.backgroundColor='#ffd'};
                elements[i].onblur=function() {this.style.backgroundColor='';}
                elements[i].onmouseout=function() {this.style.backgroundColor='';}
            }
        }
    }
}

function radio(clicked){
    var form = clicked.form;
    var checkboxes = form.elements[clicked.name];
    if (!clicked.checked || !checkboxes.length) {
        clicked.parentNode.parentNode.className="";
        return false;
    }

    for (i=0; i<checkboxes.length; i++) {
        if (checkboxes[i] != clicked) {
            checkboxes[i].checked=false;
            checkboxes[i].parentNode.parentNode.className="";
        }
    }

    // highlight the row    
    clicked.parentNode.parentNode.className="over";
}
/* Commented out by Neil 5/9/08
window.onload = function() {
    highlightFormElements();
    if ($('successMessages')) {
        new Effect.Highlight('successMessages');
        // causes webtest exception on OS X : http://lists.canoo.com/pipermail/webtest/2006q1/005214.html
        // window.setTimeout("Effect.DropOut('successMessages')", 3000);
    }
    if ($('errorMessages')) {
        new Effect.Highlight('errorMessages');
    }
}
*/
// Show the document's title on the status bar
window.defaultStatus=document.title;

function checkTextareaMaxLength(obj) {
	var currentLength = obj.value.length;
	if (currentLength >10000) {
		return false;
	}
	return true;
}

function checkWholeNumber(val){
	var tmp=new String(val); 
	
	var index = tmp.indexOf('.');
  	if(index!=-1) {
	  return false;
	} else {
	  return true;
	}
} 

function checkCurrencyValue(val)
{  
	var tmp=new String(val);  
	var index = tmp.indexOf('.');
	if (index > 12){
		return false; 
	}else if (index ==-1){
		if(tmp.length>12){
			return false;
		}else{
			return true;
		}
	}else{
		if((tmp.length - (index+1))>2){
			return false;
		}else{
			return true;
		}
	}
} 

function checkPercentage(val)
{  
	var tmp=new String(val);  
	var index = tmp.indexOf('.');
	if (index > 3){
		return false; 
	}else if (index ==-1){
		if(tmp.length>3){
			return false;
		}else{
			return true;
		}
	}else{
		if((tmp.length - (index+1))>2){
			return false;
		}else{
			return true;
		}
	}
} 

var buttonClicked = false;
function callNoticeFormSubmission(){
	if(!buttonClicked){
		document.forms.noticeFormName.submit();
		buttonClicked = true;
	}
}

//Add by Abhijit For checking only number not allow + sign
function IsNumeric(strString) 
{ 	
	var strValidChars = "0123456789."; 
    var strChar; 
    var blnResult = true;
    var dotCtr=0;
    //test strString consists of valid characters listed above 
    if (strString.length == 0) 
        return false; 
    for (i = 0; i < strString.length && blnResult == true; i++){ 
        strChar = strString.charAt(i); 
        if (strValidChars.indexOf(strChar) == -1){ 
            blnResult = false; 
            break;
        }
        if(strChar == '.'){
	        dotCtr++;
        }
        if(dotCtr > 1){
            blnResult = false; 
            break;
        }
     } 
	return blnResult; 
}
function clearRadioSelection(radioGroup){ 
 var theControl = document.getElementsByName(radioGroup);
    for (i = 0; i < theControl.length; i++) {
        theControl[i].checked = false;
    }
} 

// Methods for setting child notices

function addAddendum(){
	document.forms.noticeFormName.addChildNotice.value = "AdditionalInformationNotice";
}

function addPriorInformationNotice(){
	document.forms.noticeFormName.addChildNotice.value = "PriorInformationNotice";
}

function addContractNotice(){
	document.forms.noticeFormName.addChildNotice.value = "ContractNotice";
}

function addContractAwardNotice(){
	document.forms.noticeFormName.addChildNotice.value = "ContractAwardNotice";
}

function addPeriodicIndicativeNoticeUtilities(){
	document.forms.noticeFormName.addChildNotice.value = "PeriodicIndicativeNoticeUtilities";
}

function addContractNoticeUtilities(){
	document.forms.noticeFormName.addChildNotice.value = "ContractNoticeUtilities";
}

function addContractAwardNoticeUtilities(){
	document.forms.noticeFormName.addChildNotice.value = "ContractAwardNoticeUtilities";
}

function addQualificationSystemUtilities(){
	document.forms.noticeFormName.addChildNotice.value = "QualificationSystemUtilities";
}

function addBuyerProfileNotice(){
	document.forms.noticeFormName.addChildNotice.value = "BuyerProfileNotice";
}

function addSimplifiedContractNotice(){
	document.forms.noticeFormName.addChildNotice.value = "SimplifiedContractNotice";
}

function addPublicWorksConcession(){
	document.forms.noticeFormName.addChildNotice.value = "PublicWorksConcession";
}

function addContractNoticeConcessionaire(){
	document.forms.noticeFormName.addChildNotice.value = "ContractNoticeConcessionaire";
}

function addDesignContestNotice(){
	document.forms.noticeFormName.addChildNotice.value = "DesignContestNotice";
}

function addResultsOfDesignContest(){
	document.forms.noticeFormName.addChildNotice.value = "ResultsOfDesignContest";
}

function submitNotice(url){
	//Function to make parent/child form links as submit so that if notice is not published, 
	//the validate state is maintained
	var submitForm = document.createElement("FORM");
	document.body.appendChild(submitForm);
	submitForm.method = "POST";
	submitForm.action= url;
	submitForm.submit();
}
