// define namespace
if(typeof tx === "undefined"){var tx = {};}
if(typeof tx.volunteerdb === "undefined"){tx.volunteerdb = {};}

tx.volunteerdb.VOLUNTEER_HANDLER_URL = "/volunteerdb/volunteerprofile_handler/";
tx.volunteerdb.VOLUNTEER_GENERATOR_URL = "/volunteerdb/volunteerprofile_generator/";


// specificy the routing of forms
tx.volunteerdb.VOLUNTEER_FORM_ROUTER = { 
	 "VolunteerClinicalInfoForm": {
		form_label: "VolunteerClinicalInfoForm",
		form_type: 'cinfo', //processed specially on server side
		form_title: 'Volunteer for Future Clinical Trials',
		form_subtitle: 'Use the form below to enter your information to be contacted for future clinical trials',
		validate: true,
		submit_label: "Next",
		submit_url: tx.volunteerdb.VOLUNTEER_HANDLER_URL ,
		spinner_text: "Validating Information...",
		router: {"OK": "VolunteerContactInfoForm",
			 "NOTQ": "NoMatch"
		}
	 },
	"VolunteerContactInfoForm": {
		form_label: "VolunteerContactInfoForm",
		form_type: 'contact', //1. check the email, phone, inputs
		form_title: 'Enter Your Contact Information',
		form_subtitle: '',
		validate: true,
		submit_label: "Submit",
		submit_url: tx.volunteerdb.VOLUNTEER_HANDLER_URL,
		spinner_text: "Submitting Information...",
		router: {"OK": "VolunteerConfirmMessage"
		}
	  },
	  "VolunteerConfirmMessage": {
	  	form_label: "VolunteerConfirmMessage",
		form_type:'confirm',
	  	form_title: "Data Submitted Successfully",
		form_subtitle: '',
		validate: false,
		submit_label: "Close",
		submit_url: tx.volunteerdb.VOLUNTEER_HANDLER_URL,
		spinner_text: ""
	}

};

// widget styles
tx.volunteerdb.WIDGET_STYLES = { 
	   trialx_widget:{
			width: "400px",
			position: "relative", 
			cssFloat: "left",
			fontFamily:"Arial, Verdana",
			overflow: "hidden",
			 border: "1px solid #ececec"
		},
	  form_container:{ 
			 cssFloat: "left",
			 width:"400px",
			 padding: "5px"
		},
	  title_cover: {
			fontFamily: "Arial, Verdana",
			letterSpacing: "0.02em",
			borderBottom: "1px solid #ececec",
			padding: "8px",
			backgroundColor: "#fff",
			marginBottom:"5px"
		},
	  form_title: {
			fontSize: "20px",
			color: "#444",
			fontWeight: "bold"
		},
	  form_subtitle: {
			color: "#444",
			marginTop: "4px"
		}
};

// content styles
tx.volunteerdb.CONTENT_STYLES = {
		'ul': "font-size:100%; list-style-type:none; margin:0; padding:0; width:100%; display:block;",
		'li': "display:block; margin:0; padding:4px 5px 2px 9px; position:relative; clear:both;",
		'li:after': "display:block; margin:0; padding:4px 5px 2px 9px; position:relative; clear:both;",
		'li div': "display:inline-block;",
		'li span': "color:#444; float:left; margin:0 4px 0 0; padding:0 0 8px;",
		'li div label': "border:none; color:#222; display:block; font-size:95%; padding-top:3px; margin:0;",
		'li span label': "clear:both; color:#444; display:block; font-size:95%; line-height:130%; margin:0; padding-top:3px;",
		'input.text': "background:#fff url(/img/psignup/shadow.gif) repeat-x top;border-bottom:1px solid #ddd; border-left:1px solid #c3c3c3; border-right:1px solid #c3c3c3; border-top:1px solid #7c7c7c; color:#333; font-size:100%; margin:0; padding:7px 0;",
		'input.medium': "width:100%",
		'.description': "border:none; color:#222; display:block; font-size:95%; font-weight:700; line-height:150%; padding:0 0 1px;",
		'input[type=submit]': "background-color:#EE7721; color:#FFF; font-size:110%; padding:5px;",
		".trialx_rowradiochoices": "display:inline;font-size:95%;text-align:center; vertical-align:middle; float:left;",
		".trialx_rowradioitems": "display:block;vertical-align:middle;float:left;width:100%;",
		".guidelines": "background:#ECF1EF;border:0 solid #e6e6e6; color:#444; font-size:90%; right:0%; line-height:130%; margin:0 0 0 8px; padding:8px 10px 9px; position:absolute; top:0; visibility:hidden; width:30%; z-index:1000;",
		"li:hover .guidelines": "visibility:visible",
		".no_guidelines .guidelines": "display:none",
		"li.error": "background-color:#FFDFDF !important; border-bottom:1px solid #EACBCC; border-right:1px solid #EACBCC; margin:3px 0;",
		"li.error label": "color:#DF0000 !important;",
		"p.error": "clear:both; color:red; font-size:10px; font-weight:700; margin:0 0 5px;",
		".required":"color:red; float:none; font-weight:700;"
};

