//().ready(function() {
// $("tr.result:nth-child(odd)").addClass("odd");
//});

function turnOffQuickTip(){
        document.getElementById("qt").value="0";
        document.getElementById("quicktipbox").style.display = "none";
} 

curtip = 1;
totaltips = 3;
function nextTip(){
	curtip = curtip+1;
	if(curtip>totaltips)
		curtip = 1;
	document.getElementById("tipmessage").innerHTML = document.getElementById("msg"+curtip).innerHTML;
}
function prevTip(){
	curtip = curtip-1;
	if(curtip==0)
		curtip = totaltips;
	document.getElementById("tipmessage").innerHTML = document.getElementById("msg"+curtip).innerHTML;
}

function showFrontPageDetail(id1, id2, id3){
	document.getElementById("pagedetail"+id1).style.display = "block";
	document.getElementById("pagedetail"+id2).style.display = "none";
	document.getElementById("pagedetail"+id3).style.display = "none";

	document.getElementById("pglink"+id1).style.backgroundColor="#C8E8FF";
	document.getElementById("pglink"+id2).style.backgroundColor="#FFF";
	document.getElementById("pglink"+id3).style.backgroundColor="#FFF";
}

function showFrontPageDetailI(id1, id2, id3){
	document.getElementById("iagedetail"+id1).style.display = "block";
	document.getElementById("iagedetail"+id2).style.display = "none";
	document.getElementById("iagedetail"+id3).style.display = "none";

	document.getElementById("iglink"+id1).style.backgroundColor="#FFE0C4";
	document.getElementById("iglink"+id2).style.backgroundColor="#FFF";
	document.getElementById("iglink"+id3).style.backgroundColor="#FFF";
}

function isUserNameAvailable(username){
	//username	= document.getElementById('email').value;
	istaken		= $.ajax({
			type:"GET",
			url:"/checkusername/",
			async:false,
			data: "username="+username}).responseText;
	if(istaken=="1")
		return false;
	else
		return true;
}

function checkUserName(elem){
	clearErrorMessage(elem+"_li");
	username	= document.getElementById(elem).value;
	//if(!isValidEmail(username)){
	//	return;
	//}	
	//if(username.length==0){
	//	document.getElementById('usernametakenvmsg').style.visibility="hidden";			
	//	return;
	//}
	$.get("/checkusername/",{username: username},
		function(istaken){
			var stristaken = ""+istaken;
			if(istaken=="1"){
				//document.getElementById('usernametakenvmsg').style.visibility="visible";			
				error_li = document.getElementById(elem+"_li");
				addErrorMessage(error_li, "This email/username is already taken. Please try something else or <a href=\"/recoverpass/\">Click here</a> to recover your password");
				//document.getElementById('usernametakenvmsg').style.display="block";			
				//document.getElementById('usernametakenvmsg').innerHTML = "<i>"+username+"</i> is already taken.Please try something else";			
			}else{
			//	document.getElementById('usernametakenvmsg').style.visibility="visible";			
			//	document.getElementById('usernametakenvmsg').innerHTML = "<i>"+username+"</i> is available!";			
			}
		}
	);
}

function isValidEmail(str){
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
									if (!filter.test(str)) {
		return false;
	}
	return true;
}

function errorMessage(error_li, mesg){
	error_li.attr("class", "error");
	error_li.append('<p class="error">'+mesg+'</p>');
}

function clearError(){
   	var parentLI 	= $(this).parents('LI').get(0);
	$(parentLI).attr("class", "highlighted");
	var childErrorP = $(parentLI).children(".error").get(0);
	if(childErrorP){
		$(childErrorP).remove();
	}	
}

function addErrorMessage(error_li, mesg){

	if(!($(error_li).attr("class") == "error")){
		error_li.setAttribute("class", "error");
		var error_mesg_p = document.createElement("p");
		error_mesg_p.setAttribute("class", "error");
		//var error_mesg	= document.createTextNode(mesg);
		//error_mesg_p.appendChild(error_mesg);
		error_mesg_p.innerHTML = mesg;
		error_li.appendChild(error_mesg_p);
	}
}

