﻿(function($) {

$.fn.emailForm = function(opts) {
        var pageurl = null;
        var triggerElm = null;
        var emailBox = null;
        var isAtached = false;
        
        var SendEmail = function()
            {
                var data = {processForm :true};
                
                $("#email-form input, #email-form textarea").each(function(){
                    data[$(this).attr("name")] = $(this).val();
                });
                emailBox.load(pageurl + " #email-form",
                    data,
                    function(data, textStatus, XMLHttpRequest){
                                $("#email-form input.send").bind("click", SendEmail);
                                $("#email-form .close").bind("click", CloseForm);
                                $("#email-form label.overlabel").overlabel();
                                $("#email-form .textCount").textCounter({limit: 40, warning: 30, counterText: 'words remaining', countWords:true});
                                triggerElm.trigger("totalEmailCountChanged");
                            });
                return false;
            };
        
        var CloseForm = function ()
            {
                emailBox.detach();
                emailBox.empty();
                isAtached = false;
            };
        
        var LoadEmailFormComplete = function(data, textStatus, XMLHttpRequest)
        {
        
            //emailBox.css({top: '59px',left: '683px'});
        
        /*  //Nice but doesnt work in IE 7 :(
            emailBox.position(
                { my: 'right bottom'
                , at: 'left top'
                , of: $('#email-link')
                , offset: '40 -4'
                , collision: 'none'
                }
             );
        */
            $("#email-form input.send").bind("click", SendEmail);
            $("#email-form .close").bind("click", CloseForm);
            emailBox.show();
            $("#email-form label.overlabel").overlabel();
            $("#email-form .textCount").textCounter({limit: 40, warning: 30, counterText: 'words remaining', countWords:true});
        };
        
        var LoadEmailForm = function()
            {
                if(!isAtached)
                {
                    emailBox.hide();
                    triggerElm.parent().append(emailBox);
                    isAtached = true;
                    emailBox.load(pageurl + " #email-form", LoadEmailFormComplete);
                }
                else
                {
                    CloseForm();
                }
                
                return false;
            }

		this.each(function() {
		    emailBox = $("<div id='email-form-container'/>");
		    pageurl = $(this).attr("href");
		    triggerElm = $(this);
		    triggerElm.bind("click", LoadEmailForm);
		});
        return this;
	};
})(jQuery);
