/* <SCRIPT  LANGUAGE="JavaScript" SRC="./general.js"></SCRIPT> */

// A list of important functions.

/* The below function is used on the blur event of a textbox which is next to a checkbox. */
function IsNumeric(sText)
{
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
   }

function Checkme(txtfld, opt)
{
    var ans = txtfld.value.trim();
    if (ans != "")
        { opt.checked = true; }
}

//==========================================================================================//
/*
The below function will return the selected value in a radio object.
*/
function radioValue(radioObj)
{
    var radval = "";
    for ( i=0; i<radioObj.length; i++)
    {
        if (radioObj[i].checked)
        {
            radval = radioObj[i].value;
            break;
        }
    }
    return radval;
}

//==========================================================================================//
/*
The below function will check to make sure that the given zipcode is valid
Validations:
    1. It is a number (Won't be applicable for Canadians.
    2. Length is five characters.
    3. All five characters are digits.
    (*Won't need a regex if pincodes fall between 10000 and 99999*)
*/
function chkZipcode(zipcodeObj)
{
    if (!zipcodeObj.value.match(/^\d\d\d\d\d$/))
    {
        alert("The zipcode is invalid");
        zipcodeObj.focus();
        zipcodeObj.select();
        return false;
    }
    return true;
}

//==========================================================================================//
/*
This function will check the length of the value in txtFld and if it is more than noOfChar
it will display an alert and return false. Else, it will return true.
*/
function checkTxtLength(txtFld, optionText, questionText, noOfChar)
{
    // Do you want to trim Q2Specified_1 field???
    if (txtFld.value.length > noOfChar)
    {
       alert("Your "
                + ((optionText == "") ? "" : "'" + optionText + "'") // -> Option text.
                + " response for the question '"
                + questionText // -> Question of the option.
                + "' on this page exceeds the permissible limit of "
                + noOfChar // -> Number of characters.
                + " characters");
       return false;
    }
    return true;
}

//==========================================================================================//
/*
The setOnClick() will take a radio button group and a codestring. It will then proceed to change all the onclick functions
to the current codestring.
Eg: setOnClick(document.Survey.Q2, "document.Survey.Q2Specified_1.value=''");
Make sure that all objects specified come from document.formname.object
*/
function setOnClick(rad, codestring)
{
    var myOnClick = new Function(codestring);
    for(var itm=0; itm < rad.length; itm++ )
    {
        rad[itm].onclick = myOnClick;
    }
}

// remove leading and trailing spaces
function strtrim()
{
    return this.replace(/^\s+/,'').replace(/\s+$/,'');
}

// The following statement will enable calling the strtrim function from the string itself.
// stringObject.trim(); will return a trimmed version of stringObject.
String.prototype.trim = strtrim;


/* Still doesn't work*/
function setTableBands(obj)
{
//  alert("[" + document.all + "]");
    for (var i=0; i < obj.rows.length; i++)
    {
        obj.rows[i].bgcolor = "#CCCCCC";
    }
}

//Prototyped functions in Object doesn't trickle down to the HTML Elements in IE.
//Object.prototype.setTableBands = setTableBands;
function NewWindow(url, title, w, h, scroll, resize)
    {
        if (scroll==true || scroll=='yes')
            scroll='yes'; else scroll='no';
        if (resize==true || resize=='yes')
            resize=', resizable'; else resize='';
        var winl = (screen.width - w) / 2;
        var wint = (screen.height - h) / 2;
        winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+resize
        win = window.open(url, title, winprops)
    }

function checkEmailAddress(field) {
var trim_Qemail=Trim(field.value);
var goodEmail = field.value.match(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);
if (field.value.length <= 50)
  {
    if(trim_Qemail=='')
                {return true;}
    else
    {
        if (goodEmail)
        {
           return true;
        }
        else
        {
           alert('Please enter a valid e-mail address.')
           field.focus()
           field.select()
           return false;
           }
      }
    }
    else
        {
            alert('The length of your email address is limited to 50 characters.');
            return false;
        }
}



// remove leading and trailing spaces
function Trim(s)
    {
        var trimmed="";
        var leading = true;
        var trailing = true;

        // strip leading spaces
        for(var i = 0; i < s.length; i++)
        {
            var c = s.charAt(i);
            if (c == ' ')
            {
                if (leading==false)
                {
                    trimmed=trimmed+c;
                }
            }
            else
            {
                leading=false;
                trimmed=trimmed+c;
            }
        }

        // strip trailing spaces
        for (var i = trimmed.length-1; i>0; i--)
        {
            var c = trimmed.charAt(i);
            if (c != " ")
            {
                return trimmed;
            }
            else
            {
                trimmed=trimmed.substr(0,trimmed.length-1);
            }
        }

        return trimmed;
    }

