/*
    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 alert, response, form;

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

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

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

            if(args.velocityFields != null){
                ShareContentService.shareVelocityContent(ed, self.sent);
            }
            else{
                ShareContentService.shareContent(ed, self.sent);
            }
        }
    };

    /* Displays response message */
    this.sent = function() {
        alert = $("alert").setHTML(self.title + " has been sent to " + self.recipient + ". Your friend should receive it momentarily!");
        alert.style.display = "block";
        form = $("form");
        form.style.display = "none";
        response = $("response");
        response.style.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].getValue() == ""){
                inputs[i].className = "altbgcolor inputbox";
                hasError = true;
            }
            else{
                inputs[i].className = "defaultbgcolor inputbox";
            }
        }

        /* Validate email addresses */
        if(!hasError){
            if (!this.isValidEmail(inputs[1].getValue())){
                hasError = true;
                inputs[1].className = "altbgcolor inputbox";
            }
            else{
                inputs[1].className = "defaultbgcolor inputbox";
            }
            if(!this.areValidEmails(inputs[3].getValue())){
                hasError = true;
                inputs[3].className = "altbgcolor inputbox";
            }
            else{
                inputs[3].className = "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() {
        $(self.parentId).removeChild($("emclp"));
    };

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

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

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

                /* if the dynamic div isn't there, inject it */
                parent = new Element('div', {'id': 'popuplayer'}).injectInside($E('body'));
            }

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

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

        if (window.location.protocol=='https:'){
            new Ajax("/common/profile/community/common/emailContent.jsp", {method:'get', update:parent, onComplete:function(){ position(args); }}).request();
        } else {
            new Ajax("/common/templates/emailContent/index.jsp", {method:'get', update:parent, onComplete:function(){ position(args); }}).request();
        }


    };

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

        /* Display form */
        form.style.display = 'block';
        response.style.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.getSize().size.x/2 - emclp.getSize().size.x/2 + window.getSize().scroll.x;
        ycoord = window.getSize().size.y/2 - emclp.getSize().size.y/2 + window.getSize().scroll.y;

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

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

    function setupEventListeners(args){

        var stafclose = $("stafclose");
        if(stafclose != null){
            stafclose.addEvent("click",function(){
                mdp.emailContent.removeEm();
            });
        }

        var stafsendbtn = $("stafsendbtn");
        if(stafsendbtn != null){
            stafsendbtn.addEvent("click",function(){

                mdp.emailContent.sendMess(args);
            });
        }


        var stafremove = $("stafremove");
        if(stafremove != null){
            stafremove.addEvent("click",function(){
                mdp.emailContent.removeEm();
            });
        }

        var stafrefresh = $("stafrefresh");
        if(stafrefresh != null){
            stafrefresh.addEvent("click",function(){
                mdp.emailContent.refreshForm();
                mdp.emailContent.getForm(args);
            });
        }

    }

};

/* Add shareable functionality to all elements with class='shareable' */
window.addEvent("domready",function(){

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

    $$(".shareable").each(function(element){
        var elementTitle = element.getAttribute("title");
        var params = (elementTitle == null)? null : elementTitle.split("|");
        var preservedTitle = (params[0] == null) ? "" : params[0];
        if(preservedTitle == null){
            element.removeProperty("title");
        }
        else{
            element.setAttribute("title",preservedTitle);
        }
        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:Json.evaluate(element.getProperty('velocityFields')),
            cssClass:(params[5] == null || params[5] == "null") ? "" : params[5],
            pageDescription: (params[6] == null || params[6] == "null") ? "" : params[6] 
        };

        element.addEvent("click",function(){ mdp.emailContent.getForm(args); });
        element.removeProperty("velocityFields");

    });
});