function clearErrorMessage(elem){
	var error_li = document.getElementById(elem);	
	if (error_li.hasAttribute("class")){
		//aval = error_li.getAttribute("class");
		error_li.setAttribute("class","highlighted");
	}

	var p_childs = error_li.getElementsByTagName("p");
	for (i=0; i<p_childs.length; i++){
		if (p_childs[i].hasAttribute("class")){
			aval = p_childs[i].getAttribute("class");
			if (aval=="error")
				error_li.removeChild(p_childs[i]);
		}
	}
}

function validateSignupNew(elem){
	//alert("validate");
	//elem  = ["name","email","username","password","repassword","state"];
	var haserror = false;
	var hassiteid = false;
	var siteid	= '';
	for(var i=0;i<elem.length;i++){
		val = document.getElementById(elem[i]).value;	
		if(val==""){
			error_li = document.getElementById(elem[i]+"_li");
			addErrorMessage(error_li, "This field is required. Please enter a value");
			haserror=true;
		}
	}

	email = document.getElementById("email").value;
	if(!isValidEmail(email)){
		//document.getElementById("emailvmsg").style.visibility="visible";
		haserror=true;
		error_li = document.getElementById("email_li");
		addErrorMessage(error_li, "Please enter a valid Email address");
		haserror=true;
	}
	
	//if everything looks good.. check the password
	if(!haserror){
		pass1	= document.getElementById('password').value;
		pass2	= document.getElementById('repassword').value;

		if(pass1!=pass2){
			document.getElementById('password').value = "";
			document.getElementById('repassword').value = "";
		
			error_li = document.getElementById("password_li");
			addErrorMessage(error_li, "The passwords do not match");
		}
	}

	//alert("here!");

	//if everything is great.. check if username is taken
	if(!isUserNameAvailable(email)){
		//document.getElementById('usernametakenvmsg').style.visibility="visible";			
		error_li = document.getElementById("email_li");
		addErrorMessage(error_li, "<i>"+username+"</i> is already taken.Please try something else or <a href=\"/recoverpass/\">Click here</a> to recover your password");
	
		return false;
	}

	if(haserror==true)
		return false;
	else
		return true;

}


function validateSignup(elem){
	//elem  = ["name","email","username","password","repassword","state"];
	var haserror = false;
	var hassiteid = false;
	var siteid	= '';
	for(var i=0;i<elem.length;i++){
		val = document.getElementById(elem[i]).value;	
		//document.getElementById(elem[i]+"vmsg").style.visibility="hidden";
		//document.getElementById(elem[i]+"vmsg").style.display="none";
		if(elem[i] == "siteid" && val!=""){
			hassiteid = true;
			siteid	= val;
		}	
		if(val==""){
			document.getElementById(elem[i]+"vmsg").style.visibility="visible";
			document.getElementById(elem[i]+"vmsg").style.display="block";
			/*error_li = document.getElementById(elem[i]+"_li");
			error_li.setAttribute("class", "error");
			

			var error_mesg_p = document.createElement("p");
			error_mesg_p.setAttribute("class", "error");
			var error_mesg	= document.createTextNode("This field is required. Please enter a value");

			error_mesg_p.appendChild(error_mesg);
			error_li.appendChild(error_mesg_p); */
			haserror=true;
		}
	}

	email = document.getElementById("email").value;
	if(!isValidEmail(email)){
		//document.getElementById("emailvmsg").style.visibility="visible";
		document.getElementById("emailvmsg").style.display="block";
		haserror=true;
	}else if(hassiteid){ //then check if the domain is valid
		$.ajax({
			type:"GET",
			url:"/validatesite/",
			data:"siteid="+siteid+"&email="+email,
			async:false,	
			success: function(validresults){
				var result 	= ""+validresults;
				var toks	= result.split('|');
				if(toks[0]=="0"){
					haserror=true;
					document.getElementById("myemail").innerHTML = email;
					document.getElementById("myinstitution").innerHTML = document.getElementById("institutionname").innerHTML;
					document.getElementById("hasdomain").style.display= "none";
					if (toks[1]!="nodomain"){
						document.getElementById("hasdomain").style.display= "block";
						document.getElementById("emailallowed").innerHTML = "...@"+toks[1];
						document.getElementById("emailallowed1").innerHTML = "...@"+toks[1];
					}
					overlayStuff('invalidemail');	
				}
				//alert(''+toks[0]);
			}
		  }
		);
	}
	
	//if everything looks good.. check the password
	if(!haserror){
		pass1	= document.getElementById('password').value;
		pass2	= document.getElementById('repassword').value;

		if(pass1!=pass2){
			document.getElementById('password').value = "";
			document.getElementById('repassword').value = "";
			//document.getElementById("repasswordvmsg").style.visibility="visible";
			document.getElementById("repasswordvmsg").style.display="block";
		}
	}

	//if everything is great.. check if username is taken
	username = document.getElementById("username").value;
	if(!isUserNameAvailable(username)){
		//document.getElementById('usernametakenvmsg').style.visibility="visible";			
		document.getElementById('usernametakenvmsg').style.display="block";			
		document.getElementById('usernametakenvmsg').innerHTML = "<i>"+username+"</i> is already taken. Please try something else or <a href=\"/recoverpass/\">Click here</a> to recover your password";			
		return false;
	}

	if(haserror==true)
		return false;
	else
		return true;

}

