$(document).ready(function() {

	
	$("#step1btn").bind("click", step1);
	$("#step2btn").bind("click", step2);

	$('#contentxy').localScroll({// Only the links inside that jquery object will be affected
		lazy: true, // This is the KEY setting here, makes the links work even after an Ajax load.
		target: '#contentxy', // The element that gets scrolled
		axis:'x', // Horizontal scrolling
		duration:500,
		onBefore:function( e, subsec, $cont ){//'this' is the clicked link
			if( this.blur )
				this.blur(); // Remove the awful outline
		}
	});
	
	$("#step3btn").bind("click", sendmessage);
	$("input").bind("click", clearError);

	//alert($("#bsendmessage input[type=text]:nth-child(1)").attr('id'));
	//$("#bsendmessage input[type=text]:nth-child(1)").focus();
	/*$("input[name='checkname']").bind("click", 
		function(){
			 var selected = $("input[name='checkname']:checked").val();	
			 if (selected=="m"){
				$("#name").focus();
			 }
		}
	);

	$("#name").bind("focus", 
		function(){
			$("#checkname_m").attr("checked", "checked");
		}
	);*/

	$("#toggle_preview_btn").click(
		function(){
			if ($('#bmessagepreview').is(":hidden")) {
		       	    $('#img_preview').attr('src','/img/hide.png');
			    $('#bmessagepreview').slideDown("slow");
		       } else {
		       	    $('#img_preview').attr('src','/img/show.png');
			    $('#bmessagepreview').slideUp("slow");
		       }
		}
	);

	$("#name").keypress(
		function(e){
			//var temp_name = $("#name").val();
			//$("#bname").html("<span>"+temp_name+"</span>");
			if (e.which == 32 || (65 <= e.which && e.which <= 65 + 25)
						|| (97 <= e.which && e.which <= 97 + 25)) {
						
				var c = String.fromCharCode(e.which);
				$("#bname").append($('<span style="color:#fff"/>')).children(":last").append(document.createTextNode(c));
			   }else  if (e.which == 8) {
				// backspace in IE only be on keydown
					$("#bname").children(":last").remove();
			      }
			
		}
	);

	//var options = {exact:"whole",style_name_suffix:false, engines:[/^http:\/\/localhost/i,/keyword=([^&]+)/i]};
	//var options = {exact:"whole",style_name_suffix:false};
    	//$(document).SearchHighlight(options);
	
});

