/***************************/
//@Author: Adrian "yEnS" Mato Gondelle
//@website: www.yensdesign.com
//@email: yensamg@gmail.com
//@license: Feel free to use it, but keep this credits please!					
//
//@implementing and optimizing for Talent Banque: Alex Baskov, 2009
/***************************/

//SETTING UP OUR POPUP
//0 means disabled; 1 means enabled;
var popupStatusQuote = 0;


//loading popup with jQuery magic!
function loadPopupQuote()
{
	//loads popup only if it is disabled
	if(popupStatusQuote == 0)
	{
		$("#popupQuoteBackground").css({
			"opacity": "0.5" // set to zero, if you don't want to have a background
		});
		$("#popupQuoteBackground").fadeIn("slow");
		$("#popupQuote").fadeIn("slow");
		popupStatusQuote = 1;
	}
	
	$.validator.addMethod('customEmail', function(value, element) {
		return this.optional(element) || /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(element.value);
		},"Enter a valid email"
	);
	$.validator.addMethod('phoneSymbols', 
			function(value, element) {
				var stripped = value.replace(/[\s()+-]|ext\.?/gi, "");
				return ((/\d{7,20}/i).test(stripped));
			},"Enter a valid phone number"
	);
	$.validator.addMethod('phone', 
		function(value, element) {
			if ((value == null) || !(/^[0-9-+()\s]+$/i.test(value))) {
				return false;
			}
			else return true;
		},"Enter a valid phone number"
	);
	quote_validator = $("#form_quote").validate({
			errorElement: "div",
			rules: {
				quote_full_name: {
					required: true,
					minlength: 2,
					maxlength: 200
				},
				quote_email: {
					customEmail: true,
					required: true,
					minlength: 5,
					maxlength: 200
				},
				quote_phone: {
					required: true,
					phone: true,
					phoneSymbols: true
				},
				quote_mobile: {
					required: true,
					phone: true,
					phoneSymbols: true
				},
				quote_location:{
					required: true
				},
				quote_colour:{
					required: true
				},
				quote_type: {
					required: true
				},
				quote_date: {
					minlength: 2,
					maxlength: 20
				},
				quote_hours: {
					number: true,
					maxlength: 20
				},
				quote_comments: {
					maxlength: 4000
				}
			},
			messages: {
				quote_full_name: {
					required: "Missing full name",
					minlength: jQuery.format("Enter at least {0} characters"),
					maxlength: jQuery.format("Enter less than {0} characters")
				},
				quote_email: {
					email: "Enter a valid email",
					customEmail: "Enter a valid email",
					required: "Missing email",
					minlength: jQuery.format("Enter at least {0} characters"),
					maxlength: jQuery.format("Enter less than {0} characters")
				},
				quote_phone: {
					required: "Missing phone number",
					phone: "Enter valid phone number",
					phoneSymbols: "Enter between 7 and 20 digits"
				},
				quote_mobile: {
					required: "Missing phone number",
					phone: "Enter valid phone number",
					phoneSymbols: "Enter between 7 and 20 digits"
				},
				quote_location: {
					required: "Please select location"
				},
				quote_colour: {
					required: "Please select colour"
				},
				quote_type: {
					required: "Please select at least 1 type"
				},
				quote_date: {
					minlength: jQuery.format("Enter at least {0} characters"),
					maxlength: jQuery.format("Enter less than {0} characters")
				},
				quote_hours: {
					number: "Numbers only!",
					maxlength: jQuery.format("Enter less than {0} characters")
				},
				quote_comments: {
					maxlength: jQuery.format("Enter less than {0} symbols")
				}
			},
			errorPlacement: function(error, element) {
					switch($(element).attr("name") )
					{
						case "quote_location":
							$("#error_quote_location").append(error);
							break;
						case "quote_type":
							$("#error_quote_type").append(error);
							break;
						case "quote_colour":
							$("#error_quote_colour").append(error);
							break;
						/*case "quote_phone":
						case "quote_mobile":
							if ($("#quote_mobile:blank") && $("#quote_phone:blank"))
								$("#error_quote_phone").html("<div class='error' htmlfor='quote_phone' generated='true'>Input your phone or mobile number</div>");
							break;*/
						default:
							$(element).next().append(error);
					}
			},
			// set this class to error-labels to indicate valid fields
			success: function(label) {
				// set &nbsp; as text for IE
				label.html("&nbsp;").addClass("checked");
				label.parent().hide();
			},
			highlight: function(element, errorClass) {
				switch($(element).attr("name") )
					{
						case "quote_location":
							$("#error_quote_location").show();
							break;
						case "quote_type":
							$("#error_quote_type").show();
							break;
						case "quote_colour":
							$("#error_quote_colour").show();
							break;
						default:
							$(element).next().show();
					}
			},
			invalidHandler: function() {
				//$("#popupQuote .field_error").show();
			}
		});
		$("#popupQuote .popup_field input, #popupQuote .popup_field textarea").keypress(function(){
			quote_validator.element("#" + $(this).attr('id'));
		});
}

//disabling popup with jQuery magic!
function disablePopupQuote()
{
	//disables popup only if it is enabled
	if(popupStatusQuote == 1)
	{
		$("#popupQuoteBackground").fadeOut("slow");
		$("#popupQuote").fadeOut("slow");
		popupStatusQuote = 0;
	}
	showForm();
	$("#popupQuote .field_error").hide();
	$("#popupQuote input, #popupQuote textarea").val("");
}