//check adjacent option when click on textbox
function CheckAdjacent(obj)
    {
        obj.checked = true;
    }


// check the length of textbox or textarea
    function checkLength(element,maxvalue)
    {

        var q = Trim(eval("document.Survey."+element+".value"));
         if (q.length > maxvalue)
         {
          return false;
         }
         else
         {
          return true;
         }
    }

// questions with radio buttons are made compulsory
function RadioCheck(que,lastno)
    {
        var qno;
        var flag = false;
        for (i=0; i<=lastno ; i++)
        {
            qno = eval("document.Survey." + que + "[" + i + "].checked")
            if (qno != "undefined")
            {
                if ( qno == true)
                { flag = true}
            }
        }
        return flag;
    }

// questions with check boxes are made compulsory

function CheckBoxCheck(que,lastno)
    {
        var flag = false;
        var obj;
        for (i=1; i<=lastno ; i++)
        {
            obj = eval("document.Survey." + que + "_" + i)
            if (obj)
                {
                if ( obj.checked == true)
                    { flag = true}
                }
        }
        return flag;
    }


// questions with drop down boxes are made compulsory
function DDBCheck(que)
    {
        var qno;
        var flag = false;
        qno = eval("document.Survey." + que + ".selectedIndex")

        if ( qno != 0)
        { flag = true}
        return flag;

    }

// deselect oteh options if one options is clicked - in case of checkboxes
function DeSelectOthers(que,lastno)
    {
        var cnt
        var i;

        for(i=1;i<=lastno;i++)
        {
//          cnt = eval("document.Survey." + que + "_" + 25 )
//          alert(cnt);
            cnt = eval("document.Survey." + que + "_" + i );
            if (cnt)
            {
//              alert(cnt.checked)
                cnt.checked = false;
            }
        }
    }

// questions with textarea are made compulsory
function TextCheck(que)
    {
        var qno;
        var flag = false;
        qno = Trim(eval("document.Survey." + que + ".value"))
        if ( qno == "")
        {
            flag = false
        }
        else
        {
            flag = true
        }

        return flag;
    }
////////////////////////////////////////////////////////////////////////////////////////////////////////
// Only 3 options are allowed to be selected
//Call this function on click event of each checkbox as ThreeSelections(qno,lastindex,<This>)
function ThreeSelections(qno,lastindex,obj)
    {
        var i = 1
        var qtitle
        var counter = 0
        while (i<=lastindex)
        {
            qtitle = eval('document.Survey.' + qno  +  '_'  +  i );
            if (qtitle)
            {

                if (qtitle.checked)
                {
                    if (counter < 3)
                    {
                        counter = counter + 1
                    }
                    else
                    {
                        obj.checked=false;
                        obj.focus();
                        alert('Please select no more than 3 factors.')
                        
                    /*  else
                        {
                            alert('Please select no more than 3 items in the first column.')
                        } */
                        break;
                    }
                }
            }
            i = i + 1
            if (counter > 3)
            {
                return false;
            }
        }
        return true;
    }


// Call this function in function Resubmit as flag="Only3Selections(qno,lastindex,obj)"
//function Only3Selections(qno,lastindex,obj)
function Only3Selections(qno,lastindex)
    {
        var i = 1
        var qtitle
        var counter = 0
        while (i<=lastindex)
        {
            qtitle = eval('document.Survey.' + qno  +  '_'  +  i)
            if (qtitle)
            {
                if (qtitle.checked)
                    counter = counter + 1
            }
            i = i + 1
            if (counter > 3)
            {
                alert ('Please select no more than 3 options.');
                return false;
            }
        }
        return true;
    }
/// Selects only two
function Only2Selections(qno,lastindex)
    {
        var i = 1
        var qtitle
        var counter = 0
        while (i<=lastindex)
        {
            qtitle = eval('document.Survey.' + qno  +  '_'  +  i)
            if (qtitle)
            {
                if (qtitle.checked)
                {
 
                        counter = counter + 1
               }
            }
            i = i + 1
            if (counter > 2)
            {
                alert ('Please select no more than 2 responses.');
                return false;
            }
        }
        return true;
    }
