
/************************************************************************
 *
 * build the lightbox on click element with the form inside
 */
 var id_indx = 0;
$(function(){

	//$(".lightboxLink").lightBox({overlayBgColor: '#FFFFFF', overlayOpacity: 0.6} );

	$(".lightboxLink").bind("click", function(e){

		//$(this).lightBox();

		var form_data =  {
			formName: 'FormComments',
			formAction: '#',
			formMethod: 'post',
			title: 'Comments',
			fields: {
				1: {name: 'Name', type:'text', size:'31'},
				2: {name: 'Email', type:'text', size:'31'},
				3: {name: 'Comments', type:'textarea', rows:'4', cols:'35'}
				},
			submitAction: function(){alert('submit me');}
			};

		var form = createForm(form_data);
		new Boxy(form, {title: "Health Reform Blog Comment Form", modal: true, unloadOnHide: true});
		// append the form to the correct html element.


		//Added the correct functionality to the submit button
		$(".button_submit").bind("click", function(e){
			form_data['submitAction']();
		});


	});

});

/************************************************************************
 *
 * Form construction functions
 *
 */
function createForm(params){
/*	var form_container = '<div class="title">'+params['title']+'</div>';
	var form_subheading = '<div class="subheading">' + params['subheading'] + '</div>';
	var form_error = '<div class="error" id="form_error">&nbsp;</div>'; */
	var form_container = '';
	var form_subheading = '';
	var form_error = '';
	var form_html = '<div class="form ' + params['formName'] + '"><form name="'+params['formName']+'" action="'+params['formAction']+'" method="post">'
	var form_fields = '';
	jQuery.each(params, function(key, value) {
		switch(key){
			case 'fields':
				//console.log("objeto");
				jQuery.each(value, function(key, value) {
					//console.log("key", key, "value", value);
					form_fields = form_fields + createFormField(value);
				});
				break;

			default:
			   	//console.log(key, ": ", value);
			   	break;
		}
	});

	var form_buttons = createFormButtons(params['submitAction'], params['formPolicyUrl'], params['formPolicyLabel']);
	return form_container + form_subheading + form_error + form_html + form_fields + form_buttons + '</form></div>';
}

function createFormPolicy(formPolicyUrl, formPolicyLabel)
{
	if(formPolicyUrl != "")
		var output = "<br><a class='ugc_comment_policy' href='" + formPolicyUrl + "'>" + formPolicyLabel + "</a>&nbsp;";
	else
		var output = "";
	return output;
}


function createFormField(data){

	var field_label='';
	var id_str = data['name'] + (id_indx++);
	if (data['label'] != '')
		field_label = data['label'];
	else
		field_label = data['name'];


	//alert(field_label);
	var field_value='';
	if (data['value'] != '' && data['value'] != null)
		field_value = data['value'];

	var modify_height = '';
	if (data['type'] == 'rating')
		modify_height = 'style="line-height:30px;"';

	var field_name='';
	if (modify_height == '')
		field_name = '<div class="field_name"><label for="'+ id_str + '">'+ field_label + ':</label></div>';
	else
		field_name = '<div class="field_name" ' + modify_height + '>'+ field_label + ':</div>';

	var field_input='';
	switch(data['type']){
		case 'text':
			field_input = '<div class="field_input"><input type="text" id="'+id_str+'" name="'+data['name']+'" size="'+data['size']+'" value="'+ field_value +'"/></div>';
			break;
		case 'password':
			field_input = '<div class="field_input"><input type="password" name="'+data['name']+'" size="'+data['size']+'"/></div>';
			break;
		case 'textarea':
			field_input = '<div class="field_input"><textarea id="'+id_str+'" name="' + data['name'] + '" rows="'+data['rows']+'" cols="'+data['cols']+'">'+ field_value + '</textarea></div>';
			break;
		case 'hidden':
			field_input = '<div class="field_input"><input type="hidden" id="'+id_str+'" name="'+data['name']+'" size="'+data['size'] + '" value="'+ field_value +'"/></div>';
			break;
		case 'rating':
			//NS: Backup incase can't get stars working
			/*
			field_input = '<div class="field_input"><select name="'+data['name']+'" size="'+data['size'] + '">' +
				'<option value="5">Excellent</option><option value="4">Very Good</option><option value="3">Moderate</option><option value="2">Not Good</option><option value="1">Horrible</option>' +
				'</select';
			*/
			var rating_field_name = data['name'];
			var rating_current_li = "current-rating";
			var rating_star_width = 30;

			field_input = '<div class="field_input"><input id="' + id_str + '" type="hidden" name="'+data['name']+'" size="'+data['size'] + '" value="'+ field_value +'"/>' +
						  '<ul class="star-rating">' +
							'<li id="current-rating" class="current-rating" style="width:0px;"> Please Rate.</li>' +
							'<li><a href="javascript:void(null)" title="1 star out of 5" class="one-star" onclick="document.getElementById(\'' + rating_field_name + '\').value =\'1\';document.getElementById(\'' + rating_current_li + '\').style.width =\'' + (1 * rating_star_width) + 'px\';">1</a></li>' +
							'<li><a href="javascript:void(null)" title="2 stars out of 5" class="two-stars" onclick="document.getElementById(\'' + rating_field_name + '\').value =\'2\';document.getElementById(\'' + rating_current_li + '\').style.width =\'' + (2 * rating_star_width) + 'px\';">2</a></li>' +
							'<li><a href="javascript:void(null)" title="3 stars out of 5" class="three-stars" onclick="document.getElementById(\'' + rating_field_name + '\').value =\'3\';document.getElementById(\'' + rating_current_li + '\').style.width =\'' + (3 * rating_star_width) + 'px\';">3</a></li>' +
							'<li><a href="javascript:void(null)" title="4 stars out of 5" class="four-stars" onclick="document.getElementById(\'' + rating_field_name + '\').value =\'4\';document.getElementById(\'' + rating_current_li + '\').style.width =\'' + (4 * rating_star_width) + 'px\';">4</a></li>' +
							'<li><a href="javascript:void(null)" title="5 stars out of 5" class="five-stars" onclick="document.getElementById(\'' + rating_field_name + '\').value =\'5\';document.getElementById(\'' + rating_current_li + '\').style.width =\'' + (5 * rating_star_width) + 'px\';">5</a></li>' +
						 '</ul></div>';

						 //+ '<input type="button" onclick="document.getElementById(\'' + rating_field_name + '\').value =\'1\'" value="Testing" />';

			break;
	}
	var field='';

	if (data['type'] == 'hidden')
	{
		field = field_input;
	}
	else
		field= '<div class="fields">' + field_name + field_input + '</div>';
		//field=field_name + field_input;
	return field;
}