function step1(){
	var has_error = false;
	
	if ($("#check_condition").length>0){
		if($("INPUT[name='check_condition']:checked").length == 0){
			errorMessage($("#condition_li"), "Please select one condition");
			has_error = true;
		}
	}

	if($("#zip").val() == ""){
		errorMessage($("#zip_li"), "Please enter your zip");
		has_error = true;
	}else if($("#zip").val().length<5){
		errorMessage($("#zip_li"), "Zip code should be 5 characters");
		has_error = true;
	}

	if(has_error)
		return; 

	$("#zip2").val($("#zip").val())


	//check data validation
	if(!$("#bsendmessage").valid())
		return false;

	//check qualification
	$("#qualification_mesg").show();

	$("#redirect").hide();
	var qualify = true;
	$.ajax({
		type:"POST",
		url:"/ajax_check_qualification/",
		data:$("#bsendmessage").serialize(),
		async:false,	
		dataType: "json",
		success: function(qresult){
			if(qresult.match_score<100){
				var exp_html = ""
				for(var i=0;i<qresult.explanations.length;i++){
					exp = qresult.explanations[i];

					exp_html += "<li>";
					if (exp.exclude){
						exp_html += "This trial excludes patients if "	
					}else{
						exp_html += "This trial only includes patients if "	
					}

					if (exp.is_range){
						exp_html += "<b>"+exp.entity_name+"</b> is greater than "+exp.expected_min_numvalue+" and less than "+exp.expected_max_numvalue;	
					}else{
						exp_html += "<b>"+exp.entity_name+"</b> equal to "+exp.expected_value;	
					}
					exp_html +=" (<em>You Entered "+exp.entered_value+"</em>)";
					exp_html += "</li>";
				}

				exp_html = "<ul>"+exp_html+"</ul>";

				$("#nomatch_explain").html(exp_html);

				$("#nomatch_details").click(function(){
					$("#nomatch_explain").toggle();

				});
				$("#qualification_mesg").hide();
				$("#nomatch").show();
				$("#aqualify").click();
				qualify = false;
				window.scroll(0,100);

				$("#notifyme").click(function(){
					if(!$("#qualifycontact").valid()){
						return;
					}
					$("#redirect").show();
					//save this info		
					$.ajax({
							type:"POST",
							url:"/ajax_notqualify_save/",
							data:$("#qualifycontact").serialize()+"&"+$("#bsendmessage").serialize(),
							async:false,	
							success: function(qresult){
								if (qresult == "user_exists"){
									alert("Your account already exists on TrialX. Please login to set up an alert under My Trials.");
									return;
		  						}else{
									$("#aredirect").click();
								}
							}
					});

				});
			}else{
				$("#qualification_mesg").hide();
			}
		}
	});

	if(!qualify){
		return;
	}


	$("#fetching_mesg").show();
	var ilistdiv	= document.getElementById("investigator_list");
			
	if ( ilistdiv.hasChildNodes() )
	{
	    while ( ilistdiv.childNodes.length >= 1 )
	    {
		ilistdiv.removeChild( ilistdiv.firstChild );       
	    } 
	}
	var trialid	= $("#trial").val();
	var zip		= $("#zip").val();
		//"trial="+trialid+"&zip="+zip,
	$.ajax({
		type:"GET",
		url:"/ajax_get_investigators/",
		data:$("#bsendmessage").serialize(),
		async:false,	
		success: function(ilist){
			$("#fetching_mesg").hide();
			$("#investigator_list").show();
			var sites = eval('('+ilist+')');	
			if(sites.length>4){
				$("#investigator_list").css('height','280px');	
			}
			for(var i=0;i<sites.length;i++){
				distance_html = "";
				if(sites[i].display_distance != "9999.0")
					distance_html = '<span style="float:right;font-size:10px;padding:2px;background-color:#5a9abe;color:#FFF;font-weight:bold">'+sites[i].display_distance+' miles</span>';
					
				$("#investigator_list").append(
				   '<div class="mesgdisp">'+
					'<div style="float:left;padding-bottom:0px;width:100%;color:#333;font-weight:bold;font-size:12px">'+
						'<div style="float:left;width:150px;overflow:hidden;height:18px;">'+
							'<input type="checkbox" name="toinvestigator" value="'+sites[i].uid+'">'+
							'<a target="_blank" href="/profile/'+sites[i].uid+'">'+sites[i].name+'</a>'+
						'</div>'+
						distance_html+
					'</div>'+
					'<div style="padding-left:20px;padding-bottom:0px;">'+sites[i].site+'</div>'+
					'<div style="padding-left:20px;padding-bottom:0px;">'+sites[i].city+', '+sites[i].state+'</div>'+
				   '</div>'+
				   '<script>$("input").bind("click",clearError)</script>'
				);

			}//end of for
		window.scroll(0,100);
		$("#asites_li").click();//slide next screen
		}//end of success
	});
}

function step2(){
	//send message to server.. get back cinfo obj

	var has_error = false;
	if($("INPUT[name='toinvestigator']:checked").length == 0){
		errorMessage($("#sites_li"), "Please select one investigator or site to send your message");
		has_error = true;
	}

	if(has_error)
		return;

	/*var conditions	= new Array();
	$("INPUT[name='check_condition']:checked").each(
		function() {
			conditions.push($(this).val());
		});

	var toinvestigators = new Array();
	$("INPUT[name='toinvestigator']:checked").each(
		function() {
			toinvestigators.push($(this).val());
		});

	var trial = $("#trial").val();
	var qlog = $("#qlog").val(); */

	var data1 = $("#bsendmessage").serialize();
	var data2 = $("#bsites").serialize();
	$("#step2_processing").show();

	var data = data1+"&"+data2;
    	var args = { type:"POST", url:"/ajax_pre_sendmessage/", data:data, complete:complete_contactinvestigator };
    	$.ajax(args);
	//$("#bsendmessage").hide();	
}

var complete_contactinvestigator = function(res, status){
	  if (status == "success") {
		  $("#step2_processing").hide();
	  	  $("#aname_li").click();
		window.scroll(0,100);
		  
		  var txt = res.responseText; 
  		  var response = eval('('+txt+')');	
		  $("#bmessage").html(response.mbody);
		  $("#bmessagepreview").hide();
		  $("#nids").val(response.nids);

	  }else{
		alert('We are experiencing technical difficulties. Please try again later.\n TrialX (info@trialx.com)');
	  }
}

