/***************************/
//@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 popupStatusCastingEnquiry = 0;
var ce_validator = null;

//loading popup with jQuery magic!
function loadPopupCastingEnquiry()
{
	//loads popup only if it is disabled
	if(popupStatusCastingEnquiry == 0)
	{
		$("#popupCastingEnquiryBackground").css({
			"opacity": "0.5" // set to zero, if you don't want to have a background
		});
		$("#popupCastingEnquiryBackground").fadeIn("slow");
		$("#popupCastingEnquiry").fadeIn("slow");
		popupStatusCastingEnquiry = 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"
	);
	ce_validator = $("#form_castingenquiry").validate({
		errorElement: "div",
		rules: {
			ce_name: {
				required: true,
				minlength: 2,
				maxlength: 200
			},
			ce_phone: {
				phone: true,
				phoneSymbols: true
			},
			ce_email: {
				required: true,
				email: true,
				customEmail: true,
				minlength: 5,
				maxlength: 400
			},
			ce_dates: {
				minlength: 2,
				maxlength: 200
			},
			ce_type: {
                required: true,
				minlength: 2,
				maxlength: 200
			},
			ce_synopsis: {
				accept:'docx?|txt|pdf',
				minlength: 2,
				maxlength: 400
			},
			ce_briefs: {
				accept:'docx?|txt|pdf',
				minlength: 2,
				maxlength: 400
			},
			ce_feedetail: {
				accept:'docx?|txt|pdf',
				minlength: 2,
				maxlength: 400
			},
			ce_notes: {
				maxlength: 4000
			}
		},
		messages: {
			ce_name: {
				required: "Missing your name",
				minlength: jQuery.format("Enter at least {0} characters"),
				maxlength: jQuery.format("Enter less than {0} characters")
			},
			ce_phone: {
				required: "Missing phone number",
				phone: "Enter valid phone number",
				phoneSymbols: "Enter 7 - 20 digits"
			},
			ce_email: {
				email: "Enter a valid email",
				customEmail: "Enter a valid email",
				required: "Missing your email",
				minlength: jQuery.format("Enter at least {0} characters"),
				maxlength: jQuery.format("Enter less than {0} characters")
			},
            ce_dates: {
				minlength: jQuery.format("Enter at least {0} characters"),
				maxlength: jQuery.format("Enter less than {0} characters")
			},
            ce_type: {
				required: "Missing production type",
				minlength: jQuery.format("Enter at least {0} characters"),
				maxlength: jQuery.format("Enter less than {0} characters")
			},
			ce_synopsis: {
				accept: "Wrong file extension",
				minlength: jQuery.format("Enter at least {0} characters"),
				maxlength: jQuery.format("Enter less than {0} characters")
			},
			ce_briefs: {
				accept: "Wrong file extension",
				minlength: jQuery.format("Enter at least {0} characters"),
				maxlength: jQuery.format("Enter less than {0} characters")
			},
			ce_feedetail: {
				accept: "Wrong file extension",
				minlength: jQuery.format("Enter at least {0} characters"),
				maxlength: jQuery.format("Enter less than {0} characters")
			},
			ce_notes: {
				maxlength: jQuery.format("Enter less than {0} symbols")
			}
		},
		errorPlacement: function(error, element) {
			element.parent().prev().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) {
			$(element).parent().prev().show();
		},
		invalidHandler: function() {
			//$("#popupCastingEnquiry .field_error").show();
		}
	});
	$("#popupCastingEnquiry .popup_field input, #popupCastingEnquiry .popup_field textarea").keyup(function(event){
		if (event.keyCode != 9)
			ce_validator.element("#" + $(this).attr('id'));
	});
}

//disabling popup with jQuery magic!
function disablePopupCastingEnquiry()
{
	//disables popup only if it is enabled
	if(popupStatusCastingEnquiry == 1)
	{
		$("#popupCastingEnquiryBackground").fadeOut("slow");
		$("#popupCastingEnquiry").fadeOut("slow");
		popupStatusCastingEnquiry = 0;
	}
	$("#popupCastingEnquiry input, #popupCastingEnquiry textarea").val("");
	$("#form_castingenquiry .field_error").hide();
}

//centering popup
function centerPopupCastingEnquiry()
{
	//request data for centering
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = $("#popupCastingEnquiry").height();
	var popupWidth = $("#popupCastingEnquiry").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
	$("#popupCastingEnquiry").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
	
	$("#popupCastingEnquiryBackground").css({
		"height": windowHeight
	});
	
}

function showCastingEnquirySuccess() {
	$("#ce_form_holder").hide();
	$("#ce_form_title").text("Thank You");
	$("#ce_form_desc").html("Done! We've got the information about the project you are casting.")
		.removeClass("desc_error");
	$("#ce_button_ok_holder").show();
}

function showCastingEnquiryProgress() {
}

function showCastingEnquiryErrors(message) {
	$("#ce_form_holder").hide();
	$("#ce_form_title").text("Try Again");
	$("#ce_form_desc").html(message).addClass("desc_error");
	$("#ce_form_holder").show();
}

function sendCastingEnquiry() {
	if (!(ce_validator.form())) {
		return false;
	}
	showCastingEnquiryProgress();
	var data = $('#form_castingenquiry input,#form_castingenquiry textarea').fieldSerialize();
	$('#form_castingenquiry').ajaxSubmit
        ({
			type: "POST",
            url:'/external/castingEnquiry', 
            success: function (data, status)
			{
				if (data.indexOf("success:") != -1) {
					showCastingEnquirySuccess();
				}
				else if (data.indexOf("error:") != -1) {
					var errors = data.substring(data.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.";
					showCastingEnquiryErrors(message);
				}
            },
            error: function (data, status, e)
            {
                showCastingEnquiryErrors(e);
            }
    })
	return false;
}

//CONTROLLING EVENTS IN jQuery
$(document).ready(function() {

	//LOADING POPUP
	//Click the button event!
	
	$("#button_casting_enq").click(function() {
		$("#ce_form_title").text("Casting Enquiry");
		
		disablePopupCastingEnquiry();
		
		$("#ce_form_desc")
			.html("Please provide the following information about the project you are casting.")
			.removeClass("desc_error");
		$("#ce_button_ok_holder").hide();
		$("#ce_form_holder").show();
		
		//centering with css
		centerPopupCastingEnquiry();
		//load popup
		loadPopupCastingEnquiry();
	});
				
	//CLOSING POPUP
	$("#popupCastingEnquiryClose, #buttonCastingEnquiryOk").click(function() {
		disablePopupCastingEnquiry();
	});
	
	//Click out event!
	$("#popupCastingEnquiryBackground").click(function() {
		disablePopupCastingEnquiry();
	});
	
	//Press Escape event!
	$(document).keypress(function(e) {
		if(e.keyCode == 27 && popupStatusCastingEnquiry == 1) {
			disablePopupCastingEnquiry();
		}
	});

});


