/* 
 * Created by David Galvis
 */

/**
 * Instanciates a new comment item on feed
 * @construct
 * @param int id Id of the switch
 * @param object settings 
 */
function ShareFeed(id, settings)
{
   var _this = this;
   this.id = id;
   jQuery.extend(this, settings);

   this.toggle = jQuery("#" + id);
   this.parent = this.toggle.parent('.homeNews');
   this.toggle.after("<div class='recommendationFeed' id='share_container_" + this.id + "'>" + trad_share_description + "</div>");
   this.container = jQuery("#share_container_" + this.id);
   this.container.css({display : 'none'});
   this.input = jQuery("<input class='share_search_input' id='share_input_" + this.id + "' />");
   this.send = jQuery('<button style="display:none" type="button">' + trad_share + '</button>');
   this.cancel = jQuery('<button style="display:inline" type="button">' + trad_cancel + '</button>');
   this.selection = jQuery("<div class='selection' style='display:block'></div>");
   this.textarea = jQuery("<textarea class='comment' style='width:99%; display:none'></textarea>");
   this.succesText = jQuery("<div class='success' style='display:none'>" + trad_sharing_finished +"</div>");

   if (!this.sendButton)
       this.send.css({display : 'none'});

   if (!this.cancelButton)
       this.cancel.css({display : 'none'});

   if (this.displayTextarea)
       this.textarea.css({display : 'block'});
   // Dom manipulaion
   this.selection.append(this.input);
   this.container.append(this.selection);
   this.container.append('<div style="clear:both;"></div><div>' + this.textareaLabel + '</div>');
   this.container.append(this.textarea);
   this.container.append(this.send);
   this.container.append(this.cancel);
   this.container.append(this.succesText);
   
   // Autocomplete people
   this.autocomplete = new HomeSearch("share_input_" + this.id, {
        settings : {uid : this.id, fid : this.fid},
        target : _this.targetAutocomplete,
        loadingClass : ''
    });

    if (this.allowEmail){
        this.input.keydown(function(event)
        {
            switch(event.keyCode)
            {
                case KEY.RETURN:
                case KEY.COMA:
                case KEY.SPACE:
                case KEY.TAB:
                    if (validEmail(_this.input.val())){
                        _this.share({
                            id_membre : _this.input.val(),
                            prenom : _this.input.val(),
                            nom : ''
                        });
                    }
                    break;
            }

            // Resizes inpput box dynamically
            _this.resizeInput();
        });
        this.input.blur(function(){
            if (validEmail(_this.input.val())){
                _this.share({
                    id_membre : _this.input.val(),
                    prenom : _this.input.val(),
                    nom : ''
                });
            }
        });
    }

   //Container css
   if (this.css != null)
       this.container.css(this.css);

   /**
    * Events
    */
   this.send.click(function()
    {
        _this.send.attr({disabled : true});
        _this.send.text(trad_sending);
        var choice = _this.serializeChoice();
        jQuery.post( _this.target,
            {selection : jQuery.toJSON(choice),
             data: jQuery.toJSON( _this.data ),
             fid : _this.fid,
             comments : _this.textarea.val()},
            function(){
                _this.send.attr({disabled : false})
                //_this.container.html(trad_sharing_finished);
                _this.succesText.show()
                //_this.container.addClass('success');
                if(typeof _this.success == 'function')
                    _this.success();
                setTimeout(function(){
                    _this.reset();
                    _this.hide();
                }, 5000);
            }
        );
    });

    this.cancel.click(function()
    {
        _this.reset();
        _this.hide();
    });

    /*
     * Custom button action
     */
    if (this.nextButton == true){
       this.next = jQuery('<button type="button">' + trad_share + '</button>');
       this.next.css({display : 'inline'});
       this.container.append(this.next);
       if (typeof this.nextButtonAction != ''){
           this.next.click(function(){
               _this.nextButtonAction();
           });
       }
    }

    this.selection.click(function(){
        _this.input.focus();
    });
   
   // Show/hide container
   this.toggle.click(function(){
      _this.container.show();
      _this.input.focus();
   });
}

ShareFeed.prototype =
{
    target : '/application/ajax/shareFeed.php',

    targetAutocomplete : '/application/ajax/autocomplete_share_feed.php',

    responseContainer : null,

    success : null,

    /**
     * CSS of the container
     */
    css : null,
    data : null,
    
    sendButton : true,
    
    cancelButton : true,

    nextButton : false,

    allowEmail : false,

    /** If set to true, a text area appears for custom text */
    displayTextarea : false,
    textareaLabel : '',
    
    show : function(){
        this.container.show();
    },

    hide : function(){
        this.container.slideUp();
    },
    
    reset : function(){
        this.send.attr({disabled : false, display:'none'});
        this.send.text(trad_share);
        this.input.val('');
        this.selection.children('.item').remove();
        this.textarea.val('');
        this.succesText.hide();
        //this.selection.remove('.item');
    },

    setTarget : function(target){
        this.target = target;
    },

    /**
     * Modifies send text value to the given param
     * @param string txt
     */
    setSendText : function (txt){
        this.send.html(txt);
    },

    setContainerHtml : function (html){
        this.container.html(html);
    },

    onSelect : null,

    /**
     * Customize on succes function (when the comment is posted)
     * @param function fnc
     */
    onSuccess : function(fnc){
        if (typeof fnc == 'function')
            this.success = fnc;
    },

    share : function(data)
    {
        var _this = this;
        var item = jQuery('<span class="item"><input type="hidden" value="' + data.id_membre + '"/>' + data.prenom + ' ' + data.nom + ' </span>');

        // Close
        var a = jQuery("<a href='javascript:void(0)'>x</a>");
        a.click(function(){
            item.remove();
            if (_this.serializeChoice().length == 0){
                _this.send.hide();
                _this.input.focus();
            }
        });

        item.append(a);
        if (this.sendButton)
            this.send.show();
        this.selection.show();
        this.input.before(item);
        this.autocomplete.input.val('');
        this.input.focus();
        this.input.css({
            width: 70
        });

        // Custom callback
        if(typeof this.onSelect == 'function')
            this.onSelect();
    },

    serializeChoice : function()
    {
        var choice = Array();
        this.selection.find(":hidden").each(function(){
            choice.push({
                idMember : this.value
            });
        });

        return choice;
    },

    setData: function( data )
    {
        this.data = data;
    },

    resizeInput : function (){
        var length = this.input.val().length;
        if (length > 5){
            this.input.css({
                width : this.input.val().length * 8
            });
        }
    }
};