function sendmessage(){
	//send message to server.. get back cinfo obj
	has_error = false;
	if($("#email").val() == ""){
		errorMessage($("#email_li"), "Please enter your Email");
		has_error = true;
	}else if(!isValidEmail($("#email").val())){
		errorMessage($("#email_li"), "Your Email is Not Valid");
		has_error = true;
	}

	if($("#name").val() == ""){
		errorMessage($("#name_li"), "Please enter your Name");
		has_error = true;
	}

	if($("#phone").val() == ""){
		errorMessage($("#phone_li"), "Please enter your Phone");
		has_error = true;
	}else{
		phval = $("#phone").val();
		ph_errors = validatePhone(phval);
		if (ph_errors!=""){
			errorMessage($("#phone_li"), ph_errors);
			has_error = true;
		}
	}

	if(has_error)
		return


	var data = $("#breviewandsend").serialize();
	$("#step3_processing").show();
    	var args = { type:"POST", url:"/ajax_sendmessage/", data:data, complete:complete_sendmessage};
    	$.ajax(args);
}

var complete_sendmessage = function(res, status){
	  if (status == "success") {
		  var txt = res.responseText; 
		  $("#step3_processing").hide();
		  if (txt == "user_exists"){
			alert("Your account already exists on TrialX. Please login to send a message");
			return;
		  }

		 if (txt == "captcha_error"){
			errorMessage($("#captcha_li"), "Please enter the words as shown in the picture. This is to prevent spam submission. You can change the image by pressing the new word option");
			Recaptcha.reload();
			return;
		  }

		  if(txt == "Success"){
		  	$("#email_step").hide();
		  	$("#top_message").hide();
			$("#esend_confirm").show();
			window.scroll(0,100);
			
			return;
		  }

	  }else{
		alert('We are experiencing technical difficulties. Please try again later.\n TrialX (info@trialx.com)');
	  }
}


function showCaptcha(){
	clearErrorMessage('email_li');
	if($("#txcaptcha").css('display')=='none'){
		$("#txcaptcha").css('display','block');	
	}
}

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


function validatePhone(phone) {
    var error 		= "";
    var stripped = phone.replace(/[\(\)\.\-\ ]/g, '');    
   if (phone.value == "") {
        error = "You didn't enter a phone number.\n";
    } else if (isNaN(parseInt(stripped))) {
        error = "The phone number contains illegal characters.\n";
    } else if (!(stripped.length == 10)) {
        error = "The phone number is the wrong length. Make sure you included an area code.\n";
    }
    return error;
}


function validateForm(){
	var has_error = false;
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test($("#email").val())) {
		var error_li= document.getElementById('email_li');
		addErrorMessage(error_li, "Please provide a valid email address");
		has_error = true;
	}

	if($("#zip").val()==""){
		has_error = true;
		var error_li= document.getElementById('zip_li');
		addErrorMessage(error_li, "Please enter the zip");
	}

	if(has_error)
		return false;
	else
		return true;
}

/*function validatePatientForm(){

	var data = $('#bsendmessage').serialize()

	var elemns = new Array();
	var edata = new Array();
	$("#bsendmessage :radio").each(function(){
			if(!$(this).is(":checked"))
				if(!elemns[this.name]){
					elemns[this.name] = 1;
					edata.push(this.name+"=");
				}
	});

	var newdata = edata.join("&");

	data = data+"&"+newdata;

	//var data = $("#bsendmessage").serialize();
	//VALIDATE form
	var validated = true;
    	$.ajax({
		 type:"GET",
		 async: false,
		 url:"/validate_dynform/",
		 dataType: "json",
		 data:data,
		 success: function(data){
		 	if(data['error_list'].length>0){
				validated = false;
				highlight_errors(data['error_list']);
			}
		 }
	});
	return validated;	
} */

function highlight_errors(error_list){

	$.each(error_list, function(i,error){
		//alert(error.entity_name+" "+error.message);
		var error_li= document.getElementById(error.entity_name+'_li');
		addErrorMessage(error_li, error.message);
	});
}


