Array.prototype.search = function(t) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == t)
      return i;
  }
  return false;
}

Array.prototype.unique = function() {
    var a = [];
    var l = this.length;
    for(var i=0; i<l; i++) {
      for(var j=i+1; j<l; j++) {
        if (this[i] === this[j])
          j = ++i;
      }
      a.push(this[i]);
    }
    return a;
  };

Array.prototype.filter = function() {
    var f = [];
    for (var i = 0; i < this.length; i++) {
      if (false != this[i] || !isNaN(this[i]))
        f.push(this[i]);
    }
    return f;
  };

function isset(x) {
  return typeof window[x] === "undefined" ? false : true;
}

jQuery.fn.isChecked = function() {
  return $(this).attr('checked') == 'checked' ? true : false;
}

jQuery.fn.check = function() {
  $(this).attr('checked', 'checked');
}

jQuery.fn.uncheck = function() {
  $(this).removeAttr('checked');
}

jQuery.fn.isDisabled = function() {
  return $(this).attr('disabled') == 'disabled' ? true : false;
}

jQuery.fn.enable = function() {
  $(this).removeAttr('disabled');
}

jQuery.fn.disable = function() {
  $(this).attr('disabled', 'disabled');
}

jQuery.fn.isDisplayed = function() {
  var d = $(this).css('display');
  
  return !d || d.match(/none/i) ? true : false;
}

function startPlayer(video_clip) {
  flowplayer("player", {
    src: "/lib/fplayer/fplayer-3.2.7.swf",
    version: [9, 115],
    onFail: function()  {
      document.getElementById("player_msgs").innerHTML =
        "Hubo un problema al cargar el reproductor. " +
        "Por favor revisa si tienes instalado Flash", +
        "o actualízate a la última versión.";
    }
  }, {
    clip: video_clip
  });
}

String.prototype.cleanString = function(){
  return this.toLowerCase().replace(/[àáâãäå]/g,"a").replace(/æ/g,"ae").replace(/ç/g,"c").replace(/[èéêë]/g,"e").replace(/[ýÿ]/g,"y").replace(/[ùúûü]/g,"u").replace(/ñ/g,"n").replace(/[ìíîï]/g,"i").replace(/[òóôõöø]/g,"o").replace(/œ/g,"oe").replace(/[^\w-]/g, '');
}

function split(val) {
  return val.split(/\s*,\s*/);
}

function extractLast(term) {
  return split(term).pop();
}

Cookie = {
  put: function(name, value, days) {
    if (days == null) {
      days = 365
    }

    var date = new Date()
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000))
    var expires = "; expires=" + date.toGMTString()
    document.cookie = name + "=" + window.encodeURIComponent(value) + expires + "; path=/; domain=tutomax.com"
  },

  raw_get: function(name) {
    var nameEq = name + "="
    var ca = document.cookie.split(";")

    for (var i = 0; i < ca.length; ++i) {
      var c = ca[i]

      while (c.charAt(0) == " ") {
        c = c.substring(1, c.length)
      }

      if (c.indexOf(nameEq) == 0) {
        return c.substring(nameEq.length, c.length)
      }
    }

    return ""
  },
  
  get: function(name) {
    return this.unescape(this.raw_get(name))
  },
  
  remove: function(name) {
    Cookie.put(name, '', -1)
  },

  unescape: function(val) {
    return window.decodeURIComponent(val.replace(/\+/g, " "))
  },

  setup: function() {
    if (this.get("has_mail") == "1") {
      $("#has-mail-notice").show()
    }
  }
}

var ClearNoticeTimer;
function start_notice_timer() {
  if(ClearNoticeTimer)
    window.clearTimeout(ClearNoticeTimer);

  ClearNoticeTimer = window.setTimeout(function() {
		  $('#notice-container').fadeOut(100);
  }, 5000);
}

function notice(msg, initial) {
  if(initial) {
    var static_notice = $("#static_notice");
    if(static_notice.length > 0) {
      static_notice.html(msg);
      static_notice.show();
      return;
    }
  }

  start_notice_timer();
  $('#notice').html(msg);
  $('#notice-container').fadeIn(100);
}

function countInputChars(field_id, counter_id, limit) {
  var field = $('#' + field_id);
  if ( field.val().length >= limit ) {
    var cval = field.val();
    field.val( cval.substr(0, limit) );
  }
  if ( counter_id )
    $('#' + counter_id).html(field.val().length);
}

