function validatePrompt (Ctrl, PromptStr)
{
	alert (PromptStr)
	Ctrl.focus();
	return;
}

function ToSubmit(form)
{

	em = form.email;
	if (em.value==null || em.value == "" || em.value.indexOf ('@', 0) == -1)
	{
		validatePrompt (form.email, "Please enter a valid email address.")
		return (false);
	} else if (em.value.length >50 )
	{
		validatePrompt (form.email, "Email should be <= 50 chars.")
		return (false);
	}

	emTo = form.mailto;
	if (emTo.value==null || emTo.value == "" || emTo.value.indexOf ('@', 0) == -1)
	{
		validatePrompt (form.email, "Please enter a valid email address.")
		return (false);
	} else if (emTo.value.length >50 )
	{
		validatePrompt (form.mailto, "Email should be <= 50 chars.")
		return (false);
	}

	nm = form.name;
	if (nm.value==null || nm.value == "")
	{ validatePrompt (form.name, "Please enter your name.")
		return (false);
	} else{ }

	return true;

}


function toPrint(article, type)
{
	window.open('/faqPrint/'+type +'/' + article, 'printWindow', 'resizable=yes, scrollbars=yes, menubar=yes, status=yes');
}

// wows
var xmlHttp

function GetXmlHttpObject()
{ 
  var objXMLHttp=null;

  if (window.XMLHttpRequest)
  {
	objXMLHttp=new XMLHttpRequest();
  }
	else if (window.ActiveXObject)
  {
	objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  return objXMLHttp;
}

function cool(id)
{
  var url;
  xmlHttp=GetXmlHttpObject();
  if (xmlHttp==null)
  {
	alert ("Browser does not support HTTP Request");
	return;
  } 

  url="/PROCESSWOW?cat=v";

  if (id!="")
  {
	  url = url + "&id=" + id;
  }


  //url = url + new Date().getTime();
  xmlHttp.onreadystatechange=function() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	{ 
		document.getElementById(id).innerHTML="<strong id=\"diggs-strong-0\">" + xmlHttp.responseText + "</strong> likes";
		document.getElementById("v"+id).innerHTML="like it";
	} 
  }
  
  xmlHttp.open("GET",url,true);
  xmlHttp.send(null);
} 

function ToSubmitWow()
{

    wow = document.getElementById("wow");
    if (wow.value=="")
    {
            alert("Please enter wow.")
            return false;
    } 

    author = document.getElementById("author");
    if (author.value=="" )
    { 
            alert("Please enter the author.")
            return false;
    } 

    form = document.getElementById("addwow");
    category = form.category;
    var btn = validateRaidoButton(category);
    if (btn == null) {
            alert("please select the most appropriate category.")
            return false;
    }
    return true;
}

function validateRaidoButton(btn) {
    var cnt = -1;
    for (var i=btn.length-1; i > -1; i--) {
        if (btn[i].checked) {
			cnt = i; i = -1;
		}
    }
    if (cnt > -1) return btn[cnt].value;
    else return null;
}

function toggleMenu(currMenu){
    var listElementStyle=document.getElementById(currMenu).style;

    if (listElementStyle.display=="none")
    {
            listElementStyle.display="block";
    } else {
            listElementStyle.display="none";
    }
}

function clikker(a,b,c)
{
	//var source;
	//source = window.event.srcElement;
	if (a.style.display =="")
	{
		a.style.display = "none";
		b.src="/images/rarrow.gif";
		b.alt="Expand";
		c.value = 0
	}
	else
	{
		a.style.display="";
		b.src="/images/darrow.gif";
		b.alt="Collapse";
		c.value = 1
	}
}

//login
function getnewimage() {
	document.getElementById('securitycheck').src = "/jcaptcha?timestamp=" + new Date().getTime();
	//document.getElementById('securitycheck').src = "/images/Butterfly.gif";
}

function validatePrompt (Ctrl, PromptStr)
{
	alert (PromptStr)
	Ctrl.focus();
	return;
}


