jQuery.extend({
    //dims the screen
    dimScreen: function(speed, opacity, callback) {
        if(jQuery('#__dimScreen').size() > 0) return;
        
        if(typeof speed == 'function') {
            callback = speed;
            speed = null;
        }

        if(typeof opacity == 'function') {
            callback = opacity;
            opacity = null;
        }

        if(speed < 1) {
            var placeholder = opacity;
            opacity = speed;
            speed = placeholder;
        }
        
        if(opacity >= 1) {
            var placeholder = speed;
            speed = opacity;
            opacity = placeholder;
        }

        speed = (speed > 0) ? speed : 500;
        opacity = (opacity > 0) ? opacity : 0.5;
        return jQuery('<div></div>').attr({
                id: '__dimScreen'
                ,fade_opacity: opacity
                ,speed: speed
            }).css({
            background: "#FFFFFF"
            ,height: $(document).height() + 'px'
            ,left: '0px'
            ,opacity: 0
            ,position: 'absolute'
            ,top: '0px'
            ,width: $(document).width() + 'px'
            ,"z-index": 999
        }).appendTo(document.body).fadeTo(speed, opacity, callback);
    },
    
    //stops current dimming of the screen
    dimScreenStop: function(callback) {
        var x = jQuery('#__dimScreen');
        var opacity = x.attr('fade_opacity');
        var speed = x.attr('speed');
        x.fadeOut(speed, function() {
            x.remove();
            if(typeof callback == 'function') callback();
        });
    }
});

/************************************************************************
 * 
 * build the lightbox on click element with the form inside
 */
$(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);

		// append the form to the correct html element.
		var lightbox_top = '<div class="lightbox_top"><div class="actions"><div class="action_close">close</div></div></div>';
		var lightbox='<div class="lightbox" id="lightboxSendComment"><div class="lightbox_content">'+ lightbox_top + form +'</div></div>';
		
		$(".lightboxContainer").append(lightbox);
		
		//Added the correct functionality to the submit button
		$(".button_submit").bind("click", function(e){
			form_data['submitAction']();
		});
		
		$.dimScreen(200, 0.7, function() {
			/*$("#lightboxSendComment").css({"z-index": "10000" });*/
	    	$('#lightboxSendComment').fadeIn();
		});
		
		
		// lightbox close
		$(".action_close").bind("click", function(e){
			$.dimScreenStop(100, 0.7, function() {
		    	$('#lightboxSendComment').fadeOut();
			});
			$(".lightboxContainer").empty();
		});
		$(".action_close").bind("click",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_html = '<div class="form"><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)
{
	var output = "<a class='ugc_comment_policy' href='" + formPolicyUrl + "'>" + formPolicyLabel + "</a>&nbsp;";
	return output;
}


function createFormField(data){
	var field_label='';
	if (data['label'] != '')
		field_label = data['label'];
	else
		field_label = data['name'];
	
	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">'+ field_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" 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 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" 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="' + data['name'] + '" 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="field">' + field_name + field_input + '</div>';
	return field;
}

function createFormButtons(submitAction, formPolicyUrl, formPolicyLabel){
	var form_policy = createFormPolicy(formPolicyUrl, formPolicyLabel);

	var buttons= '<div class="buttons"><div class="button">' + form_policy + '<input type="submit" class ="button_submit" name="submitComments" value="Submit"/></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){
		var lightbox_id = 'lightbox'+containerId;
		// append the form to the correct html element.
		//var lightbox_top = '<div class="lightbox_top"><div class="lightbox_actions"><div class="action_close">close</div></div></div>';
		//var lightbox='<div class="lightbox" id="'+lightbox_id+'"><div class="lightbox_content">'+ lightbox_top + content +'</div></div>';
		
		var lightbox_top = '<div class="lightbox_top"><div class="lightbox_actions"><div class="action_close">close</div></div></div>';
		var lightbox_bottom = '<div class="lightbox_bottom">&nbsp;</div>';
		var lightbox='<div class="lightbox" id="'+lightbox_id+'">' + lightbox_top + '<div class="lightbox_center"> <div class="lightbox_content">' + content +'</div></div>'+ lightbox_bottom +'</div>';
		
		$("#" + containerId).css({"display":"none"});
		$("#" + containerId).append(lightbox);
		
				
		//Added the correct functionality to the submit button
//		$(".button_submit").bind("click", function(e){
//			form_data['submitAction']();
//		});
		
		
		var options = 
		{
			//iframe : true,
			url: "/soln-ugc/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 and will be posted once it has been reviewed.");
				$.dimScreenStop(100, 0.7, function() {
					$("#"+lightbox_id).fadeOut();
				});
				$("#" + containerId).empty();
				//jQuery('#comment_response').append(response);
			}
		};
		//console.log(jQuery('.form form'));
			jQuery('.form form').submit(function () {
				jQuery(this).ajaxSubmit(options);
			
				return false;
			});
		
		
		$.dimScreen(350, 0.9, function() {
			$("#" + containerId).css({"display":"block"});
			centerThis(lightbox_id); 
			$("#"+lightbox_id).fadeIn();
			$("#"+lightbox_id).css({"z-index": "10000" });
		});
		
		// lightbox close
		$(".action_close").bind("click", function(e){
			$.dimScreenStop(100, 0.7, function() {
				$("#"+lightbox_id).fadeOut();
			});
			$("#" + containerId).empty();
		});
		$(".action_close").bind("click",submitAction);
	};
	
	$("#" + actionId).bind("click", doForm);
	
}

