/*
	jquery.comments.js
	Ver 2.0

	Uso:
		$( identificador ).comments(opciones);

*/
var COMMENTS = {};

(function($){

  var createThread = function(spec){
    var baseQuery, thread, config = {}, user = {};

    $.extend(config, spec);

    if(config.thread){
      config.container = config.container.find(config.thread);
    }

    config.sortBy = 'byDate';

    baseQuery = 'url=' + config.url + 
      '&divid=' + config.id + 
      '&forum=' + config.forum;

    var query = function(data){
      var prop, ext = '';
      for(prop in data){
        if(data.hasOwnProperty(prop)){
          ext += '&' + prop + '=' + escape( data[prop].toString() );
        }
      }

      return function(){
        $.ajax({
          type: 'GET',
          url: config.handler,
          data: baseQuery + ext,
          cache: false,
          dataType: 'jsonp'
        });
      }

    };

    var inputForm = function(commentId){
      var opts, form, button;
			var textarea = $('<textarea></textarea>').attr('rows', 10);

      opts = {_method:'PUT'};
      if(commentId){
        opts.comment_id = commentId;
      }

      if(user.uid){
        button = $('<button></button>').
          html('Comentar').
          click(function(){
            opts.comment_body = textarea.val();
            query(opts)();
            }) 
      }else{
        textarea.attr('disabled', 'disabled');
          button = $('<button></button>').
          html('Iniciar sesi&oacute;n para comentar').
          click(function(){
            url = window.location.toString().replace(/^http:\/\//, '');
            window.location = 'http://comunidad.multimedios.com/'
							+ 'user?external=1&redirect=' + url;
          });
      }

      form = $('<div>').attr('class', 'mmc-form');
      if(user.uid){
        if(!user.commentCount){
          user.commentCount = 0;
        }

        form.append( $('<div></div>').addClass('mmc-user').
          append( $('<img>').attr('src', user.picture) ).
          append( $('<h3></h3>').html( user.name ) ).
          append( 'Puntos: ' + user.votes).
          append( ' Comentarios: ' + user.commentCount)
        );
      }

      form.
        append( $('<label></label>').html('Comentario')).
        append(textarea).
        append(button);

      return form;
    };

    function formatComment(comment){
      var  out, children, actions, i;

      if(comment.children && comment.children.length){
        //Se duplica sort en build
        thread.sort(sort[config.sortBy]);
        children = $('<div></div>').attr('class', 'mmc-children');
        for(i in comment.children){
          children.append(
            formatComment(comment.children[i])
            );
        }
      }

      if(!user.isAdmin && comment.status !== 0 
				&& (!children || !children.html())){
        return '';
      }

      out = $('<div></div>').addClass('mmc-comment');
      actions = $('<div></div>').addClass('mmc-actions');

      function addButtons(){
        actions.html( $('<button></button>').html('Responder').
          addClass('mmc-first').
          click(function(){
            actions.html(
              inputForm(comment.cid).
              append( $('<button></button>').
                html('Cancelar').
                addClass('mmc-cancel').
                click( addButtons )
                )
              );
            actions.find('textarea').focus();
            })
          );

      if(user.uid === comment.uid && !user.isAdmin){
        actions.append( $('<button>').
            html('Eliminar').
            click( query({
              _method: 'DELETE',
              comment_id: comment.cid
              })
            )
          );
      }else if(user.uid !== comment.uid && !comment.voted){
        actions.append( $('<button></button>').
            html('Me gusta').
            click(
              query({
                _method: 'VOTE',
                comment_id: comment.cid
              })
            )
          );

      }

      if(user.isAdmin && comment.status !== 0){
        out.addClass('mmc-deleted');

        actions.append($('<button></button>').
          html('Aprobar').
          click( query({
            _method: 'EDIT',
            comment_id: comment.cid,
            'status': 0
            })
          )
        );
      }else if(user.isAdmin){
        actions.append($('<button></button>').
            html('Eliminar').
            click( query({
              _method: 'EDIT',
              comment_id: comment.cid,
              'status': 3
            })
          )
        );
      }

    }//addButtons

    if(user.uid){
      addButtons();
    }

    if(!user.isAdmin && comment.status === 2){
      comment.body = 'Comentario Eliminado';
    }


    return out.
      append( $('<img>').attr('src', comment.userpic || config.defaultPic) ).
      append( $('<h3></h3>').html( comment.username ) ).
      append( comment.body || comment.title ).
      append( actions ).
      append( children );

    };

    function count(thread){
      var i, total = 0;

      if(thread && thread.length){
        for(i in thread){
					//Solo cuenta los activos
					if(thread[i].status === 0){
						total += 1;
					}
					//Busca comentarios activos
					//dentro de todos
          if(thread[i].children && thread[i].children.length){
            total += count(thread[i].children);
          }
        }
      }

      return total;
    };


    var sort = {
      "byVotes": function(a, b){
        var diff = 0;
        diff = (a.votes < b.votes) ? 1 : -1;
        return diff;
      },
      "byDate": function (a, b){
        var diff = 0;
        diff = (a.created > b.created) ? 1 : -1;
        return diff;
      }
    };

    return {
      'get': function(){
        query({_method: 'GET_THREAD'})();

        return this;
      },
        'build': function build(){
          var i;
          config.container.
            html(' ').
            append(inputForm());

          if(config.message){
            config.container.append( 
                $('<div></div>').addClass('mmc-message').
                html(config.message)
                );
								config.message = '';
            setTimeout("$('.mmc-message').fadeOut(1600, 'linear');"
						 + "config.message = ''", 5000); 
          }

          if(config.error){
            config.container.append( 
                $('<div>').addClass('mmc-errormessage').
									html(config.error)
                );
								config.error = '';
            setTimeout("$('.mmc-errormessage').fadeOut(1600, 'linear')", 5000); 
          }

          config.container.append(
              $('<select>').append(
                $('<option>').attr('value', 'byDate').
                html('Ordenar por fecha')
                ).append( 
                  $('<option>').attr('value', 'byVotes').
                  html('Ordenar por votos')
                  ).change(function(element){
                    config.sortBy = $(this).find('option:selected').
											attr('value') ;
                    build();
                    })
              ).find('option[value=' + config.sortBy +']').
							attr('selected', 'selected');

          if(thread){
            //Sort se dupllica en formatComment
            thread.sort(sort[config.sortBy]);

            for(i in thread){
              config.container.
                append(formatComment(thread[i]));
            }

            if(config.countTag){
              config.countTag.html( count(thread) );
            }
          }

          return this;
        },
        'update': function(resp){
          thread = resp.thread;
          if(resp.user){
            user = resp.user;
            if(!user.isAdmin){
              user.isAdimn = false;
            }
          }

          return this;
        },
        'message': function(message){
          if(message === 'ADD_OK'){
            config.message = 'Comentario enviado';
          }else{
            config.message = message;
          }

          return this;
        },
        'setCountTag': function(element){
          config.countTag = element;
        },
        'error': function(resp){
          config.error = resp.message;

          return this;
        }

    };
  };

  $.fn.comments = function(spec){
    var config = {
      'url': window.location.href,
      'handler': 'http://comunidad.multimedios.com/community_tools/api.php',
      'defaultPic': 'http://comunidad.multimedios.com/'
				+'media/imagecache/miniavatar/pictures/default.png',
      'forum': null,
      'container': null,
      'thread': null,
      'count': null,
      'onInit': function(){}
    };

    if(spec){
      $.extend(config, spec);
    }


    this.each(function(index, element){
        var container = $(element), countTag;

        //Corremos las funciones externas
        var extra = config.onInit.call(container);
        $.extend(config, extra);
        //Identificar contenedor por una ID
        if(container.attr('id')){
        config.id = container.attr('id');
        }else{
        do{
        index += 1;
        config.id = 'mmcId' + index;
        }while(document.getElementById('#' + config.id));
        container.attr('id', config.id)
        }


        if(config.forum){
        config.container = container;
        COMMENTS[config.id] = createThread(config);
        COMMENTS[config.id].get();
        if( config.count && container.find(config.count)){
          countTag = $('<span/>');
          container.find(config.count).append(countTag);
          COMMENTS[config.id].setCountTag(countTag);
        }
        }else{
          container.html('No hay foro definido');
        }
    });

    return this;
  };

})(jQuery)

function commentCallback(response){
  var thread;
  if( response.status === 0  && COMMENTS[response.divid]){
    if(response.thread){
      COMMENTS[response.divid].update(response).build();
    }else{
      COMMENTS[response.divid].message(response.message).build().get();
    }

  }else if(COMMENTS[response.divid]){
    COMMENTS[response.divid].message(response.message).build();
  }
}

