var interest;
var lang;
var contact_path;
function initSimpleModal(){
	$("a.simplemodal").click(function (e) {
		e.preventDefault();
		// load the contact form using ajax
		interest = $(this).attr("rel");
		(window.location.href.indexOf("/en") > 0) ? lang = "en" : lang = "ro";
		(lang != "en") ? contact_path = "../contact.html" : contact_path = "../../contact-en.html";
		$.get(contact_path, function(data){
			// create a modal dialog with the data
			$(data).modal({
				close: false,
				position: ["15%",],
				overlayId: 'contact-overlay',
				containerId: 'contact-container',
				onOpen: contact.open,
				onShow: contact.show,
				onClose: contact.close
			});
		});
	});

	// preload images
	var img = ['_img/btn1.jpg', '_img/btn2.jpg', '_img/btn_close1.jpg', '_img/btn_close2.jpg', '_img/lightbox/lightbox-ico-loading.gif', '_img/simplemodal/bkg_nume.jpg', '_img/simplemodal/bkg_prenume.jpg', '_img/simplemodal/bkg_email.jpg', '_img/simplemodal/bkg_mesaj.jpg'];
	$(img).each(function () {
		var i = new Image();
		i.src = this;
	});
}

var contact = {
	message: null,
	open: function (dialog) {
		var title = $('#contact-container .contact-title').html();
		if (interest.indexOf("[job]") == -1) // product
		    if (lang != "en")
		        $('#contact-container .contact-content p').prepend("<span style='color:#333;'>Completati formularul pentru a cere informatii despre oferta noastra de <b>" + interest + "</b>.<br />Veti primi un raspuns prin email in cat mai scurt timp posibil.</span><br />");
		    else
		        $('#contact-container .contact-content p').prepend("<span style='color:#333;'>Please fill in the form to ask for information about <b>" + interest + "</b>.<br />You will receive a reply via email as soon as possible.</span><br />");
		else                                // job
		    if (lang != "en")
		        $('#contact-container .contact-content p').prepend("<span style='color:#333;'>Completati formularul pentru a solicita mai multe informatii despre postul disponibil de <b>" + interest.replace("[job]","") + "</b>.<br />Veti primi un raspuns prin email in cat mai scurt timp posibil.</span><br />");
		    else
		        $('#contact-container .contact-content p').prepend("<span style='color:#333;'>Please fill in the form to ask for information about the available position - <b>" + interest.replace("[job]","") + "</b>.<br />You will receive a reply via email as soon as possible.</span><br />");
		if (lang != "en")
		    $('#contact-container .contact-title').html('Se incarca...');
		else
		    $('#contact-container .contact-title').html('Loading...');
		dialog.overlay.fadeIn(200, function () {
			dialog.container.fadeIn(200, function () {
				dialog.data.fadeIn(200, function () {
					$('#contact-container .contact-content').slideDown(500, function(){
						$('#contact-container .contact-title').html(title);
						$('#contact-container form').fadeIn(200, function () {
							$('#contact-container #contact-nume').focus();
						});
					});
				});
			});
		});
	},
	show: function (dialog) {
		$('#contact-container .contact-send').click(function(e){
			e.preventDefault();
			// validate form
			if (contact.validate()) {
				$('#contact-container .contact-message').fadeOut(function(){
					$('#contact-container .contact-message').removeClass('contact-error').empty();
				});
				if (lang != "en")
				    $('#contact-container .contact-title').html('Se trimite...');
				else
				    $('#contact-container .contact-title').html('Sending...');
				$('#contact-container p').slideUp(200, function() {
				    $('#contact-container form').slideUp(200, function(){
				        $('#contact-container .contact-content').css("background","#333");
					    $('#contact-container .contact-content').animate({height: '60px'}, function(){
					        $('#contact-container .contact-loading').fadeIn(200, function(){
						        $.ajax({
							        url: (lang != "en") ? '../modalcontact.aspx' : '../../modalcontact.aspx',
							        data: 'n=' + $("#contact-nume").val() + '&p=' + $("#contact-prenume").val() + '&e=' + $("#contact-email").val() + '&m=' + $("#contact-mesaj").val() + '&i=' + interest + '&lang=' + lang,
							        type: 'post',
							        cache: false,
							        dataType: 'html',
							        complete: function (xhr, text_status) { // text_status example: success
								        $('#contact-container .contact-loading').fadeOut(200, function(){
								            if (lang != "en")
								                $('#contact-container .contact-title').html('Multumim');
								            else
								                $('#contact-container .contact-title').html('Thank you');
								        });
							        },
							        error: contact.error,
							        success: function (data, textStatus)
							        {
							            if (lang != "en")
							                $('#contact-container .contact-title').html('Multumim');
							            else
							                $('#contact-container .contact-title').html('Thank you');
    					                $('#contact-container .contact-content').html("<br /><span style='display:block; padding:5px; margin:0 15px; background:#666; border:1px solid #000; color:#fff;'>" + data + "</span>").fadeIn(200);
							        }
						        });
					        });
				        });
				    });
				});
			}
			else {
				if ($('#contact-container .contact-message:visible').length > 0) {
					var msg = $('#contact-container .contact-message div');
					msg.fadeOut(200, function () {
						msg.empty();
						contact.showError();
						msg.fadeIn(200);
					});
				}
				else {
					$('#contact-container .contact-message').slideDown("slow", contact.showError);
				}
				
			}
		});
	},
	close: function (dialog) {
		$('#contact-container .contact-message').fadeOut();
		//$('#contact-container .contact-title').html('Multumim');
		$('#contact-container form').fadeOut(200);
		$('#contact-container .contact-content').animate({
			height: 40
		}, function () {
			dialog.data.fadeOut(200, function () {
				dialog.container.fadeOut(200, function () {
					dialog.overlay.fadeOut(200, function () {
						$.modal.close();
					});
				});
			});
		});
	},
	error: function (xhr) {
		alert(xhr.statusText);
	},
	validate: function () {
		contact.message = '';
		if (!$('#contact-container #contact-nume').val()) {
		    if (lang != "en")
			    contact.message += 'Trebuie sa va introduceti numele.<br />';
			else
			    contact.message += 'Please fill in your last name.<br />';
		}
        if (!$('#contact-container #contact-prenume').val()) {
            if (lang != "en")
			    contact.message += 'Trebuie sa va introduceti prenumele.<br />';
			else
			    contact.message += 'Please fill in your first name.<br />';
		}

		var email = $('#contact-container #contact-email').val();
		if (!email) {
		    if (lang != "en")
			    contact.message += 'Trebuie sa va introduceti adresa de email.<br />';
			else
			    contact.message += 'Please fill in your email address.<br />';
		}
		else {
			if (!contact.validateEmail(email)) {
			    if (lang != "en")
				    contact.message += 'Adresa de email nu este valida.<br />';
				else
				    contact.message += 'Your email address is invalid.<br />';
			}
		}

		if (!$('#contact-container #contact-mesaj').val())
		{
		    if (lang != "en")
			    contact.message += 'Trebuie sa intoduceti mesajul.';
			else
			    contact.message += 'Please fill in the message field.';
	    }
		if ($("#contact-container #contact-mesaj").val().length > 1000)
		{
		    if (lang != "en")
		        contact.message += 'Mesajul dumneavoastra are ' + $("#contact-container #contact-mesaj").val().length + ' caractere. Lungimea maxima acceptata este de 1000 de caractere.';
		    else
		        contact.message += 'Your message contains ' + $("#contact-container #contact-mesaj").val().length + ' characters and excedes the maximum allowed length of 1000 characters.';
        }
		if (contact.message.length > 0) {
			return false;
		}
		else {
			return true;
		}
	},
	validateEmail: function (email) {
		var at = email.lastIndexOf("@");

		// Make sure the at (@) sybmol exists and  
		// it is not the first or last character
		if (at < 1 || (at + 1) === email.length)
			return false;

		// Make sure there aren't multiple periods together
		if (/(\.{2,})/.test(email))
			return false;

		// Break up the local and domain portions
		var local = email.substring(0, at);
		var domain = email.substring(at + 1);

		// Check lengths
		if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
			return false;

		// Make sure local and domain don't start with or end with a period
		if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
			return false;

		// Check for quoted-string addresses
		// Since almost anything is allowed in a quoted-string address,
		// we're just going to let them go through
//[gicu]		if (!/^"(.+)"$/.test(local))
//			// It's a dot-string address...check for valid characters
//			if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
//				return false;

		// Make sure domain contains only valid characters and at least one period
		if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
			return false;	

		return true;
	},
	showError: function () {
		$('#contact-container .contact-message')
			.html($('<div class="contact-error">').append(contact.message))
			.fadeIn(200);
	}
};