function overlayStuff(elementid) {
        el = document.getElementById(elementid);
        el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
        el.style.display = (el.style.display == "inline") ? "none" : "inline";
}

function findInstitution(byparam){

	value	= document.getElementById(byparam+'text').value;

	if(value==''){
		alert('Please Enter Name or Zip code to search');
		return;
	}

	//Search by JQuery AJAX!
	$.get("/findinstitution/",{byparam: byparam, value: value},
		function(instresults){
			parentnode	= document.getElementById("findinstsearchresults");
			while (parentnode.childNodes[0]) {
			    parentnode.removeChild(parentnode.childNodes[0]);
			}
				
			strdata = ""+instresults;	
			toks 	=  strdata.split("|");
			totalcnt = toks[0]
			sites = eval('(' + toks[1] + ')');
			totalsites = sites.length;
		
			if (totalsites>0){
				document.getElementById('showinginstresults').innerHTML = "Select your Instution from "+totalsites+" shown below of total "+totalcnt;

				for (var i=0;i<sites.length;i++){
					pardivrow	= document.createElement('div');
					pardivrow.style.fontSize	= "12px";
					pardivrow.style.paddingTop	= "2px";
					if (i%2==0){
						pardivrow.style.backgroundColor = "#E8FFDF";
					}
					checkinst = document.createElement('input');
					checkinst.setAttribute("type","radio");
					checkinst.setAttribute("name","site"+sites[i].id);
					checkinst.setAttribute("id","site"+sites[i].id);
					checkinst.setAttribute("onclick","selectInstitution('"+sites[i].id+"')");
					pardivrow.appendChild(checkinst);

					sitenamediv	= document.createElement('span')
					sitenamediv.setAttribute('id','sitenamediv'+sites[i].id);
					sitenametxt	= document.createTextNode(sites[i].sitename+","+sites[i].city+"-"+sites[i].state);
					sitenamediv.appendChild(sitenametxt);
					pardivrow.appendChild(sitenamediv);
					parentnode.appendChild(pardivrow);
				}
			}else{
				document.getElementById('showinginstresults').innerHTML = "No results found for "+value;
			}
		}
	);
}

function selectInstitution(siteid){
	document.getElementById('siteid').value = siteid; //set the value
	//document.getElementById('institutionname').innerHTML = document.getElementById('sitenamediv'+siteid).innerHTML;//copy the site name
	document.getElementById('instname').value = document.getElementById('sitenamediv'+siteid).innerHTML;//copy the site name
	//document.getElementById('findinst
	overlayStuff('findinstitutionoverlay');//close the window
}