tx.volunteerdb.bind_action = function(form_type, next_form, submit_btn){
	submit_btn.unbind("click");
	submit_btn.click(function(){
		$.post( tx.volunteerdb.VOLUNTEER_HANDLER_URL ,
			{form_type:1},
			function(response){
				if(response == "OK"){ //cinfo is saved, then show the form for contact
				}
		});
	});
};

tx.volunteerdb.show_form = function(container_div, form_type, submit_btn){
	// var vurl = tx.volunteerdb.VOLUNTEER_PROFILE_URL;
	$.get( tx.volunteerdb.VOLUNTEER_HANDLER_URL ,
		{form_type:form_type},
		function(response){
			container_div.html(response);
			$("form_submit").unbind("click");
	});
};

if (typeof trialx == 'undefined') { trialx = {};}
if (typeof trialx.trial == 'undefined') { trialx.trial = {};}
if (typeof trialx.trial.widget == 'undefined') { 
	trialx.trial.widget = new Object();
}

trialx.trial.widget.init = function(widget_id){
	var server_domain 	= SITE_DOMAIN; //this has to be "injected" from the serving page.. can be fetchd from settings.SITE_DOMAIN localhost or the host of hte domain
	var is_secure 		= false;
	var conn_type 		= "http://";
	if(is_secure)
		conn_type 	= "https://";

	var params 		= {
		"form_seq": tx.volunteerdb.VOLUNTEER_FORM_ROUTER,	
		"widget_styles": tx.volunteerdb.WIDGET_STYLES,
		"content_styles": tx.volunteerdb.CONTENT_STYLES,
		"generator_url": tx.volunteerdb.VOLUNTEER_GENERATOR_URL,
		"init_form": "VolunteerClinicalInfoForm"
	};


	trialx.trial.widget.setup(widget_id, server_domain, is_secure, params);

};