function ToSubmit(form)
{
	var un;
	un = form.username;
	if (un.value==null || un.value.length < 4 || un.value.length >15 )
	{
		validatePrompt (form.username, "Username is not valid.")
		return false;
	} 
	pw1 = form.password;
	if (pw1.value==null || pw1.value.length ==0)
	{
		validatePrompt (form.password, "Please Enter you password.")
		return false;
	} 
	
	pw2 = form.j_captcha_response;
	if (pw2.value==null || pw2.value.length==0) {
		validatePrompt (form.j_captcha_response, "Please Enter security check field.")
		return false;
	}

	//image validate here
	url="/PROCESSLOGIN?";
	valueString = "j_captcha_response="+pw2.value+"&username="+un.value+"&password="+pw1.value;
	notSubmitForm(form,url, valueString); 

	return false;

}



function $() {
    var elements = new Array();

    for (var i = 0; i < arguments.length; i++) {
        var element = arguments[i];

        if (typeof element == 'string')
            element = document.getElementById(element);

        if (arguments.length == 1)
            return element;

        elements.push(element);
    }

    return elements;
}

var _ms_XMLHttpRequest_ActiveX = ""; // Holds type of ActiveX to instantiate
// self = this; creates a pointer to the current function
// the pointer will be used to create a "closure". A closure
// allows a subordinate function to contain an object reference to the
// calling function. We can't just use "this" because in our anonymous
// function later, "this" will refer to the object that calls the function 
// during runtime, not the AJAXRequest function that is declaring the function
function AJAXRequest( method, url, data, process, async, dosend) 
{
    var self = this;

    // check the dom to see if this is IE or not
    if (window.XMLHttpRequest) {
	// Not IE
        self.AJAX = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
	// Hello IE!
        // Instantiate the latest MS ActiveX Objects
        if (_ms_XMLHttpRequest_ActiveX) {
            self.AJAX = new ActiveXObject(_ms_XMLHttpRequest_ActiveX);
        } else {
	    // loops through the various versions of XMLHTTP to ensure we're using the latest
	    var versions = ["Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
                        "Microsoft.XMLHTTP"];

            for (var i = 0; i < versions.length ; i++) {
                try {
					// try to create the object
					// if it doesn't work, we'll try again
					// if it does work, we'll save a reference to the proper one to speed up future instantiations
                    self.AJAX = new ActiveXObject(versions[i]);

                    if (self.AJAX) {
                        _ms_XMLHttpRequest_ActiveX = versions[i];
                        break;
                    }
                }
                catch (objException) {
                // trap; try next one
                } ;
            }

            ;
        }
    }
    
    // if no callback process is specified, then assing a default which executes the code returned by the server
    if (typeof process == 'undefined' || process == null) {
        process = executeReturn;
    }

    self.process = process;

    // create an anonymous function to log state changes
    self.AJAX.onreadystatechange = function() {
        //alert("AJAXRequest Handler: State =  " + self.AJAX.readyState);
        self.process(self.AJAX);
    }

    // if no method specified, then default to POST
    if (!method) {
        method = "POST";
    }

    method = method.toUpperCase();

    if (typeof async == 'undefined' || async == null) {
        async = true;
    }

	//alert("AJAX Request: " + ((async) ? "Async" : "Sync") + " " + method + ": URL: " + url + ", Data: " + data);
    self.AJAX.open(method, url, async);

    if (method == "POST") {
        self.AJAX.setRequestHeader("Connection", "close");
        self.AJAX.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        self.AJAX.setRequestHeader("Method", "POST " + url + "HTTP/1.1");
    }

    // if dosend is true or undefined, send the request
    // only fails is dosend is false
    // you'd do this to set special request headers
    if ( dosend || typeof dosend == 'undefined' ) {
	    if ( !data ) data=""; 
	    self.AJAX.send(data);
    }

    return self.AJAX;

}

function validateImage(url, valueString, process ) {
    // process is an optional parameter
    // 
   var functionToCall = null;

	if (typeof process == 'function') {
		functionToCall = process;
	} else {
		functionToCall = executeReturn; // generic function will execute what is returned
	}

	new AJAXRequest('POST', url, valueString, functionToCall);
}