/*function showPPInfo(pid){
	document.getElementById('imdisplay'+curSelPid).style.backgroundColor= "#FFF";
	document.getElementById('imdisplay'+pid).style.backgroundColor= "#D2ECFF";
	curSelPid = pid;
	document.getElementById('ifrmdetails').src = "/showppdetails/?pid="+pid;
}*/

function toggleIPTab(showtab,hidetab){
	$("#"+hidetab+'glink1').hide('slow');
	$("#"+hidetab+'glink2').hide('slow');
	$("#"+hidetab+'glink3').hide('slow');
	$("#"+showtab+'glink3').show('slow');
	$("#"+showtab+'glink2').show('slow');
	$("#"+showtab+'glink1').show('slow');
	
	document.getElementById(showtab+"agedetail1").style.display="block";
	document.getElementById(showtab+"agedetail2").style.display="none";
	document.getElementById(showtab+"agedetail3").style.display="none";
	
	document.getElementById(hidetab+"agedetail1").style.display="none";
	document.getElementById(hidetab+"agedetail2").style.display="none";
	document.getElementById(hidetab+"agedetail3").style.display="none";

	if(showtab=='p'){
		document.getElementById('parrow').src="/img/bhide.png";
		document.getElementById('iarrow').src="/img/show.png";
	}else{
		document.getElementById('parrow').src="/img/bshow.png";
		document.getElementById('iarrow').src="/img/hide.png";
	}
}


function checkIForm(){
	value	= document.getElementById("email").value;
	apos	= value.indexOf("@");
	dotpos	= value.lastIndexOf(".");
	if (apos<1||dotpos-apos<2) 
	{
		document.getElementById("email").style.borderWidth="3px";
		document.getElementById("email").style.borderColor="Red";
		document.getElementById("vmsg").style.visibility="visible";
		document.getElementById("email").focus();
		return false;
 	}
	  else {
	  	return true;
	}
}

function changeSendAs(mid){
	if($("input[name='sendas']:checked").val() == 'me'){
		window.location="/accounts/profile/?mymessages&show=drafts&mid="+mid+"&sas=m";
	}else{
		window.location="/accounts/profile/?mymessages&show=drafts&mid="+mid+"&sas=p";
	}
}

function reformulateQuery(){
    totalcond   = parseInt(document.getElementById('total_cond').value); 
    querystr    = '';
    for(var i=1;i<=totalcond;i++){
        if(document.getElementById('chkcond_'+i).checked){
            //alert('chekcd '+i);
            querystr += document.getElementById('cond_'+i).value+' and '; 
        }
    }
    querystr    = querystr.substring(0,querystr.length-5);
    if (querystr == ""){
           querystr = document.getElementById('cond_1').value;         
           document.getElementById('chkcond_1').checked = true;
    }
    document.getElementById('keyword').value = querystr; 
    //alert('query '+querystr);
    document.mfrmquery.submit();
}

var cur_showing = "";
function selectTab(tabname, desel1, desel2){
        //tb = document.getElementById(desel1);
        //tb.setAttribute("class","tab "+desel1+"def");
        //tb = document.getElementById(desel2);
        //tb.setAttribute("class","tab "+desel2+"def");
	//tb = document.getElementById(tabname);
        //tb.setAttribute("class","tab "+tabname+"select");
	if (tabname== "home"){
		window.location = "/tour";
	}
	if (tabname== "part"){
		window.location = "/";
	}
	if (tabname== "invest"){
		window.location = "/investigator";
	}

        }

function toggleMyTrialRecord(id){
	if(document.getElementById(id).style.display == "none")	{
		$("#"+id).show('slow');	
		document.getElementById(id+"text").innerHTML = "Hide";
		document.getElementById(id+"img").src="/img/hide.png";
	}else{
		$("#"+id).hide('slow');	
		document.getElementById(id+"text").innerHTML = "Show";
		document.getElementById(id+"img").src="/img/show.png";
	}
}