//centering popup
function centerPopupQuote()
{
	//request data for centering
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = $("#popupQuote").height();
	var popupWidth = $("#popupQuote").width();

	//
	// we need here to emulate fixed position... so we use offsetHeight and offsetWidth instead
	// (c) Alex Baskov
	//
	var topScrollerPosition = 0;
	
	// we may just scroll to top and see nice popup
	//scroll(0,0);

	// center vertically in the visible area...
	if ($.browser.msie) {
		topScrollerPosition = document.body.scrollTop;
	}
	else {
		topScrollerPosition = window.pageYOffset;
	}

	//centering
	$("#popupQuote").css({
		"position": "fixed",
		"top": windowHeight/2-popupHeight/2,
		//"top": parseInt((windowHeight-popupHeight)/2) + topScrollerPosition,
		//"top": topScrollerPosition + 60,
		"left": windowWidth/2-popupWidth/2
	});
	//only need force for IE6
	
	$("#popupQuoteBackground").css({
		"height": windowHeight
	});
	
}

function showSuccess() {
	$("#popupQuote .message.progress").hide();
	$("#popupQuote .message.success").show();
	$("#popupQuote #popupQuoteOK").show();
	$("#popupQuote #popupQuoteOK").parent().show();
}

function showProgress() {
	$("#popupQuote .message,.col,.col2,.col3,.col5,.popup_label,.popup_field").hide();
	$("#popupQuote .message.progress").show();
	$("#popupQuote .popup_buttons").show();
	$("#popupQuote #quote_button_submit,#popupQuoteClose").parent().hide();
}

function showErrors(message) {
	$("#popupQuote .message.error").html(message);
	$("#popupQuote .message.progress").hide();
	$("#popupQuote .message.error").show();
	$("#popupQuote .popup_button").parent().show();
	$("#popupQuote #popupQuoteBack,#popupQuoteOK").show();
	$("#popupQuote #popupQuoteBack,#popupQuoteOK").parent().show();
}

function showForm() {
	$("#popupQuote .col,.col2,.col3,.col5,.popup_label,.popup_field").show();
	$("#popupQuote input[type=radio],input[type=checkbox]").attr("checked","");
	$("#popupQuote .message").hide();
	$("#popupQuote .message.desc").show();
	$("#popupQuote #popupQuoteOK").parent().hide();
	$("#popupQuote .button_back").hide();
	$("#popupQuote #quote_button_submit,#popupQuoteClose").parent().show();
}

function sendPhotographyQuoteRequest() {
	if (!(quote_validator.form())) {
		return false;
	}
	
	var quote_type = "";
	var quote_location = $('input[name=quote_location]:checked').val();
	var quote_colour =  $('input[name=quote_colour]:checked').val();
	
	$('input[name=quote_type]:checked').each(function() {
		quote_type += $("#quote_type_label_" + $(this).val()).text() + ",";
	});
	
	if (quote_location == undefined) {
		quote_location = "";
	}
	else {
		quote_location = $("#quote_location_label_" + quote_location).text();
	}
	
	if (quote_colour == undefined) {
		quote_colour = "";
	}
	else {
		quote_colour = $("#quote_colour_label_" + quote_colour).text();
	}
	
	var date = $("#quote_date").val();	
	date = (date == "dd/mm/yyyy" ? "" : date);
	var data = "name=" + escape($("#quote_full_name").val()) +
			   "&email=" + escape($("#quote_email").val()) +
			   "&phone=" + escape($("#quote_phone").val()) +
			   "&cell_phone=" + escape($("#quote_mobile").val()) +
			   "&date=" + escape(date) +
			   "&hours=" + escape($("#quote_hours").val()) +
			   "&information=" + escape($("#quote_comments").val()) +
			   "&location=" + escape(quote_location) +
			   "&colour=" + escape(quote_colour) +
			   "&type=" + escape(quote_type) +
			   "&photographerId=" + escape($("#quote_photographer_id").val()) +
			   "&photographerName=" + escape($("#quote_photographer_name").val());
	showProgress();
	$.ajax({
		type: "POST",
		url: "/external/photographers/quote",
		data: data,
		success: function(msg) {
			if (msg.indexOf("success:") != -1) {
			   showSuccess();
			   return false;
			}
			else if (msg.indexOf("error:") != -1) {
				var errors = msg.substring(msg.indexOf("error:") + "error:".length);
				var errorsList = errors.split(";");
				var message = "";
				for (var i = 0; errorsList.length; i++) {
					var errorInfo = errorsList[i];
					if (errorInfo == undefined || errorInfo == "") {
						break;
					}
					var splitted = errorInfo.split("=");
					var key = splitted[0];
					var value = splitted[1];
					message += "<li>" + key +": " +value +"</li>";
				}
				if (message == "") message = "Error during sending request.";
				showErrors(message);
			}
		}
	});
	return false;
}

//CONTROLLING EVENTS IN jQuery
$(document).ready(function() {

	//LOADING POPUP
	//Click the button event!
	$(".photographerButtonRequestQuote").click(function() {
		
		centerPopupQuote();
		loadPopupQuote();
		
		var photographerId = $(this).attr("photographer-id");
		if (photographerId != undefined) {
			$("#quote_photographer_id").val(photographerId);
			var photographerName = $(this).attr("photographer-name");
			$("#quote_photographer_name").val(photographerName);
		}
		
	});

	//Return to form
	$("#popupQuoteBack").click(function() {
		showForm();
	});
					
	//CLOSING POPUP
	$("#popupQuoteClose,#popupQuoteOK").click(function() {
		disablePopupQuote();
	});
	
	//Click out event!
	$("#popupQuoteBackground").click(function() {
		disablePopupQuote();
	});
	
	//Press Escape event!
	$(document).keypress(function(e) {
		if(e.keyCode == 27 && popupStatusQuote == 1) {
			disablePopupQuote();
		}
	});

});