function TwoSelections(qno,lastindex,obj)
    {
        var i = 1
        var qtitle
        var counter = 0
        while (i<=lastindex)
        {
            qtitle = eval('document.Survey.' + qno  +  '_'  +  i)
            if (qtitle)
            {
                if (qtitle.checked)
                {
                    if (counter < 2)
                    {
                        counter = counter + 1

                    }
                    else
                    {
                        obj.checked=false;
                        obj.focus();
                        alert('Please select no more than 2 sources.')
                        break;
                    }
                }
            }
            i = i + 1
            if (counter > 2)
            {
                return false;
            }
        }
        return true;
    }
////////////////////////////////////////////////////////////////////////////////////////////////////////
// checks whether the email address written in the textbox is a valid email address or not
/* function isValidEmail(e)
    {
        var trim_Qemail=Trim(e);
        if (e.length <= 50)
        {
            if(trim_Qemail=="")
            {return true;}
            else
            {
                var alnum="a-zA-Z0-9";
                exp="^[^@\\s]+@(["+alnum+"+\\-]+\\.)+["+alnum+"]["+alnum+"]["+alnum+"]?$";
                emailregexp = new RegExp(exp);
                result = e.match(emailregexp);
                if (result != null)
                {
                  return true;
                }
                else
                {
                  alert("Invalid email address");
                  return false;
                }
            }
        }
        else
        {
            alert("The length of your email address is limited to 50 characters.");
            return false;
        }
    }
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////
// checks whether the email address written in the textbox is a valid email address or not

 function isValidEmail(e)
    {
        var trim_Qemail=Trim(e);
        if (e.length <= 500)
        {
            if(trim_Qemail=="")
            {return true;}
            else
            {
                var alnum="a-zA-Z0-9";
                exp="^[^@\\s]+@(["+alnum+"+\\-]+\\.)+["+alnum+"]["+alnum+"]["+alnum+"]?$";
                emailregexp = new RegExp(exp);
                result = e.match(emailregexp);
                if (result != null)
                {
                  return true;
                }
                else
                {
                  alert("Invalid email address");
                  return false;
                }
            }
        }
        else
        {
            alert("The length of your email address is limited to 500 characters.");
            return false;
        }
    }

function AssociatedText(txtname, optname)
{
var optOnClick = new Function('document.Survey.' + txtname + ".value=''");
eval('document.Survey.' + optname + '.onclick=' + optOnClick);
if (navigator.appName == "Netscape" && navigator.appVersion == "4.7 [en] (WinNT; I)")
    {
    document.write("<font face='Verdana, Arial, Helvetica, sans-serif' size='3'>"
                                    + "<INPUT TYPE='Text' NAME='" + txtname
                                    + "' onFocus='" + optname + ".checked=true;"
                                    + "' onBlur='Checkme(this, " + optname + ")'></font>");
    }
else
    {
    document.write("<font face='Verdana, Arial, Helvetica, sans-serif' size='3'>"
                                    + "<INPUT TYPE='Text' NAME='"
                                    + txtname + "' onKeyDown='JavaScript:"
                                    + " if ((event.keyCode >= 41 && event.keyCode <= 44) || (event.keyCode >= 47 && event.keyCode <= 90)"
                                            + " || (event.keyCode >= 96 && event.keyCode <= 111) || (event.keyCode >= 124 && event.keyCode <= 143)"
                                            + " || (event.keyCode == 187 || event.keyCode == 189"
                                                    + " || event.keyCode == 192 || event.keyCode == 94 || event.keyCode == 32)"
                                            + ") {"
                                    + optname + ".checked=true;}' onBlur='Checkme(this, " + optname + ")'></font>");
    }
}

function RAssociatedText(txtname, optname)
{

if (navigator.appName == "Netscape" && navigator.appVersion == "4.7 [en] (WinNT; I)")
    {
    document.write("<font face='Verdana, Arial, Helvetica, sans-serif' size='3'>"
                                    + "<INPUT TYPE='Text' NAME='" + txtname
                                    + "' onFocus='" + optname + ".checked=true;"
                                    + "' onBlur='Checkme(this, " + optname + ")'></font>");
    }
else
    {
    document.write("<font face='Verdana, Arial, Helvetica, sans-serif' size='3'>"
                                    + "<INPUT TYPE='Text' NAME='"
                                    + txtname + "' onKeyDown='JavaScript:"
                                    + " if ((event.keyCode >= 41 && event.keyCode <= 44) || (event.keyCode >= 47 && event.keyCode <= 90)"
                                            + " || (event.keyCode >= 96 && event.keyCode <= 111) || (event.keyCode >= 124 && event.keyCode <= 143)"
                                            + " || (event.keyCode == 187 || event.keyCode == 189"
                                                    + " || event.keyCode == 192 || event.keyCode == 94 || event.keyCode == 32)"
                                            + ") {"
                                    + optname + ".checked=true;}' onBlur='Checkme(this, " + optname + ")'></font>");
    }
}


// use to open the chart window
function open_win(what_link,the_x,the_y,toolbar,addressbar,directories,statusbar,menubar,scrollbar,resize,history,pos,wname)
 { 
 var the_url = what_link;
 the_x -= 0;
 the_y -= 0;
 var how_wide = screen.availWidth;
 var how_high = screen.availHeight;
 if(toolbar == "0"){var the_toolbar = "no";}else{var the_toolbar = "yes";}
 if(addressbar == "0"){var the_addressbar = "no";}else{var the_addressbar = "yes";}
 if(directories == "0"){var the_directories = "no";}else{var the_directories = "yes";}
 if(statusbar == "0"){var the_statusbar = "no";}else{var the_statusbar = "yes";}
 if(menubar == "0"){var the_menubar = "no";}else{var the_menubar = "yes";}
 if(scrollbar == "0"){var the_scrollbars = "no";}else{var the_scrollbars = "yes";}
 if(resize == "0"){var the_do_resize =  "no";}else{var the_do_resize = "yes";}
 if(history == "0"){var the_copy_history = "no";}else{var the_copy_history = "yes";}
 if(pos == 1){top_pos=0;left_pos=0;}
 if(pos == 2){top_pos = 0;left_pos = (how_wide/2) -  (the_x/2);}
 if(pos == 3){top_pos = 0;left_pos = how_wide - the_x;}
 if(pos == 4){top_pos = (how_high/2) -  (the_y/2);left_pos = 0;}
 if(pos == 5){top_pos = (how_high/2) -  (the_y/2);left_pos = (how_wide/2) -  (the_x/2);}
 if(pos == 6){top_pos = (how_high/2) -  (the_y/2);left_pos = how_wide - the_x;}
 if(pos == 7){top_pos = how_high - the_y;left_pos = 0;}
 if(pos == 8){top_pos = how_high - the_y;left_pos = (how_wide/2) -  (the_x/2);}
 if(pos == 9){top_pos = how_high - the_y;left_pos = how_wide - the_x;}
 if (window.outerWidth )
  {
  var option = "toolbar="+the_toolbar+",location="+the_addressbar+",directories="+the_directories+",status="+the_statusbar+",menubar="+the_menubar+",scrollbars="+the_scrollbars+",resizable="+the_do_resize+",outerWidth="+the_x+",outerHeight="+the_y+",copyhistory="+the_copy_history+",left="+left_pos+",top="+top_pos;
  wname=window.open(the_url, wname, option);
  wname.focus();
  }
 else
  {
  var option = "toolbar="+the_toolbar+",location="+the_addressbar+",directories="+the_directories+",status="+the_statusbar+",menubar="+the_menubar+",scrollbars="+the_scrollbars+",resizable="+the_do_resize+",Width="+the_x+",Height="+the_y+",copyhistory="+the_copy_history+",left="+left_pos+",top="+top_pos;
  if (!wname.closed && wname.location){
  wname.location.href=the_url;
  }
 else
  {
  wname=window.open(the_url, wname, option);
  //wname.resizeTo(the_x,the_y);
  wname.focus();
  wname.location.href=the_url;
  }
}
}

function fdebug()
	{ 
	if(!document.forms.length) return;
	if(!document.forms[0].elements.length) return;
	
	//Calling function to create table and set attributes to the table
		CreateDebugTable()
	
	var strhidvar=""; //To keep the track of all hidden variable
	var els= document.forms[0].elements;

	//scroll through all elements of form
	for(var i=els.length-1; i >=0; i--)
	{	
		if(els[i].type == 'hidden')
				 strhidvar=strhidvar+els[i].name+" = "+els[i].value+" ;  ";
		else
		{
			//Insert a row to the table, 'tid' is id of DebugTable
			var tblRow=tid.insertRow(1);

			//Insert three coloumns to the currently inserted row
			var tblcol1=tblRow.insertCell(0);
			var tblcol2=tblRow.insertCell(1);
			var tblcol3=tblRow.insertCell(2);
			
			if(els[i].type == 'radio')
					if(els[i].name.indexOf("_")==-1)
					{
						tblRow.bgColor="#ffffee";
						tblcol1.innerHTML=els[i].type;
						tblcol2.innerHTML=els[i].name;
						tblcol3.innerHTML=els[i].value;
					}
					else
					{
						tblRow.bgColor="#ffffcc";
						tblcol1.innerHTML=els[i].type+"Grid";
						tblcol2.innerHTML=els[i].name;
						tblcol3.innerHTML=els[i].value;
					}	 
			else if(els[i].type == 'checkbox')
					if(els[i].name.indexOf("_")!=els[i].name.lastIndexOf("_"))
					{
						if (els[i].value==1)
							tblRow.bgColor="#boe7c6";
						else
							tblRow.bgColor="#ff5555";//red color 
						
						tblcol1.innerHTML=els[i].type+"Grid";
						tblcol2.innerHTML=els[i].name;
						tblcol3.innerHTML=els[i].value;
					}
					else
					{
						 if (els[i].value==1)
							tblRow.bgColor="#ddffc6";
						else
							tblRow.bgColor="#ff5555";//red color 	
						 tblcol1.innerHTML=els[i].type;
						 tblcol2.innerHTML=els[i].name;
						 tblcol3.innerHTML=els[i].value;
					}
			else if (els[i].type == 'select-one')
				{
						 tblRow.bgColor="#eeffff";
						 tblcol1.innerHTML="Combo"
						 tblcol2.innerHTML=els[i].name;
						 var strOpt="";
						 for(j=1;j<els[i].length;j++) 
						 if(j%5)
								strOpt=strOpt+els[i].item(j).value+",";
						else
								strOpt=strOpt+els[i].item(j).value+"<BR>";
						 tblcol3.innerHTML=strOpt;
				}
			else // All other elements
			{
						tblcol1.innerHTML=els[i].type;
						tblcol2.innerHTML=els[i].name;
						tblcol3.innerHTML=els[i].value;
			}
		
		}
		
	}
	var mybody=document.getElementsByTagName("body").item(0);
	currenttext=document.createTextNode(strhidvar);
	myFont=document.createElement("FONT");	
	myFont.setAttribute("color","darkRed");
	myFont.setAttribute("size","3");
	myFont.appendChild(currenttext);
	mybody.appendChild(myFont);

	var obj = document.getElementsByTagName("body").item(0);
	var obj1 = document.getElementById("mydivId");
	obj.onmousemove = moveme;
	obj.onmouseup = moveme;
	obj1.onmousedown = moveme;
	
	if (obj.captureEvents)
		obj.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP | Event.MOUSEDOWN);
	if (obj1.captureEvents)
		obj1.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP | Event.MOUSEDOWN);
	
	}
//	function to create table and set attributes to the table	
	function CreateDebugTable() {
		var mybody=document.getElementsByTagName("body").item(0);
        mytable = document.createElement("TABLE");
        mytablebody = document.createElement("TBODY");
        mycurrent_row=document.createElement("TR");
        
                mycurrent_cell=document.createElement("TD");
                currenttext=document.createTextNode("TYPE");
                mycurrent_cell.appendChild(currenttext);
                mycurrent_row.appendChild(mycurrent_cell);
                
                mycurrent_cell=document.createElement("TD");
                currenttext=document.createTextNode("NAME");
                mycurrent_cell.appendChild(currenttext);
                mycurrent_row.appendChild(mycurrent_cell);
                
                mycurrent_cell=document.createElement("TD");
                currenttext=document.createTextNode("VALUE");
                mycurrent_cell.appendChild(currenttext);
                mycurrent_row.appendChild(mycurrent_cell);
           
           mytablebody.appendChild(mycurrent_row);
       
        mytable.appendChild(mytablebody);
        mytable.setAttribute("style","position:absolute; top:0px");
        mytable.setAttribute("id","tid");
        mytable.setAttribute("border","1");
		mydiv=document.createElement("DIV");
        mydiv.style.position ="absolute";
        mydiv.style.top = "0px";
		mydiv.style.left = "800px";
		mydiv.id="mydivId";
	    mydiv.style.background = "white";
        mydiv.appendChild(mytable);
        mybody.appendChild(mydiv);
     }

	 function moveme(e){
	if (!e) e = window.event;
	var obj = document.getElementById("mydivId");
	if(e.type == 'mousedown') 
		document.draggable = 1;
	if ((e.type == 'mousemove')&&(document.draggable == 1))
		{
		obj.style.top = event.y
		obj.style.left = event.x
		}
	if(e.type == 'mouseup')
		document.draggable = 0;
	return true;
}