trialx.trial.widget.setup = function(widget_id, server_domain, is_secure, params){

	var obj_seq 	   = params["form_seq"];
	var widget_styles  = params["widget_styles"];
	var content_styles = params["content_styles"];
	var init_form	   = params["init_form"];	
	var generator_url  = params['generator_url']

	
	for (var content_style in content_styles){
		CSSRules.add("#trialx_widget"+widget_id+" "+content_style, content_styles[content_style]);
	}
	

	//layout dom
	var trialx_widget 	= document.createElement("div");
	trialx.trial.widget.extend_properties(trialx_widget.style, widget_styles['trialx_widget']);


	/*var contentxy 		= document.createElement("div");
	trialx.trial.widget.extend_properties(contentxy.style, widget_styles['contentxy']);

	var sectionxy 		  = document.createElement("div");
	trialx.trial.widget.extend_properties(contentxy.style, widget_styles['sectionxy']);*/

	var subxy 		= document.createElement("div");
	//trialx.trial.widget.extend_properties(subxy.style, widget_styles['subxy']);
	
	trialx_widget.name 	= "trialx_widget"+widget_id;
	trialx_widget.id 	= "trialx_widget"+widget_id;

	/*contentxy.name 		= "contentxy"+widget_id;
	contentxy.id 		= "contentxy"+widget_id;

	sectionxy.name 		= "sectionxy"+widget_id;
	sectionxy.id 		= "sectionxy"+widget_id;*/

	subxy.name		= "subxy"+widget_id;
	subxy.id		= "subxy"+widget_id;


	trialx_widget.appendChild(subxy);
//	contentxy.appendChild(sectionxy);
//	sectionxy.appendChild(subxy);

	var form 		= document.createElement("form");
	form.name 		= "trialx_frmwc"+widget_id;
	form.id 		= "trialx_frmwc"+widget_id;
	
	var form_container 	= document.createElement("div");
	form_container.id 	= "trialx_form_container"+widget_id;
	trialx.trial.widget.extend_properties(form_container.style, widget_styles['form_container']);

	//title area
	var title_cover 	= document.createElement("div");
	title_cover.id 		= "trialx_title_cover"+widget_id;
	trialx.trial.widget.extend_properties(title_cover.style, widget_styles['title_cover']);

	var form_title 		= document.createElement("div");
	form_title.id 		= "trialx_form_title"+widget_id;
	trialx.trial.widget.extend_properties(form_title.style, widget_styles['form_title']);
	
	var form_subtitle 	= document.createElement("div");
	form_subtitle.id 	= "trialx_form_subtitle"+widget_id;
	trialx.trial.widget.extend_properties(form_subtitle.style, widget_styles['form_subtitle']);
	
	title_cover.appendChild(form_title);
	title_cover.appendChild(form_subtitle);

	//form area
	var wc 	= document.createElement("ul");
	wc.id 	= "trialx_wcon"+widget_id;
	wc.name = "trialx_wcon"+widget_id;

	var submit_btn 	= document.createElement("input");
	submit_btn.type = "submit";
	submit_btn.id 	= "trialx_sb"+widget_id;
	submit_btn.name = "trialx_sb"+widget_id;
	submit_btn.value = "Please wait...";

	//status area
	var tx_proc 	= document.createElement("div");
	var proc_img 	= document.createElement("img");

	var conn_type = "http://";
	if(is_secure)
		conn_type = "https://";

	proc_img.src 		= conn_type+server_domain+"/img/spinner_transparent.gif";
	var spinner_text 	= document.createElement("span");

	tx_proc.appendChild(proc_img);
	tx_proc.appendChild(spinner_text);

	//append all form elements
	form_container.appendChild(title_cover);
	form_container.appendChild(wc);
	form_container.appendChild(submit_btn);
	form_container.appendChild(tx_proc);

	form.appendChild(form_container);

	//add form to tx_container
	subxy.appendChild(form);
	
	//root element by defailt trialx_widget_id
	var root_element = document.getElementById("trialx"+widget_id);
	root_element.innerHTML = "";
	root_element.appendChild(trialx_widget);

	//init events
	$(form).submit(function(){
		return false;
	});

	
	form_router = new trialx.trial.widget.FormRouter({
		'widget_id' : widget_id,
		'trial_id':trial_id, 
		'form_seq': obj_seq,
		'parentContainer': wc, 
		'submitBtn': submit_btn, 
		'formtitle':form_title, 
		'formsubtitle':form_subtitle, 
		'spinner_text': spinner_text, 
		'tx_processing':tx_proc,
		'server_domain': server_domain,
		'is_secure': false,
		'security_code':'',
		'generator_url':generator_url});

	form_router.init(init_form);


	$("#trialx_name"+widget_id).live('keypress',
		function(e){
			if(form_router.security_code.indexOf('1')==-1){
				form_router.security_code += '1';
				//alert('name');
			}
	});

	$("#trialx_email"+widget_id).live('keypress',
		function(e){

			if(form_router.security_code.indexOf('2')==-1){
				form_router.security_code += '2';
			}

	});

	$("#trialx_phone"+widget_id).live('keypress',
		function(e){
			if(form_router.security_code.indexOf('9')==-1){
				form_router.security_code += '9';
				//alert(form_router.security_code);
			}
	});
	
	
};

trialx.trial.widget.extend_properties = function(object1, object2){
	for(var property in object2){
		object1[property] = object2[property];
	}
};