function maxlen(c, cntr, max) {
  if(c.val().length > max)
    c.val(c.val().substr(0, max));
  $(cntr).html(c.val().length);
}

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
 x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
 y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
 x=x.replace(/^\s+|\s+$/g,"");
 if (x==c_name)
   {
   return unescape(y);
   }
 }
}

User = {
  is_logged: function () {
    if (!Cookie.get("auth")) {
      notice("Debes ingresar para realizar esta acción");
      return false;
    }
    return true;
  }
}

Vote = {
  busy: false,
  object_type:null,
  object_id:null,
  vote:null,
  e:null,
  opp:null,
  
  vote_do:function(e) {
    if (this.busy)
      return false;
    
    notice('Votando...');
    
    this.e = e
    this.set_vote()
    this.set_opp()
    this.set_object_data()
    
    data = {vote:{
      object_type:Vote.object_type,
      object_id:Vote.object_id,
      vote:Vote.vote
    }}
    
    $.ajax({
      url:'/vote/vote/',
      data:data,
      success:function(r){
        if (r.success) {
          if (Vote.vote == 0) {
            Vote.e.removeClass('voted')
          } else {
            Vote.e.addClass('voted')
            Vote.opp.removeClass('voted')
          }
          notice('Voto guardado');
        } else {
          notice('No se pudo guardar el voto');
        }
        
        Vote.busy = false;
      }
    })
    
  },
  
  set_object_data: function() {
    vote_data = this.p.children('.vote-data')
    this.object_type = vote_data.attr('object_type')
    this.object_id = vote_data.attr('object_id')
  },
  
  set_vote: function() {
    if (this.e.hasClass('voted'))
      vote = 0
    else if (this.e.hasClass('up'))
      vote = 1
    else
      vote = -1
    
    this.vote = vote
  },
  
  set_opp: function(){
    cls = this.e.hasClass('up') ? '.down' : '.up'
    
    opp = this.e.parent().children(cls)
    
    if (!opp.length) {
      opp = this.e.parent().prev().prev().children(cls)
      this.p = this.e.parent().parent()
    } else
      this.p = this.e.parent()
    
    this.opp = opp
  }
}

$().ready(function(){
  $('.-bot.up').live('click', function(){
    Vote.vote_do($(this))
    return false;
  })
  $('.-bot.down').live('click', function(){
    Vote.vote_do($(this))
    return false;
  })
})

$().ready(function(){
  $('.tut-vote-up').click(function() {
    vote = Vote.parse('tut', $(this), true);
    
    Vote.prepare($(this), vote);
    return false;
  });

  $('.tut-vote-down').click(function() {
    vote = Vote.parse('tut', $(this));
    
    Vote.prepare($(this), vote);
    return false;
  });

  $('.cmt-vote-up').click(function() {
    vote = Vote.parse('cmt', $(this), true);
    
    Vote.prepare($(this), vote, true);
    return false;
  });

  $('.cmt-vote-down').click(function() {
    vote = Vote.parse('cmt', $(this));
    
    Vote.prepare($(this), vote, true);
    return false;
  });
});

Favorite = {
  prepare: function(type) {
    if (!User.is_logged())
      return false;
    data = {
      type: type,
      id: cmt_object_id
    }
    this.send(data);
  },
  
  send: function(data) {
    var msg = data.type == 'add' ? 'Agregando a favoritos':'Eliminando de favoritos';
    notice(msg);
    $.ajax({
      url: '/tutorial/favorito.json',
      data: data,
      type: 'POST',
      dataType: 'json',
      success: function(resp) {
        notice(resp.notice);
        Favorite.change_link(data.type);
      }
    });
  },
  
  change_link: function(type) {
    if(type == 'remove') {
      title = 'Agregar a favoritos';
      cls = 'add_fav';
      lnk = '+Favorito';
      lmnt = 'remove_fav';
    } else {
      title = 'Eliminar de favoritos';
      cls = 'remove_fav';
      lnk = '-Favorito';
      lmnt = 'add_fav';
    }
    new_lmnt = '<a href="#" title="'+title+'" class="'+cls+'">'+lnk+'</a>';
    $('.'+lmnt).replaceWith(new_lmnt);
  }
}

$().ready(function(){
  $('.add_fav').live('click', function(){
    Favorite.prepare('add');
  });
  $('.remove_fav').live('click', function(){
    Favorite.prepare('remove');
  });
});

Comment = {
  go: function() {
    this.show();
  },
  
  show: function() {
    $('#cmt_frm_cnt').toggle();
    $('#comment_body').focus();
  }
}

