/*
	jMailer jQuery plugin version 1.0
	
	Copyright (c) 2009 Jens Ebbe Thomsen
	Adapted from  2009 Dan Wellman - version 1.2
  
	Dual licensed under the MIT and GPL licenses:
  http://www.opensource.org/licenses/mit-license.php
  http://www.gnu.org/licenses/gpl.html
	
*/

(function($) {
	  
	//url of current page
	var pageURL = window.location.href,
	
	//fields
	fields = ["to", "emne", "navn", "email", "tekst"];
	
	//define jMailer object with some default properties
	$.jMailer = {
		defaults: {
			id:"jMailer",
			message:"Skriv til os",
			recipient:"info",
			recipienta:"emu.dk",
			defaultClass:"jMailerContainer",
			additionalClass:null,
			suppressTo:false,
			animation: "hide",
			send: "Send",
			cancel: "Fortryd",
			close: "",
			errmsg: "Udfyld venligst alle felter",
	    labels: ["to", "Emne", "Navn", "E-mail", "Tekst"]
		}
	};
  
	//extend jquery with the plugin
	$.fn.extend({
		jMailer:function(config) {
																
			//use defaults or properties supplied by user
			config = $.extend({}, $.jMailer.defaults, config);
			
			//get href of link to post data to
			url = this.attr("rel");
			
			//create mailer and add to dom
			createMailer(config, url);
				
			//show mailer
			show(config);
			
			//return the jquery object for chaining
			return this;
		}
  });		
	
	//function to create the widget
	function createMailer(config, url) {  
	  var pageHOST = window.location.host;
				
		//create mailer div
	  $("<div>").attr("id", config.id).addClass(config.defaultClass).appendTo($("body"));
		
		//add additonal class if configured
		(config.additionalClass != null) ? $("#" + config.id).addClass(config.additonalClass) : null ;
		
		//create mailer form
		$("<fieldset>").attr({id:"jMailerForm"}).appendTo("#" + config.id);
		
		//add default fields to form
		$.each(fields, function(i, n) {
			if (this == "to") {
				if (config.suppressTo != true) {
					$("<label>").attr("for", this).attr("id", this + "Label").addClass("jMailerLabel").text(this + ":").appendTo("#jMailerForm");
					$("<input>").attr("id", this).attr("name", this).addClass("jMailInput").appendTo($("#" + this + "Label"));
				}
			} else {
				$("<label>").attr("for", this).attr("id", this + "Label").addClass("jMailerLabel").text(config.labels[i] + ":").appendTo("#jMailerForm");
				(this != "tekst") ? $("<input>").attr("id", this).attr("name", this).addClass("jMailInput").appendTo($("#" + this + "Label")) : $("<textarea>").attr("id", this).attr("name", this).text("").addClass("jMailText").appendTo("#" + this + "Label") ;			
			}
		});
		
		// add hidden fields
		$("<input>").attr("type", "hidden").attr("name", "content-type").attr("value", "text/plain; charset=utf-8; format=flowed").appendTo("#jMailerForm");
		$("<input>").attr("type", "hidden").attr("name", "missing_fields_redirect").attr("value", "http://"+pageHOST+"/generelt/skrivtil/minihovsa.html").appendTo("#jMailerForm");
		$("<input>").attr("type", "hidden").attr("name", "print_blank_fields").attr("value", "1").appendTo("#jMailerForm");
		$("<input>").attr("type", "hidden").attr("name", "recipient").attr("value", config.recipient+"@"+config.recipienta).appendTo("#jMailerForm");
		$("<input>").attr("type", "hidden").attr("name", "redirect").attr("value", "http://"+pageHOST+"/generelt/skrivtil/minitak.html").appendTo("#jMailerForm");
		$("<input>").attr("type", "hidden").attr("name", "required").attr("value", "navn,email,emne,tekst").appendTo("#jMailerForm");
		$("<input>").attr("type", "hidden").attr("name", "subject").attr("value", config.message).appendTo("#jMailerForm");
		$("<input>").attr("type", "hidden").attr("name", "Aktiveret fra").attr("value", document.referrer).appendTo("#jMailerForm");
		
		//add cancel button
		$("<button>").attr({id:"jMailerCancel", title:config.cancel, rel:config.close}).text(config.cancel).appendTo("#" + config.id).click(function() {
			
			//determine animation
			if (config.animation == "hide") {
				$("#" + config.id).hide("slow", function() { tidyUp() });
			} else if (config.animation == "slide") {
				$("#" + config.id).slideUp("slow", function() { tidyUp() });
			} else if (config.animation == "fade") {
				$("#" + config.id).fadeOut("slow", function() { tidyUp() });
			} else {
				$("#" + config.id).remove();
				tidyUp();
			}			
		});
		
		//remove plugin elements
			function tidyUp() {
				$("#jMailerOverlay").remove();
			};
		
		//add send button
		$("<button>").attr({id:"jMailerSend", title:config.send}).text(config.send).appendTo("#" + config.id).click(function() {
			
			//remove error message and styling if present
			(!$(".jMailerErrorMsg")) ? null : $(".jMailerErrorMsg").remove();
			$("#" + config.id + " input").each(function(){
			  var inputType = $(this).attr("type");
			  if (inputType != "hidden") {
  				$(this).removeClass("jMailerFailedInput");
  				$(this).parent().removeClass("jMailerFailedLabel");
				}
			});
			
			//get value of fields into data object
			var formData = {};
			formData.pageURL = pageURL;
			var errors = 0;
			$("#" + config.id + " input").each(function(){
			  var inputType = $(this).attr("type");
				
				if (inputType == "hidden") {
  					//populate data object
  					formData[$(this).attr("name")] = $(this).val();
				} else {
  				var id = $(this).attr("id");
  				var val = $(this).val();
  				if (id == "email") {
  				  var apos=val.indexOf("@");
            var dotpos=val.lastIndexOf(".");
            if (apos<1 || dotpos-apos<2) { val = ""; }
          }
  				//check fields not empty or wrong email format
  				if (val == "") {
  					//show failed validation
  				  $(this).addClass("jMailerFailedInput");
  					$(this).parent().addClass("jMailerFailedLabel");
  					errors += 1;
  				} else {
  				  
  				  $(this).removeClass("jMailerFailedInput");
  					$(this).parent().removeClass("jMailerFailedLabel");
  					//populate data object
  					formData[id] = val;
  				}
				}
			});
			
			$("#" + config.id + " textarea").each(function(){
				//check textarea not empty
				if ($(this).val() == "") {
					//show failed validation
				  $(this).addClass("jMailerFailedInput");
					$(this).parent().addClass("jMailerFailedLabel");
					errors += 1;
				} else {
				  $(this).removeClass("jMailerFailedInput");
					$(this).parent().removeClass("jMailerFailedLabel");
					//populate data object
					formData[$(this).attr("id")] = $(this).val();
				}
			});
			
			if (errors == 0) {
			  //disable the button to stop multiple submissions
				$(this).attr("disabled", "disabled");
				
			  //make request if no errors
        $.post(url, formData, processResponse);
      } else {
        $("<div>").addClass("jMailerErrorMsg").text(config.errmsg).appendTo("#" + config.id) ;
      }
		});
	};
	function show(config) {
		
		$("<div>").attr("id", "jMailerOverlay").insertBefore("#" + config.id);
		
		//remove error message and styling if present
		(!$(".errorMsg")) ? null : $(".errorMsg").remove();
			$("#" + config.id + " input").each(function(){
				$(this).removeClass("jMailerFailedInput");
				$(this).prev().removeClass("jMailerFailedLabel");
			});
		
		//show mailer
		$("#" + config.id).show("slow");
	};
	
	function processResponse(data) {
	  
	  //hide form elements
		$("#jMailerForm").hide("fast");
		$("#jMailerSend").hide("fast");
    
	  var lukText = $("#jMailerCancel").attr("rel");
		if (lukText == "") {
		  $("#jMailerCancel").hide("fast");
		} else {
      //change cancel button text
  		$("#jMailerCancel").text(lukText).attr("title", lukText);
  		
      $("#jMailerCancel").click(function() {
  			//show form elements again
  			$("#jMailerForm").show();
  			$("#jMailerSend").show().attr("disabled", "");
  			
  			$(this).remove();
  		});
		}
		
		//add message
		$("<div>").attr("id", "jMailerConfirm").html(data).insertBefore("#jMailerForm");
  };
		
})(jQuery);