function sendMessage(show, mid){

	var totalmtostr = document.getElementById("totalmto").value;
	var totalmto    = parseInt(totalmtostr)
	tosend	= "";
	var uniq_tosend= new Array()
	
	for(var i=0;i<totalmto;i++){
		if(document.getElementById('mto'+i).checked==true){
			sendto = document.getElementById('hto'+i).value;
			if(!uniq_tosend[sendto]){
				tosend = tosend+"$"+sendto
			}else{
				uniq_tosend[sendto] = 1;			   }	
		}
	}

	if(tosend.length>0){
		tosend = tosend.substring(1);
		window.location="/accounts/profile/?mymessages&show="+show+"&mid="+mid+"&send="+tosend;
	}else{
		alert('Please select atleast one investigator to send the message');
	}
}

function selectUserTab(tabname, desel1, desel2, desel3){
        tb = document.getElementById(tabname);
        //tb.setAttribute("class","participanttabselect");
	if (tabname== "mydashboard"){
		window.location = "/accounts/profile";
	}
	if (tabname== "myaccount"){
		window.location = "/accounts/profile/?myaccount";
	}
	if (tabname== "mytrials"){
		window.location = "/accounts/profile/?mytrials";
	}
	if (tabname== "mymessages"){
		window.location = "/accounts/profile/?mymessages";
	}

        //tb = document.getElementById(desel1);
        //tb.setAttribute("class","participanttabdef");
        //tb = document.getElementById(desel2);
        //tb.setAttribute("class","participanttabdef");
}


function getCriteria(nct,type){
	$.get("/fetchcriteria", {id: nct, type: type},
		function(data){
			if(cur_showing!=""){
				hideCriteria(cur_showing);	
			}
			strdata = ""+data;
			jobj	= eval('('+strdata+')');
			if(jobj.length == 0){
				$("#titlediv"+nct+type).show("slow");	
				$("#contentdiv"+nct+type).show("slow");	
				parnode = document.getElementById("contentdiv"+nct+type);	
				ctext = document.createTextNode("No criteria found");	
				parnode.appendChild(ctext);
				cur_showing = "div"+nct+type;
				return;
			}
			arr = strdata.split(",");		
			titlenode = document.getElementById("titlediv"+nct+type);			
			parnode = document.getElementById("contentdiv"+nct+type);			

			$("#titlediv"+nct+type).show("slow");	
			$("#contentdiv"+nct+type).show("slow");	
			for(i=0;i<jobj.length;i++){
				cdiv = document.createElement('div');
				cdiv.style.fontFamily = "Arial,Verdana";
				cdiv.style.fontSize	= "12px";
				cdiv.style.paddingTop	= "2px";
				if (i%2==0){
					cdiv.style.backgroundColor = "#E8FFDF";
				}
				ctext = document.createTextNode(arr[i]);	
				cdiv.appendChild(ctext);	
				parnode.appendChild(cdiv);
			}
			cur_showing = "div"+nct+type;
		});

}

function hideCriteria(divId){
  $("#content"+divId).hide("slow");
  $("#title"+divId).hide("slow");
  parnode = document.getElementById("content"+divId);			
  if(parnode.hasChildNodes()){
	while(parnode.childNodes.length>=1){
		parnode.removeChild(parnode.firstChild);
	}
  } 
  cur_showing="";
}

function showElement(filter){
  delem = document.getElementById(filter);
  delem.style.display = "none";
  delem.style.visibilty = "hidden"; 
  //$("#"+filter).hide("fast");
  delem = document.getElementById("elem"+filter);
  delem.style.display = "inline";
  delem.style.visibilty = "visible";
  //$("#elem"+filter).show("show");
}

function filterQuery(filter){
	op = document.getElementById("s"+filter);
	if(op.value == "def" || op.value == "clear"){
		helem = document.getElementById(filter);
		helem.value = "";	
		document.mfrmquery.submit();
		return;
	}
	helem = document.getElementById(filter);
	helem.value = op.value;	
	document.mfrmquery.submit();
}

function removeFilter(filter){
   helem = document.getElementById(filter);
   helem.value = "";	
   document.mfrmquery.submit();
}

