/*
    author : Mike Bosworth 
    date : May 2007
    description : UI for ShareContentService.
    dependencies : /web/parents/js/mootools.v1.1.js
*/

mdp.app.EmailContent = function(){

    /* ---[ CLASS VARIABLES ]--- */

    /* private */
    var self = this;
    var inputs;
    var alertEl, response, form;

    /* public */
    this.recipient = "";

    /* ---[ PUBLIC METHODS ]--- */

    /* Creates and sends email messages */
    this.sendMess = function(args) {
        if (!this.verify()) {
            var ed = {
                fromName : $("#fname").val(),
                fromEmail : $("#femail").val(),
                toName : $("#uname").val(),
                toEmail : $("#uemail").val(),
                url : args.url,
                message : $("#mess").val(),
                velocityFields:args.velocityFields,
                template : args.template,
                title : args.title,
                sendCopyToSender : $("#sendcopy").attr('checked'),
                pageDescription:args.pageDescription
            };
           
            /* values set for response message */
            self.recipient = $("#uname").val();
            self.title = args.title;
            if($.isEmptyObject(args.velocityFields)){
                ShareContentService.shareContent(ed, self.sent);
            }
            else{
                ShareContentService.shareVelocityContent(ed, self.sent);
            }
        }
    };

    /* Displays response message */
    this.sent = function() {
        alertEl = $("#alert").html(self.title + " has been sent to " + self.recipient + ". Your friend should receive it momentarily!");
        alertEl.css("display","block");
        form = $("#form");
        form.css("display","none");
        response = $("#response");
        response.css("display","block");
    };

    /* Verifies the form */
    this.verify = function() {
        var hasError = false;
        inputs = [$('#fname'), $('#femail'), $('#uname'),$('#uemail')];

        /* Validate text fields */
        for(var i=0; i<inputs.length; i++){
            if(inputs[i].val() == ""){
                inputs[i].attr("class","altbgcolor inputbox");
                hasError = true;
            }
            else{
                inputs[i].attr("class","defaultbgcolor inputbox");
            }
        }

        /* Validate email addresses */
        if(!hasError){
            if (!this.isValidEmail(inputs[1].val())){
                hasError = true;
                inputs[1].attr("class","altbgcolor inputbox");
            }
            else{
                inputs[1].attr("class","defaultbgcolor inputbox");
            }
            if(!this.areValidEmails(inputs[3].val())){
                hasError = true;
                inputs[3].attr("class","altbgcolor inputbox");
            }
            else{
                inputs[3].attr("class","defaultbgcolor inputbox");
            }
        }

        return hasError;
    };

    /* Validates mutiple emails */
    this.areValidEmails = function(str){
        var isValid = true;
        var emails = str.split(',');
        var i = 0;
        while(isValid == true && i < emails.length){
            isValid = this.isValidEmail(emails[i].trim());
            i++;
        }

        return isValid;
    };

    /* Validates Email input */
    this.isValidEmail = function(str){
        return /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(str);
    };

    /* Removes the form from the page */
    this.removeEm = function() {
        $("#emclp").remove();
    };

    /* Obtains the form via Ajax request */
    this.getForm = function(args){

        /* set parent to current parentId */
        var parent = $(this.parentId);
        if(this.parentId == null || parent.length == 0){

            /* if parent is null try and use the dynamic div */
            parent = $('#popuplayer');
            if (parent.length == 0) {

                /* if the dynamic div isn't there, inject it */
                parent = $("<div>").attr({'id': 'popuplayer'}).appendTo($('body:first'));
            }

            this.parentId = 'popuplayer';
            parent.addClass('invisible');
        }

        if(args.cssClass != null) {
            $(this.parentId).addClass(args.cssClass);
        }

        if (window.location.protocol=='https:'){
            $.ajax({
                url:"/common/profile/community/common/emailContent.jsp",
                type:'get',
                success:function(html){
                    parent.html(html);
                    position(args);
                }
            });
        } else {
            $.ajax({
                url:"/common/templates/emailContent/index.jsp",
                type:'get',
                success:function(html){
                    parent.html(html);
                    position(args);
                }
            });
        }


    };

    /* Clears inputs values and displays form */
    this.refreshForm = function(){
        /* Clear inputs */
        inputs[2].val('');
        inputs[3].val('');
        $('#mess').val('');

        /* Display form */
        form.css("display","block");
        response.css("display","none");
    };

    /* ---[ PRIVATE METHODS ]--- */

    /* Centers email form in the browser window */
    function position(args){
        setupEventListeners(args);
        var xcoord = 0;
        var ycoord = 0;
        var emclp = $("#emclp");

        xcoord = $(window).width()/2 - emclp.width()/2 + $(window).scrollLeft();
        ycoord = $(window).height()/2 - emclp.height()/2 + $(window).scrollTop();

        emclp.css({
           top:ycoord,
           left:xcoord
        });

        emclp.parent().removeClass('invisible');
    }

    function setupEventListeners(args){

        $("#stafclose").click(function(){
            mdp.emailContent.removeEm();
        });

        $("#stafsendbtn").click(function(){
            mdp.emailContent.sendMess(args);
        });

        $("#stafremove").click(function(){
            mdp.emailContent.removeEm();
        });

        $("#stafrefresh").click(function(){
            mdp.emailContent.refreshForm();
            mdp.emailContent.getForm(args);
        });

    }

};

/* Add shareable functionality to all elements with class='shareable' */
$(document).ready(function(){

    mdp.emailContent = new mdp.app.EmailContent();

    $(".shareable").each(function(i,element){
        var el = $(element);
        var elementTitle = el.attr("title");
        var params = (elementTitle == null)? null : elementTitle.split("|");
        var preservedTitle = (params[0] == null) ? "" : params[0];
        if(preservedTitle == null){
            el.removeAttr("title");
        }
        else{
            el.attr("title",preservedTitle);
        }

        var vf = {};

        if( el.attr('velocityFields') != null ){
            vf = $.parseJSON(unescape(el.attr('velocityFields')));
        }

        var args = {
            title:(params[1] == null || params[1] == "null") ? "" : params[1],
            template:(params[2] == null || params[2] == "null") ? "" : params[2],
            url:(params[3] == null || params[3] == "null") ? "" : params[3],
            site:(params[4] == null || params[4] == "null") ? "" : params[4],
            velocityFields:vf,
            cssClass:(params[5] == null || params[5] == "null") ? "" : params[5],
            pageDescription: (params[6] == null || params[6] == "null") ? "" : params[6] 
        };

        el.click(function(){ mdp.emailContent.getForm(args); });
        el.removeAttr("velocityFields");

    });
});


