/***************************/
//@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 LMCM Management: Alex Baskov, 2009
/***************************/

//SETTING UP OUR POPUP
//0 means disabled; 1 means enabled;
var popupStatusEmail = 0;
var ready = false;
var validator = null;

//loading popup with jQuery magic!
function loadPopupEmail()
{
	//loads popup only if it is disabled
	if(popupStatusEmail == 0)
	{
		$("#popupEmailBackground").css({
			"opacity": "0.8"
		});
		$("#popupEmailBackground").fadeIn("slow");
		$("#popupEmail").fadeIn("slow");
		popupStatusEmail = 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( 
	  "customRequired", 
	  function(value, element) { 
		if (element.value == element.title) 
	    { 
	      return false; 
	    } 
	    else return true; 
	  }, 
	  "Please input something." 
	);
	validator = $("#form_email_to_friend").validate({
		errorElement: "div",
		rules: {
			your_email: {
				customRequired: true,
				customEmail: true
			},
			friend_email: {
				customRequired: true,
				customEmail: true
			}
		},
		messages: {
			your_name: {
				customRequired: "Missing your name",
				required: "Missing your name",
				minlength: jQuery.format("Enter at least {0} characters"),
				maxlength: jQuery.format("Enter less than {0} characters")
			},
			your_email: {
				email: "Enter a valid email",
				customEmail: "Enter a valid email",
				customRequired: "Missing your email",
				required: "Missing your email",
				maxlength: jQuery.format("Enter less than {0} characters")
			},
			friend_name: {
				customRequired: "Missing friend name",
				required: "Missing friend name",
				minlength: jQuery.format("Enter at least {0} characters"),
				maxlength: jQuery.format("Enter less than {0} characters")
			},
			friend_email: {
				email: "Enter a valid email",
				customEmail: "Enter a valid email",
				customRequired: "Missing friend email",
				required: "Missing friend email",
				maxlength: jQuery.format("Enter less than {0} characters")
			},
			comments: {
				maxlength: jQuery.format("Enter less than {0} symbols")
			}
		},
		errorPlacement: function(error, element) {
				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) {
			$(element).next().show();
		},
		invalidHandler: function() {
			$("#form_email_to_friend .field_error").show();
		},
		submitHandler: function() {

		}
	});
	$("input[class^='input_text_rhp']").keypress(function(){
		validator.element("#" + $(this).attr('id'));
	});
}

//disabling popup with jQuery magic!
function disablePopupEmail()
{
	//disables popup only if it is enabled
	if(popupStatusEmail == 1)
	{
		$("#popupEmailBackground").fadeOut("slow");
		$("#popupEmail").fadeOut("slow");
		popupStatusEmail = 0;
	}
	
	$(".popupEmailForm .message").hide();
	$(".popupEmailForm .message.desc").show();
	$(".popupEmailForm .label").show();
	$(".popupEmailForm .field").show();
	$(".popupEmailForm .field_delim").show();
	$(".popupEmailForm #popupEmailClose").show();
	$(".popupEmailForm #button_email_ok").parent().hide();
	$(".popupEmailForm #button_email_submit").parent().show();
}

//centering popup
function centerPopupEmail()
{
	//request data for centering
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	//var windowWidth = document.body.clientWidth;
	//var windowHeight = document.body.clientHeight;
	var popupHeight = $("#popupEmail").height();
	var popupWidth = $("#popupEmail").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...
	var topScrollerPosition = document.documentElement.scrollTop;

	//centering
	$("#popupEmail").css({
		"position": "fixed",
		"top": windowHeight/2-popupHeight/2+40,
		//"top": parseInt((windowHeight-popupHeight)/2) + topScrollerPosition,
		//"top": topScrollerPosition + 40,
		"left": windowWidth/2-popupWidth/2
	});
	//only need force for IE6
	
	$("#popupEmailBackground").css({
		"height": windowHeight
	});
	
}

function showEmailSuccess() {
	$(".popupEmailForm .message").hide();
	$(".popupEmailForm .message.success").show();
	$(".popupEmailForm .field_btn").show();
	$(".popupEmailForm #button_email_ok").parent().show();
}

function showEmailErrors() {
	$(".popupEmailForm .message").hide();
	$(".popupEmailForm .message.error").show();
	$(".popupEmailForm #button_email_ok").parent().show();
}

function showEmailProgress() {
	$(".popupEmailForm .message").hide();
	$(".popupEmailForm .message.in_process").show();
	$(".popupEmailForm .label").hide();
	$(".popupEmailForm .field").hide();
	$(".popupEmailForm .field_delim").hide();
	$(".popupEmailForm #popupEmailClose").hide();
	$(".popupEmailForm #button_email_submit").parent().hide();
}

	function sendEmail2Friend(artistId) {
		if (artistId == undefined) return;
		
		if (!(validator.form())) {
			return false;
		}
		showEmailProgress();
        var data = "_sender=" + escape(realValueOf("#your_name")) +
                   "&_senderEmail=" + escape(realValueOf("#your_email")) +
                   "&_receiver1=" + escape(realValueOf("#friend_name")) +
                   "&_receiverEmail1=" + escape(realValueOf("#friend_email")) +
                   "&_message=" + escape(realValueOf("#comments")) +
                   "&_url=" + escape(window.location); 
		
        $.ajax({
            type: "POST",
            url: "/external/artistProfile/" + artistId + "/email2friend",
            data: data,
            success: function(msg) {
                if (msg.indexOf("success:") != -1) {
                    showEmailSuccess();
                }
                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];
						
						if (key == "_senderEmail") {
							key = "Your Email";
						}
						else if (key == "_sender") {
							key = "Your Name";
						}
						else if (key == "_receiver1") {
							key = "Friend Name";
						}
						else if (key == "_receiverEmail1") {
							key = "Friend Email";
						}
						else if (key == "_message") {
							key = "Comments";
						}
						
						message += "<li>" + key +": " +value +"</li>";
                    }
					if 	(message == "") message = "Error during sending request.";
					$(".popupEmailForm .message.error").html(message);
					showEmailErrors();
                }
            }
        });
    }

//CONTROLLING EVENTS IN jQuery
$(document).ready(function() {

	//LOADING POPUP
	//Click the button event!
	
	/*
	$("#buttonEmail").live('click', function() {
		//centering with css
		centerPopupEmail();
		//load popup
		loadPopupEmail();
	});
	*/
				
	//CLOSING POPUP
	//Click the x event!
	$("#popupEmailClose").live('click', function() {
		disablePopupEmail();
	});
	
	//Click out event!
	$("#popupEmailBackground").live('click', function() {
		disablePopupEmail();
	});
	
	//Press Escape event!
	$(document).keypress(function(e) {
		if(e.keyCode == 27 && popupStatusEmail == 1) {
			disablePopupEmail();
		}
	});

});


function emailToFriendPopup()
{
	centerPopupEmail();
	loadPopupEmail();

	return true;
}