$().ready(function(){
  $('#create_cmt').click(function(){
    Comment.show();
    return false;
  });
  
  $('#cmt_frm_go').click(function(){
    Comment.go();
    return false;
  });
  
  $('.cmt_reply').live('click', function(){
    if (!User.is_logged())
      return false;
    
    var id = $(this).attr('class').replace('cmt_reply ', '');
    
    var cmt_form = $('#comment_'+id+' > * > * > .cmt_reply_form');
    if(cmt_form.length > 0) {
      cmt_form.toggle();
      cmt_form.children('form').children('textarea').focus();
      return false;
    }
    var rbox = '<div class="cmt_reply_form" style="text-align:center;">'+
        '<form action="/comentario/crear/" method="post">'+
          '<input type="hidden" name="return_url" value="'+cmt_return_url+'" />'+
          '<input type="hidden" name="comment[obj_type]" value="'+cmt_belongs_to+'" />'+
          '<input type="hidden" name="comment[parent_id]" value="'+id+'" />'+
          '<input type="hidden" name="comment[obj_id]" value="'+cmt_object_id+'" />'+
          '<textarea rows="5" name="comment[body]" style="width:600px"></textarea>'+
          '<p><span style="float:right"><input type="submit" value="Enviar" /></span></p>'+
        '</form>'+
      '</div>';
    $('#comment_'+id+' > * > * > .right').after(rbox);
    $('#comment_'+id+' > * > * > .cmt_reply_form').children('form').children('textarea').focus();
    return false;
  });
});

_Json = {
  dEr: 'Error: No se pudo conectar con el servidor',
  isResp: function(obj) {
    try {
      resp = jQuery.parseJSON(obj.responseText);
      return resp;
    } catch (e) {
      return false;
    }
  },
  dEF: function(r) {
    if ((resp = this.isResp(r)) && resp.error)
      notice(resp.reason);
    else
      notice(this.dEr);
  }
}

$.ajaxSetup({
  type: 'POST',
  dataType: 'json',
  error: function(r) {
    // alert(r.responseText);
    _Json.dEF(r);
  }
});

VideoLights = {
  on: true,
  toggle: function() {
    if (this.on) {
      $("#the_lights").fadeIn(100);
      $('.light').removeClass('on');
      $('.light').addClass('off');
      this.on = false;
    } else {
      $("#the_lights").fadeOut(100);
      $('.light').removeClass('off');
      $('.light').addClass('on');
      this.on = true;
    }
  }
}
Tutorial = {
  id:null,
  voting: false,
  vote:function(e){
    if (!User.is_logged())
      return;
    
    if (this.voting)
      return;
    this.voting = true;
    if (e.hasClass('up')) {
      vote_up = true;
      ee = $('.-bot.down');
    } else {
      vote_up = false;
      ee = $('.-bot.up');
    }
    
    remove_vote = e.hasClass('voted') ? true : false;
    
    if (vote_up)
      counter_vote = ee.hasClass('voted') ? true : false;
    else
      counter_vote = ee.hasClass('voted') ? true : false;
    
    if (remove_vote)
      vote = 0;
    else {
      vote = vote_up ? 1 : -1;
    }
    
    $.ajax({
      url:'/tutoriales/votar.json',
      data:{
        vote:vote,
        tutorial_id:Tutorial.id

      }, success:function(){
        if (remove_vote) {
          e.removeClass('voted');
        } else {
          e.addClass('voted');
          if (counter_vote)
            ee.removeClass('voted');
        }
        Tutorial.voting = false;
      }
    });
  }
}

$().ready(function() {
  $('#notice-container').click(function(){
    $(this).fadeOut(100);
  });
  
  $("a.need-signup").click(function() {
    notice("Debes ingresar para realizar esta acción");
    return false;
  });

  $('div.thead').click(function(){
    $(this).next().slideToggle(100);
  });

  $('a.disabled').click(function(){
    return false;
  });

  $('.show_spam').click(function() {
    $(this).parent().hide();
    $(this).parent().parent().find('.cmt_body').show();
  });

  $('#comments-pagination button').live('click', function(){
    cmt_page = $(this).html();
    $('#comments').load('/comentario/?id=' + cmt_object_id + '&type=' + cmt_belongs_to + '&no_layout=1&page=' + cmt_page);
  });
  
  $('body').append('<div id="the_lights"></div>');
  
  /*Video Lights*/
  $('.light').click(function(){
    VideoLights.toggle();
  });
  $("#the_lights").click(function(){
    VideoLights.toggle();
  });
});