var wrongSecurityCodeHtml = "<table cellSpacing=0 cellPadding=1 border=1 width='100%' bordercolor=red><tr><td><font color=red>Typed wrong security check code. please try it again</font></td></tr></table>";
var wrongLoginHtml = "<table cellSpacing=0 cellPadding=1 border=1 width='100%' bordercolor=red><tr><td><font color=red>The user id or password is incorrect, please try again</font></td></tr></table>";
var serverBusyHtml = "<table cellSpacing=0 cellPadding=1 border=1 width='100%' bordercolor=red><tr><td><font color=red>The server is busy right now, please try again later</font></td></tr></table>";

function notSubmitForm(form, url, valueString, process ) {
	validateImage(url, valueString, function( AJAX ) {
		if (AJAX.readyState == 4) {
			if (AJAX.status == 200) {
				if (AJAX.responseText=="0"){
					form.submit();
				} else if (AJAX.responseText=="-1"){
					var error_div = $('error');
					error_div.style.visibility = 'visible';
					error_div.innerHTML = wrongLoginHtml;
					reload();
				} else if (AJAX.responseText=="-2"){
					var error_div = $('error');
					error_div.style.visibility = 'visible';
					error_div.innerHTML = wrongSecurityCodeHtml;
					reload();
				} else {
					var error_div = $('error');
					error_div.style.visibility = 'visible';
					error_div.innerHTML = serverBusyHtml;
					reload();
				}
			} else {
				var error_div = $('error');
					error_div.style.visibility = 'visible';
					error_div.innerHTML = serverBusyHtml;
					reload();
			}
		}
	});

}
/* question.js */
function CheckNumeric()
{
   var key = window.event.keyCode;
   //alert(key);
   if ( key > 46 && key < 58 )
      return; // if so, do nothing
   else
      window.event.returnValue = null;
}

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 fillInText(ind, ddAnswerText, ddAnswer, choices)
{
	str = document.getElementsByName(ddAnswerText+(ind))[0].value;
	if(str=='' || str == null )
	{
		document.getElementById(ddAnswer+(ind)).value = '';
		return;
	} else if (!IsNumeric(str) )
	{
		return;
	}


	itemno = (document.getElementsByName(ddAnswerText+(ind))[0].value)/1;
	document.getElementById(ddAnswer+(ind)).value = itemno;

	itemno = itemno - 1;
	if(document.getElementById(choices+itemno))
	{
		itemval = document.getElementById(choices+itemno).value;
		document.getElementsByName(ddAnswerText+(ind))[0].value = itemval;
	}
	else document.getElementsByName(ddAnswerText+(ind))[0].value = '';
}

function  beforeSubmit(command, examType, eSample, numSample, eMember, numMember, inputGoto, commandC, finish)
{
	var numberOfQuestions;
	var index;
	if ( examType == eSample )
	{
		numberOfQuestions = numSample
	} else if ( examType == eMember )
	{
		numberOfQuestions = numMember
	}

	if(command == "Goto")
	{
	   if(document.getElementById("gotoQ").value == '' || !IsNumeric(document.getElementById("gotoQ").value))
	  {
		alert("Please enter a valid value for Goto instead of : "+document.getElementById("gotoQ").value);
		return;
	  }

	  if ( document.getElementById("gotoQ").value > numberOfQuestions
		  || document.getElementById("gotoQ").value <1 )
	  {
		alert("Please enter a valid value ( from 1 to " + numberOfQuestions + " ) for Goto instead of : "+document.getElementById("gotoQ").value);
		return;
	  }
	  index = document.getElementById("gotoQ").value;
	  document.getElementById(inputGoto).value = index;
  
	} 
	
	if (command == "Next")
	{
		var nextQ = document.getElementById("curQuestionNum").value;
		if ( nextQ < numberOfQuestions )
		{
			index = parseInt(document.getElementById("curQuestionNum").value) + 1;
			document.getElementById(inputGoto).value= index;

		} 
		else 
		{
			alert("This is the last question");
			return;
		}
	} 
	
	if (command == "Previous")
	{
		if ( document.getElementById("curQuestionNum").value > 1)
		{
			index = parseInt(document.getElementById('curQuestionNum').value) - 1;
			document.getElementById(inputGoto).value = index;
		} else 
		{
			alert("This is the first question");
			return;
		}
	}

	if (command == "Finish")
	{
		document.getElementById(commandC).value = finish;
	}

	document.getElementById("gotoForm").action="/servlet/ExamServlet?action=gotoQuestion&QID=" + index;

	document.getElementById("gotoForm").submit();
}

