/*
    jMailer jQuery plugin version 1.1
    
    Copyright (c) 2009 Dan Wellman
  
    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", "from_name", "from", "message"],
    
    //detect ie6
    ie6 = ($.browser.msie == true && $.browser.version == "6.0") ? true : false;
    
    //define jMailer object with some default properties
    $.jMailer = {
        defaults: {
            modal:true,
            id:"mailer",
            message:"Hi, check out this great page I found: ",
            shim:(ie6 == true) ? true : false,
            forceShim:false,
            defaultClass:"mailer-container",
            additionalClass:null,
            suppressTo:false,
            animation: "hide",
//            translation: {to:"Send this page to email address",from_name:"Your name",from:"Your email address",message:"Message",cancel:"Cancel",send:"Send"}
            translation: { 
                to:"Send siden til denne emailadresse",
                from_name:"Dit navn",
                from:"Din emailadresse",
                message:"Besked",
                cancel:"Annullér",
                send:"Send",
                errEmail:"Ugyldig emailadresse",
                errMissing:"Feltet skal udfyldes"}
        }
    };
  
    //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
            //create mailer and add to dom
            createMailer(config);
                        
            //add click handler
            this.click(function(e){
                
                //stop link following href
                e.preventDefault();
                
                //show mailer
                show(config);
            });
            
            //return the jquery object for chaining
            return this;
        }
    });        
    
    //remove plugin elements
    function tidyUp() {
        (ie6 == true) ? $("#shim").remove() : null ;
        $("#overlay").remove();
    };
        
    
    //function to create the widget
    function createMailer(config) {
        
        //normalize body if ie6
        (ie6 == true) ? $("body").css({padding:"0", margin:"0"}).width("100%").height("100%") : null ;
        
        //create mailer div
      $("<div>").attr("id", config.id).addClass(config.defaultClass).css({display:"none", position:"absolute", zIndex:"99999", width:"300px"}).appendTo($("body"));
        
        //add additonal class if configured
        (config.additionalClass != null) ? $("#" + config.id).addClass(config.additonalClass) : null ;
        
        //create mailer form
        $("<fieldset>").attr({id:"mailerForm"}).appendTo("#" + config.id);
        
        //add default fields to form
        $.each(fields, function() {
            if (this == "to") {
                if (config.suppressTo != true) {
                    $("<div>").attr("id", this).appendTo("#mailerForm");
                    $("<div>").addClass("label").text(config.translation[this] + ":").appendTo("#" + this);
                    $("<input>").attr("id", this + "_field").appendTo($("#" + this));
                }
            } else {
                $("<div>").attr("id", this).appendTo("#mailerForm");
                $("<div>").addClass("label").text(config.translation[this] + ":").appendTo("#" + this);
                (this != "message") ? $("<input>").attr("id", this + "_field").appendTo($("#" + this)) : $("<textarea>").attr("id", this + "_field").text(config.message).appendTo("#" + this) ;            
            }
        });
        
        $("#" + config.id + " #to input").add("#" + config.id + " #from input").addClass("emailfield");
        
        //add cancel button
        $("<button>").attr({id:"cancel", title:config.translation["cancel"]}).text(config.translation["cancel"]).appendTo("#" + config.id).click(function() {

            //determine animation
            if (config.animation == "hide") {
                $("#" + config.id).hide("fast", function() { tidyUp() });
            } else if (config.animation == "slide") {
                $("#" + config.id).slideUp("fast", function() { tidyUp() });
            } else if (config.animation == "fade") {
                $("#" + config.id).fadeOut("fast", function() { tidyUp() });
            } else {
                $("#" + config.id).remove();
                tidyUp();
            }            
        });

        //add send button
        $("<button>").attr({id:"send", title:config.translation["send"]}).text(config.translation["send"]).appendTo("#" + config.id).click(function() {
            
            //remove error message and styling if present
            (!$(".errorMsg")) ? null : $(".errorMsg").remove();
            $("#" + config.id + " input").add("#" + config.id + " textarea").each(function(){
                $(this).css({border:"1px solid #abadb3"});
            });
            
            $("#" + config.id + " div.error").remove();
            
            //get value of fields into data object
            var formData = {};
            formData.pageURL = pageURL;
            formData.sunix_post_page = true;
            var errors = 0;
            var emailerrors = 0;
            $("#" + config.id + " input").add("#" + config.id + " textarea").each(function(){
                
                //check fields not empty
                if ($(this).val() == "" || ($(this).hasClass("emailfield") && !email_validate(this) )) {
                    
                    //show failed validation
                    $(this).css({border:"1px solid #ff0000"});
                    if ($(this).hasClass("emailfield") && !email_validate(this)) $(this).after("<div class=\"error\">" + config.translation["errEmail"] + "</div>");
                    else $(this).after("<div class=\"error\">" + config.translation["errMissing"] + "</div>");
                    errors += 1;
                } 
                else {
                    //populate data object
                    formData[$(this).parent().attr("id")] = $(this).val();
                }
            });
            
            //make request if no errors
            if (errors == 0) $.ajax({
                async:false,
                type:"post",
                url:pageURL,
                data:formData,
                success:function(data){
                    if(data=="success") {
                        $("#mailer").hide("fast", function() { tidyUp() });
                        return true;
                    }                                         
                    else alert("error: " + data);
                },
                error:function(objError){ alert("error: " + objError.statusText); },
                dataType:"text"
            });
        });
    };
    
    function show(config) {
        
        //create modal if set to true
        (config.modal == true) ? $("<div>").attr("id", "overlay").css({opacity:0.7, backgroundColor:"#000000", zIndex:99990, height:"100%", width:"100%", position:"fixed", top:0, left:0}).insertBefore("#" + config.id) : null ;
        
        //create shim if enabled
        (config.shim == true || config.forceShim == true) ? $("<iframe>").attr({src:"", frameBorder:"0", scrolling:"no", id:"shim"}).css({display:"block", zIndex:99989, opacity:0, height:$("body").height(), width:"100%", position:"absolute", top:0, left:0}).insertBefore("#overlay") : null ;
        
        //viewport dimensions
        var vDim = {
            w:(!window.innerWidth) ? document.documentElement.offsetWidth : window.innerWidth,
            h:(!window.innerHeight) ? document.documentElement.offsetHeight : window.innerHeight
        };
        
        //has the visitor scrolled
        var sDim = {
            x:(document.documentElement.scrollLeft) ? document.documentElement.scrollLeft : document.body.scrollLeft,
            y:(document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop
        };
        
        //set mailer position
        var left = sDim.x + (vDim.w - $("#" + config.id).width()) / 2;
        var top = (sDim.y + (vDim.h - $("#" + config.id).height()) / 2) - 27; 
        
        //remove error message and styling if present
        (!$(".errorMsg")) ? null : $(".errorMsg").remove();
        $("#" + config.id + " input").add("#" + config.id + " textarea").each(function(){
            $(this).css({border:"1px solid #abadb3"});
        });

        $("#" + config.id + " div.error").remove();
        
        //show mailer
        $("#" + config.id).css({left:left, top:top}).fadeIn("slow",function(){ 
            if (jQuery.browser.msie) this.style.removeAttribute("filter");
            $("#" + config.id + " #to input").focus();
        });
        
    };
    
        
})(jQuery);

function email_validate(email_element) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var address = email_element.value;
   if(reg.test(address) == false) {
      return false;
   }
   return true;
}