function createFormButtons(submitAction, formPolicyUrl, formPolicyLabel){
	var form_policy = createFormPolicy(formPolicyUrl, formPolicyLabel);

	var buttons= '<div class="buttons"><div class="button">' + '<input type="image" alt="Submit" src="http://www.healthreform.gov/images/sys_images/blog_submit_btn.jpg" class ="button_submit" name="submitComments" value="Submit"/>' + form_policy + '</div></div>';
	return buttons;
}


function submitAction()
{
	alert('submit me');
	return true;
}




function createCustomForm( form_data, actionId , containerId )
{//alert("hi");
	jQuery(function() {
		var form = createForm(form_data);
		createLightbox(form, actionId, containerId);
	});
}

function createLightbox(content, actionId , containerId )
{//alert("actionid: " + actionId);

	var doForm = function(e){

		$("#" + containerId).css({"display":"none"});
		//$("#" + containerId).append(content);

		var boxy = new Boxy(content, {title: "Health Reform Blog Comment Form", modal: true, unloadOnHide: true});
		$("div.FormComments" + actionId + " form div.field_input input").eq(0).focus();
		//Added the correct functionality to the submit button
//		$(".button_submit").bind("click", function(e){
//			form_data['submitAction']();
//		});


		var options =
		{
			//iframe : true,
			url: "/ugc-healthreform/comments.do",
			dataType: 'text',
			/*
			beforeSubmit: function(data,form,options) {
				var name = document.getElementsByName("psw_comment_author").item(0).value;
				var email = document.getElementsByName("psw_comment_author_email").item(0).value;
				var comment = document.getElementsByName("psw_collaborate_body").item(0).value;
				var form_errorField = document.getElementById("form_error");

				var regex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(2([0-4]\d|5[0-5])|1?\d{1,2})(\.(2([0-4]\d|5[0-5])|1?\d{1,2})){3} \])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
				var incorrectEmail = "";

				var error = "Please fill in the required fields: ";
				var missingFields = "";

				if (name == "")
					missingFields = "Name";

				if (email == "")
					if (missingFields == "")
						missingFields = "Email";
					else
						missingFields += ", Email";
				else if (email.match(regex) == null)
					incorrectEmail = "The input email is not valid";

				if (comment == "")
					if (missingFields == "")
						missingFields = "Comment";
					else
						missingFields += ", Comment";

				if (missingFields == "" && incorrectEmail == "")
				{
					form_errorField.innerHTML = "&nbsp;";
					//form_errorField.style.display = "none";
					return true;
				}
				else
				{
					var output = "";
					if (missingFields != "")
						output = error + missingFields;

					if (incorrectEmail != "")
						if (output == "")
							output = incorrectEmail;
						else
							output += "<br />" + incorrectEmail;

					form_errorField.innerHTML = output;

					return false;
				}
			},*/
			success: function(responseText, statusText) {
				alert("Your comment has been received. We will review your comment and post it if it complies with our comment policy.");
				$("#" + containerId).empty();
				//jQuery('#comment_response').append(response);
			}
		};
		//console.log(jQuery('.form form'));
			jQuery('.form form').submit(function () {
				jQuery(this).ajaxSubmit(options);
				boxy.hide();
				return false;
			});



	};

	$("#" + actionId).bind("click", doForm);
}

// Health Reform custom form
function createCustomForm2( form_data, actionId , containerId )
{//alert("hi");
	jQuery(function() {
		var form = createForm(form_data);
		createLightbox2(form, actionId, containerId);
	});
}

function createLightbox2(content, actionId , containerId )
{//alert("actionid: " + actionId);


		$("div#" + actionId).html(content);
		//var boxy = new Boxy(content, {title: "Health Reform Blog Comment Form", modal: true});
		var options =
		{
			//iframe : true,

			url: "/ugc-healthreform/comments.do",
			dataType: 'text',
			resetForm: true,
			success: function(responseText, statusText) {
				alert("Your comment has been received. We will review your comment and post it if it complies with our comment policy.");
				$("#" + containerId).empty();
				//jQuery('#comment_response').append(response);
			}
		};
		//console.log(jQuery('.form form'));
			//jQuery('.form form').submit(function () {
			$('.FormComments' +  actionId + ' form').submit(function () {
				if($(this).find('[name=body]').val() == "")
					alert("Comment field can not be empty.");
				else
					jQuery(this).ajaxSubmit(options);
				return false;
			});




}

