﻿var BALA = {filter_on : true}

jQuery("document").ready(function(){
  if (AUTH_TOKEN){
    jQuery.ajaxSetup({
      data: {authenticity_token : AUTH_TOKEN}
    })
  }
  

  jQuery("li.filter div.notselected").live('click', function(){
    if (BALA.filter_on){
      jQuery(".promotable").show();
      var selected = jQuery("li.filter div.selected");
      jQuery("li.filter div.notselected").removeClass("notselected").addClass("selected");
      selected.removeClass("selected").addClass("notselected");
      BALA.filter_on = false;
      jQuery.cookie("_filter", "false");
    }
    else{
      jQuery(".promotable").hide();
      var selected = jQuery("li.filter div.selected");
      jQuery("li.filter div.notselected").removeClass("notselected").addClass("selected");
      selected.removeClass("selected").addClass("notselected");
      BALA.filter_on = true;
      jQuery.cookie("_filter", "true");
    }
  });
  
  if (jQuery.cookie("_filter") == "false") jQuery("li.filter div.notselected").click();
  
  jQuery(".vote-box ul li a").click(function(){
    var link_id = jQuery(this).parents("ul:first").get(0).id.substring(2);
    var votebox = jQuery(this).parents("ul:first")
    var url = (document.location).toString();

    if (link_id) {
      var isPlus = jQuery(this).hasClass("plus");
      /*if (isPlus)
        jQuery("ul#vn" + link_id + " li a.plus span").fadeOut(400);
      else
        jQuery("ul#vn" + link_id + " li a.minus span").fadeOut(400);*/
      jQuery.ajax({
        url: (isPlus ? "/links/up_by_one/" : "/links/down_by_one/") + link_id,
        type: "POST",
        dataType: "json",
        success: function(msg){
          if (msg){
            if (msg.message){
              votebox.children('li.votes').children("span").html(msg.message).fadeIn(800);
            }
            if (msg.negative){
              votebox.children("li").children('a.minus').children("span").html(msg.negative).fadeIn(800);
            }
            if (msg.positive){
              votebox.children("li").children('a.plus').children("span").html(msg.positive).fadeIn(800);
            }
            if ((msg.user)&&(url.indexOf("permlink") >= 0 )&&(msg.success)) {
              var voters = votebox.parents('div#links').children('div.extra-content').children('div.voters');
              voters.append('<a class=\''+ (isPlus ? "" : "red_vote") +'\' href=\"/users/' + msg.user + '\">' + msg.user + '</a>').fadeIn(800);
            }
          }
        },
        error: function(msg){
          if (msg && msg.responseText){
            jQuery("ul#vn" + link_id + " li.votes span").html(msg.responseText).fadeIn(800);
          }
        }
      })
      jQuery(this).parents("ul:first").get(0).id = '';
    }
  });
     
})

function getSelected(e) {
    if (document.selection) {
        e.focus();
        var range = document.selection.createRange();
        return range.text;
    } else {
        var length = e.textLength;
        var start = e.selectionStart;
        var end = e.selectionEnd;
        if (end == 1 || end == 2 && length != undefined) end = length;
        return e.value.substring(start, end);
    }
}

function setSelection(e, v) {
    if (document.selection) {
        e.focus();
        var range = document.selection.createRange();
        range.text = v;
    } else {
        var length = e.textLength;
        var start = e.selectionStart;
        var end = e.selectionEnd;
        if (end == 1 || end == 2 && length != undefined) end = length;
        e.value = e.value.substring(0, start) + v + e.value.substr(end, length);
        e.selectionStart = start + v.length;
        e.selectionEnd = start + v.length;
    }
    e.focus();
}

function formatStr(e, v) {
    var str = getSelected(e);
    if (str) setSelection(e, '<' + v + '>' + str + '</' + v + '>');
    return false;
}

function mtShortCuts(e) {
    e = e || event;
    if (!e || (!e.ctrlKey)) return;
    /* we have to add 64 to keyCode since the user hit a control key */
    var code = (e.keyCode) ? (e.keyCode + 64) :
               ((e.which) ? e.which : 0);
    var ch = String.fromCharCode(code);
    el = e.target || e.srcElement;
    if (el.nodeType == 3) el = el.parentNode; // Safari bug
    if (ch == 'A') insertLink(el, false);
    if (ch == 'B') formatStr(el, 'strong');
    if (ch == 'I') formatStr(el, 'em');
    if (ch == 'U') formatStr(el, 'u');
}

function insertLink(e, isMail) {
    var str = getSelected(e);
    var link = '';
    if (!isMail) {
        if (str.match(/^https?:/)) {
            link = str;
        } else if (str.match(/^(\w+\.)+\w{2,5}\/?/)) {
            link = 'http://' + str;
        } else if (str.match(/ /)) {
            link = 'http://';
        } else {
            link = 'http://' + str;
        }
    } else {
        if (str.match(/@/)) {
            link = str;
        }
    }
    var my_link = prompt(isMail ? 'Enter email address:' : 'Enter URL:', link);
    if (my_link != null) {
         if (str == '') str = my_link;
         if (isMail) my_link = 'mailto:' + my_link;
        setSelection(e, '<a href="' + my_link + '">' + str + '</a>');
    }
    return false;
}


// attaches the new window link to 
// function seturl(node) {
//  $(node).setAttribute("href", $(node).next('a').readAttribute('href'));
// }

$(document).live('keyup', function(e) {
     if (e.keyCode == Event.KEY_ESC && $('#modal-box').length > 0) {
       $('#modal-box').remove();
     }
});

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