function showMoreHow(){
  $("#morehow").show("slow");
}

function importRecord() {
        el = document.getElementById("overlay");
 	$("tr.recordprompt:nth-child(odd)").addClass("odd");
        el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
}
function closeImportRecord() {
        el = document.getElementById("overlay");
        el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
}

function displayMatchScore(nctid, score){
	if(score<100){
		secondnum 	= Math.floor(score/10);
		thirdnum 	= score % 10;

		secondstart 	= Math.floor(Math.random()*10);
		if(secondnum == secondstart){
			secondstart = secondnum+1;
		}
		thirdstart 	= Math.floor(Math.random()*10);
		if(thirdstart 	== thirdnum){
			thirdstart = thirdnum+1;
		}	
	//	alert(thirdstart)
		setTimeout("runTicker('secondnum"+nctid+"',"+secondnum+", "+(secondstart)+")",100);
		setTimeout("runTicker('thirdnum"+nctid+"',"+thirdnum+", "+(thirdstart)+")",100);
		//alert("first num "+firstnum+" second num "+secondnum);			
	}else{
		secondnum 	= 0;
		thirdnum 	= 0;
		firststart 	= Math.floor(Math.random()*10);
		if(firststart==1){
			secondstart = secondnum+1;
		}
		secondstart 	= Math.floor(Math.random()*10);
		if(secondnum == secondstart){
			secondstart = secondnum+1;
		}
		thirdstart 	= Math.floor(Math.random()*10);
		if(thirdstart 	== thirdnum){
			thirdstart = thirdnum+1;
		}
		setTimeout("runTicker('firstnum"+nctid+"',1, "+firststart+")",100);
		setTimeout("runTicker('secondnum"+nctid+"',0, "+secondstart+")",100);
		setTimeout("runTicker('thirdnum"+nctid+"',0, "+thirdstart+")",100);
	}
}

function runTicker(id, targetnum, currentnum){
	numdiv	= document.getElementById(id);
	if(currentnum==10){
		currentnum = 0;
	}
	numdiv.innerHTML = ""+currentnum;
	if(currentnum!=targetnum){
		setTimeout("runTicker('"+id+"',"+targetnum+", "+(currentnum+1)+")",100);
	}	
}

function toggleCriteriaDisp(celem){
	 curval =document.getElementById(celem).innerHTML;
	if(curval == "-"){ //hide the contents
		document.getElementById(celem).innerHTML = "+";
		 $("#"+celem+"disp").hide("slow");
	}else{
		document.getElementById(celem).innerHTML = "-";
		 $("#"+celem+"disp").show("slow");

	}	
}

function addMoreCond(){
document.getElementById("addmorea").style.display = "none";
document.getElementById("addmoreb").style.display = "block";
document.getElementById("addmorekeyword").focus() ;
}

function addKeyword(){
  curq = document.getElementById('keyword').value; 
  newq = document.getElementById('addmorekeyword').value;
  if(newq == ""){
	return;
  }
  document.getElementById('keyword').value = curq+" and "+newq;
  document.mfrmquery.submit();
}
 
function showPreview() {
        el = document.getElementById("epreview");
        el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
}
function closePreview() {
        el = document.getElementById("epreview");
        el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
}


function getCookie(c_name){
	if (document.cookie.length>0)
	  {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1)
	    {
	    c_start=c_start + c_name.length+1;
	    c_end=document.cookie.indexOf(";",c_start);
	    if (c_end==-1) c_end=document.cookie.length;
	    return unescape(document.cookie.substring(c_start,c_end));
	    }
	  }
	return "";
}

$(document).ready(function(){
	var trl = getCookie("sessionid");
	var ref = "";
	if (document.referrer){
		ref = document.referrer;
	}
	var url = document.location.href;
	if (trl==""){
		if($.post)
			$.post("/rest/trail/",{ref: ref, url:url});
		else
			J.post("/rest/trail/",{ref: ref, url:url});
	}else{
		if($.post)
			$.post("/rest/path/",{url:url});
		else
			J.post("/rest/path/",{url:url});
	}
});