function createSimpleLightbox(content, containerId )
{
	
		var lightbox_id = 'lightbox'+containerId;
		var lightbox='<div class="lightbox" id="'+lightbox_id+'">' + content +'</div>';
		
		$("#" + containerId).css({"display":"none"});
		$("#" + containerId).append(lightbox);
		
		//Added the correct functionality to the submit button
		$(".button_submit").bind("click", function(e){
			form_data['submitAction']();
		});
		
		$.dimScreen(350, 0.9, function() {
			$("#" + containerId).css({"display":"block"});
			centerThis(lightbox_id); 
			$("#"+lightbox_id).fadeIn();
			$("#"+lightbox_id).css({"z-index": "10000" });
		});

		
		// lightbox close
		$(".action_close").bind("click", function(e){
			$.dimScreenStop(100, 0.7, function() {
				$("#"+lightbox_id).fadeOut();
			});
			$("#" + containerId).empty();
		});
		$(".action_close").bind("click",submitAction);

	
}

function openLightbox(content_div_id ) {
	content = $('#'+content_div_id).html();
	createSimpleLightbox(content, actionId , containerId );
}

function displayInLightbox(content_div_id, actionId , containerId ) {
	content = $('#'+content_div_id).html();
	//$(".lightboxContainer").append(lightbox);
	createSimpleLightbox(content,  containerId );
}

function centerThis(div) {
    var winH = $(window).height();
    var winW = $(window).width();
    var centerDiv = $('#' + div);
    centerDiv.css('top', '100px');
    centerDiv.css('left', winW/2-centerDiv.width()/2);
    
	$('#'+div).css({position: 'fixed'});
	//$('#'+div).vCenter();
}

(function($){
	$.fn.vCenter = function(options) {
		var pos = {
			sTop : function() {
				return window.pageYOffset || document.documentElement && document.documentElement.scrollTop || document.body.scrollTop;
			},
			wHeight : function() {
				return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body.clientHeight;
		 	}
		};
		
		return this.each(function(index) {
			if (index == 0) {
		 		var $this = $(this);
		 		var elHeight = $this.height();
		 		var elTop = pos.sTop() + (pos.wHeight() / 2) - (elHeight / 2);
				$this.css({
					position: 'absolute',
					marginTop: '0',
					top: elTop
 				});
			}
		});
	};
})(jQuery);

/*
$(function(){function hwOpen( id , type ) {
	// Close it first
	hwClose(); 
	$("a[@rel]").overlay();
	$("a.overlay").overlay(); 
});
*/