var CSSRules = function() {
	 var headElement = document.getElementsByTagName("head")[0],
	 styleElement = document.createElement("style");
	 styleElement.type = "text/css";
	 headElement.appendChild(styleElement);
	 
	 var add = function() {
	  if (styleElement.styleSheet) {
	   return function(selector, rule) {
	    if (styleElement.styleSheet.cssText == '') {
	     styleElement.styleSheet.cssText = '';
	    }
	    styleElement.styleSheet.cssText += selector + " { " + rule + " }";
	   }
	  } else {
	   return function(selector, rule) {
	    styleElement.appendChild(document.createTextNode(selector + " { " + rule + " }"));
	   }
	  }
	 }();
	 
	 return {
	  add : add
	 }
}();


trialx.trial.widget.FormRouter = function(options){
	this.widget		= options.widget_id;
	this.trial 		= options.trial_id;
	this.forms 		= options.form_seq;
	this.parentContainer 	= options.parentContainer;
	this.submitBtn 		= options.submitBtn;
	this.currentForm 	= "";
	this.formTitle 		= options.formtitle;
	this.formSubtitle 	= options.formsubtitle;
	this.spinnerText 	= options.spinner_text;
	this.tx_processing 	= options.tx_processing;
	this.server_domain 	= options.server_domain;
	this.is_secure 		= options.is_secure;
	this.security_code 	= options.security_code;
	this.generator_url 	= options.generator_url;
};


trialx.trial.widget.FormRouter.prototype.check_required = function(){
	var invalid = {};
	elements = $([]).add($("#trialx_frmwc"+this.widget).get(0)).filter(":input")
	.not(":submit, :reset, :image, [disabled]");
	for(var i=0;i<elements.length;i++){
		var element 	= elements[i];
		var valid 	= true;
		element.error_message = "This field is required";
		switch(element.nodeName.toLowerCase()){
			case 'select':
				// could be an array for select-multiple or a string, both are fine this way
				var val = $(element).val();
				valid = val && val.length > 0;
				break;
			case 'input':
				if ( /radio|checkbox/i.test(element.type) ){
					valid = $("input[name='"+element.name+"']:checked").length > 0;
				}else{
					valid = $.trim(element.value).length > 0;
					//check email
					if (valid && element.id.indexOf("trialx_email")!=-1){
						var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
						valid  = filter.test($.trim(element.value));
						element.error_message = "Please enter a valid email address";

					}

					//check phone
					if (valid && element.id.indexOf("trialx_phone")!=-1){
						var phval = $.trim(element.value);
					 	var stripped = phval.replace(/[\(\)\.\-\ ]/g, '');    
					    	if (isNaN(parseInt(stripped))) {
							valid = false;
							element.error_message = "The phone number contains illegal characters.\n";
					    	} else if (!(stripped.length == 10)) {
							valid = false;
							element.error_message = "The phone number is the wrong length. Make sure you included an area code.\n";
					   	} 
					}

				}
				break;
			default:
				valid = $.trim(element.value).length > 0;
				
		};


		if (!valid){
			invalid[element.name] = element;
		}
        }

	var is_valid = true;
	for(var element_name in invalid){
		is_valid = false;
		element = invalid[element_name];
		var error_li= $("#"+element_name+"_li");
		if(!(error_li.attr("class") == "error")){
			error_li.attr("class", "error");
		
			var pelement = document.createElement("p");
			pelement.setAttribute("class"," error");
			
			error_text =document.createTextNode(element.error_message);	
			pelement.appendChild(error_text);
			error_li.append($(pelement));
		}

		(function(eli){
			var focuselement = '';
			if (element.type.indexOf("radio")!=-1 || element.type.indexOf("checkbox")!=-1)
				focuselement = $("input[name='"+element.name+"']");
			else
				focuselement = $(element);

			focuselement.focus(function(e){
				eli.attr("class", "highlighted");
				var childErrorP = eli.children(".error").get(0);
				if(childErrorP){
					$(childErrorP).remove();
				}
			});
		})(error_li);
	}

	return is_valid;

}