var popupheading = '';
var popupmessage = '';

function forComment(questionId, userId)
{
	window.open('/jsp/scdjwsfeedback.jsp?SCDJWSQID='+questionId+'&userId='+userId, 'FeedbackWindow', 'width=600, height=550, resizable=yes, scrollbars=yes, menubar=yes, status=yes');
}

//registration
var xmlHttp
var username

function GetXmlHttpObject()
{ 
  var objXMLHttp=null;

  if (window.XMLHttpRequest)
  {
	objXMLHttp=new XMLHttpRequest();
  }
	else if (window.ActiveXObject)
  {
	objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  return objXMLHttp;
}

function showdata(str)
{
  if (str=="")
  {
	  return;
  }

  username=str
  xmlHttp=GetXmlHttpObject();
  if (xmlHttp==null)
  {
	alert ("Browser does not support HTTP Request");
	return;
  } 

  var url="/CHECKUSERNAME";
  url=url+"?uname="+str+"&timestamp=" + new Date().getTime();
  xmlHttp.onreadystatechange=stateChanged;
  xmlHttp.open("GET",url,true);
  xmlHttp.send(null);
} 

function stateChanged() 
{ 
  if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
  { 
    eval("strFunc(xmlHttp.responseText)");
  } 
} 

/*
* output the html message
*/
function strFunc(strIn) {
	var message;
	if (strIn == "0")
	{
		message = "<font size=-2 color=green>Great, the username \"" + username + "\" is available.</font>"
	} else if ( strIn == "1")
	{
		message = "<font size=-2 color=red>Sorry, the username \"" +username+ "\" is taken.</font>"
	} else 
	{
		message = "<font size=-2>The system is busy, please try again later.</font>"
	}

	document.getElementById("usernamestatus").innerHTML=message;
}

function setcheckbutton() {
	if (document.getElementById("username").value.length > 3)
	{
		document.getElementById("username_check").disabled=false;
	}
	
}

function validatePrompt (Ctrl, PromptStr)
{
	alert (PromptStr)
	Ctrl.focus();
	return;
}
function ToSubmitRegister(form)
{

	em = form.email;
	if (em.value==null || em.value == "" || em.value.indexOf ('@', 0) == -1)
	{
		validatePrompt (form.email, "Please Enter a valid email address.")
		return (false);
	} else if (em.value.length >50 )
	{
		validatePrompt (form.email, "Email should be <= 50 chars.")
		return (false);
	}

	un = form.username;
	if (un.value==null || un.value.length < 4 || un.value.length >15 )
	{ validatePrompt (form.username, "Name should be at least 4 characters and no more than 15 characters.")
		return (false);
	} else{ }

	fn = form.firstname;
	if (fn.value==null)
	{ validatePrompt (form.realname, "please enter your first name with no more than 15 characters.")
		return (false);
	} else{ }

	pw1 = form.password;
	if (pw1.value==null || pw1.value.length < 6)
	{
		validatePrompt (form.password, "Password should be at least 6 letters.")
		return (false);
	} else{ }

	pw2 = form.password1;
	if (pw2.value==null) {
		validatePrompt (form.password1, "Please Re enter your password.")
		return (false);
	}

	if (pw1.value != pw2.value) {
		validatePrompt (form.password1, "You did not enter the same new password twice.")
		return (false);
	} else { }

	pj = form.j_captcha_response;
	if (pj.value == null || pj.value.length==0) {
		validatePrompt (form.j_captcha_response, "Please enter characters in the picture.")
		return (false);
	}

	return true;

}


function reload() {
	document.getElementById('securitycheck').src = "/jcaptcha?timestamp=" + new Date().getTime();
}