trialx.trial.widget.FormRouter.prototype.init = function (form_label){

	this.displayForm(this.forms[form_label].form_label);
	this.currentForm = this.forms[form_label];

	//associate submit Event
	var fr = this;
	$(fr.submitBtn).click(function(e){
		//first check if we need client side validation
			if (fr.currentForm.form_type=="cinfo" || fr.currentForm.form_label == "InvestigatorSelect" || fr.currentForm.form_label == "SendMessage")
				if(!fr.check_required())
					return false;
			form_data = $("#trialx_frmwc"+fr.widget).serialize();
			form_data = form_data+"&trial="+fr.trial+"&ft="+fr.currentForm.form_type+"&wgtid="+fr.widget;
			//alert("current form"+fr.currentForm.form_label);
			//alert("form "+form_data);
		
			if(fr.currentForm.form_type == "contact"){
				var sc_key 	= $("#trialx_sc"+fr.widget).val();
				//alert("key "+sc_key);
				var encrypted_code = "";

				var to_enc 	= parseInt(fr.security_code);
				//alert(to_enc);

				/*if(to_enc.length!=){
					alert("Please enter your Name, Email and Phone number");
					return;
				}*/
				//sc will always be between 100-999 nad to_enc length == 3
				for(var j=0;j<sc_key.length;j++){
					encrypted_code +=String.fromCharCode(sc_key.charCodeAt(j)^to_enc);
				}
			
				var enc_uri = encodeURI(encrypted_code);
				form_data += "&sc="+enc_uri;
				//alert("ENC"+ encrypted_code);
			}
			
			if(fr.currentForm.form_type == "confirm"){
				//trigger event to close
				$('body').trigger("close_trialx"+fr.widget);
				return; 
			}
			
			$(fr.tx_processing).show();
		
			var conn_type = "http://";
			if(fr.is_secure)
				conn_type = "https://";

			$.ajax({
				'type': 'GET',	
				'url': conn_type+fr.server_domain+fr.currentForm.submit_url,
				'data': form_data, 
				'dataType': 'jsonp',
				success: function(result){
				//	alert('response :'+result.response.status);
					if(result.response.status == "OK"){
						
						nextform_label = fr.currentForm.router[result.response.status];
						fr.displayForm(nextform_label);
					}
					else if(result.response.status == "NOTQ")
					{
						nextform_label = fr.currentForm.router[result.response.status];
						fr.displayForm(nextform_label);
					}
					else if(result.response.status == "CAPTCHA_ERROR")
					{
						alert("Sorry, the please re-enter the words as shown in the image");
						Recaptcha.reload();
					}
					else if(result.response.status == "INPUT_ERROR")
					{
						alert("Please enter your name, email and phone");
					}
					else{
						alert("Sorry. Some error occurred. Please try again later");
					}

				}
			});
	});
	
};

trialx.trial.widget.FormRouter.prototype.displayForm = function(form_label){
	//set a closure to pass
	var fr = this; //make this public variable to enable access inside the inner function

	var conn_type = "http://";
	if(this.is_secure)
		conn_type = "https://";

	$.ajax({
		 'type':'GET',
		 'url' : conn_type+fr.server_domain+fr.generator_url+form_label+"/"+"?wgtid="+fr.widget, 
		 'dataType': 'jsonp',
		 'success': function(form_obj){
		 	form_html 			= form_obj.form_html;
			//alert(fr.parentContainer.innerHTML);
			
			$(fr.parentContainer).html(form_html);	
			$(fr.tx_processing).hide();
			//alert(fr.parentContainer.id);
			//runScripts(fr.parentContainer);
			//
			if (typeof fr.forms[form_label] !== "undefined"){
				fr.currentForm = fr.forms[form_label];
				fr.updateLabels();
			//alert("new current "+fr.currentForm.form_label);
			}
		  }
	});

};

trialx.trial.widget.FormRouter.prototype.updateLabels = function(){

	if (typeof this.currentForm.form_title!= 'undefined'){
		this.formTitle.innerHTML = this.currentForm.form_title;
	}
	if (typeof this.currentForm.form_subtitle!= 'undefined'){
		this.formSubtitle.innerHTML = this.currentForm.form_subtitle;
	}

	if (typeof this.currentForm.submit_label!= 'undefined'){
		$(this.submitBtn).css("display","block");
		this.submitBtn.value = this.currentForm.submit_label;
	}else{
		$(this.submitBtn).css("display","none");
	}

	if (typeof this.currentForm.spinner_text != 'undefined'){
		this.spinnerText.innerHTML = this.currentForm.spinner_text;
	}
};

