
jk = {};
$(document).ready(function() {
  jk.uid = 0;
  jk.ga = _gat._getTracker('UA-18307662-1');
  
  if (!"".trim) {
    String.prototype.trim = function() {
      return this.replace(/^\s*/, "").replace(/\s*$/, "");
    }
  }
  
  jk._grabContent();
  
  $('#search').focus().select();
  jk._recenter('#inputBox');
  $(window).resize(function() { jk._recenter('#inputBox'); });
  
  jk._setupSearchHandlers();
  
  $('a[title]').simpleTip();
  
  // Add a routine to show example searches if no activity yet
  setTimeout(function() {
    $('#searchHelp').fadeIn();
  }, 3000);
});

jk.__ignoreWords = ['the', 'a', 'an', 'i', 'we', 'you', 'can', 'it', 'that', 'those', 'these', 'them', 'to', 'and', 'or', 'is', 'am', 'are', 'be', 'have', 'do', 'as', 'at', 'in', 'do', 'by', 'for', 'of', 'so', 'who', 'what', 'where', 'when', 'why', 'how'];
jk.doSearch = function(q) {
  q = (q)?(''+q):'';
  q = q.replace(/(?:\?|\.|\!|\,|\-|\'|\")/g, '').trim();
  var w = q.toLowerCase().split(' ');
  
  if (/riley\s+bear/i.test(q)) { $('body').css('background-image', 'url("images/dawgs.jpg")'); }
  
  jk._clearResults();
  if (q.length < 1) {
    $('#searchResults').html("<p>Looks like you didn't type in a search query...</p>");
    return;
  }
  
  // Remove ignored words
  var wi;
  for (var i=0, l=jk.__ignoreWords.length; i<l; ++i) {
    wi = $.inArray(jk.__ignoreWords[i], w);
    if (wi > -1) {
      w.splice(wi, 1);
    }
  }
  
  // Score the content
  var sc = [];
  $.each(jk.content, function(i) {
    var s = 0;
    s = $.score(this.title + ' ' + $(this.content).text(), q);
    
    // score tags
    var tg = this.tags;
    var st = 0;
    if (tg.length > 0) {
      for (var i=0, l=w.length; i<l; ++i) {
        if (w[i].length < 1) { continue; }
        if (tg.indexOf(w[i]) > -1) {
          st += 0.15;
        }
      }
    }
    s += st;
    
    if (s > 0.05) {
      sc.push([s, this]);
    }
  });
  
  // Sort results
  sc.sort(function(a, b){
    return b[0] - a[0];
  });
  
  if (sc.length < 1) {
    $('#searchResults').html("<p>Hmm, I didn't find anything, can you try again?</p>");
  } else {
    // show results
    var sr = $('#searchResults').append('<ol></ol>').find('ol');
    var pt, tm, ti, ct, hw;
    // limit to top 5
    for (var i=0, l=Math.min(5, sc.length); i<l; ++i) {
      
      // find and highlight preview text
      pt = '';
      ct = $(sc[i][1].content).text().replace(/\s+/g, ' ').trim();
      for (var j=0, l2=w.length; j<l2; ++j) {
        tm = ct.match(w[j], "i");
        if (tm) {
          ct = ct.replace(tm[0], '|{'+tm[0]+'}|');
        }
      }
      ct = ct.replace('}| |{', ' ');
      ct = ct.replace(/\}\|([a-z]+)/ig, '$1}|');
      ct = ct.replace(/([a-z]+)\|\{/ig, '$1}|');
      
      // find longest highlight and start there for preview
      ti = 0;
      hw = '';
      tm = ct.match(/\|\{.+?\}\|/);
      if (tm) {
        for (var j=0, l2=tm.length; j<l2; ++j) {
          if (tm[j].length > hw.length) {
            hw = tm[j];
          }
        }
        tm = ct.substr(0,ct.indexOf(hw)).match(/(?:[^\s]+\s){2}$/i);
        if (tm) {
          ti = ct.indexOf(tm[0]+hw);
        }
      }
      
      pt = ct.substr(ti, 70);
      if (pt.length >= 70) { pt += '...'; }
      if (ti > 0) { pt = '...'+pt; }
      pt = pt.replace(/\|\{/g, "<span class='resultHighlight'>");
      pt = pt.replace(/\}\|/g, "</span>");
      
      // add the node
      sr.append("<li id='result_"+sc[i][1].id+"'><span class='resultTitle'>"+sc[i][1].title+"</span><span class='previewText'>"+pt+"</span></li>")
        .find('li:last')
        .click(function() {
          var c = jk.content[Number($(this).attr('id').substr(7))];
          jk.addContentDiag(c.content, c.title, c.id);
          return false;
        })
        .hover(
          function() { $('#searchResults li').removeClass('searchHover'); $(this).addClass('searchHover'); },
          function() { $(this).removeClass('searchHover'); }
        );
    }
  }
}

jk._clearResults = function() {
  $('#searchResults').find('li, ol, p').remove();
}

jk.__currQuery = '';
jk.__searchTimeout = null;
jk._setupSearchHandlers = function() {
  $('#search')
    .click(function() {
      $('#inputBox').css('z-index', 600);
      return false;
    })
    .keyup(function(e) {
      // wait for more input for efficiency of search
      clearTimeout(jk.__searchTimeout);
      var input = this;
      jk.__searchTimeout = setTimeout(function() {
        if (input.value.length > 2 && jk.__currQuery != input.value) {
          jk.__currQuery = input.value;
          jk.doSearch(input.value);
        }
      }, 400);
      
      if (this.value.length < 1) {
        jk._clearResults();
      }
      
      // go through the list on arrow keys, select on enter
      if (e.keyCode == 40 || e.which == 40) {
        var n = $('li.searchHover').removeClass('searchHover').next();
        if (n.length < 1) {
          n = $('#searchResults li:first');
        }
        n.addClass('searchHover');
      }
      if (e.keyCode == 38 || e.which == 38) {
        var n = $('li.searchHover').removeClass('searchHover').prev();
        if (n.length < 1) {
          n = $('#searchResults li:last');
        }
        n.addClass('searchHover');
      }
      if (e.keyCode == 13 || e.which == 13) {
        var n = $('li.searchHover').removeClass('searchHover');
        if (n.length == 1) {
          var c = jk.content[Number(n.attr('id').substr(7))];
          jk.addContentDiag(c.content, c.title, c.id);
          return false;
        }
      }
      
      // Clear input box on escape
      if (e.keyCode == 27 || e.which == 27) {
        this.value = '';
        jk._clearResults();
      }
    });
  
  $('#inputBox').click(function() {
    $(this).css('z-index', 600);
    $('#search').focus().select();
  });
  
  $('#e').click(function(e) {
    e.preventDefault();
    if (e.ctrlKey || e.metaKey) {
      var p = prompt('Wall-e?');
      $.ajax({url: 'pass.php', data: {pass: p}, dataType: 'json', success: function(d) { if (d.pass) { jk._doWall(); }}});
    }
  })
  
  $('.showSearch').live('click', function(e) {
    e.preventDefault();
    $('#inputBox').css('z-index', 600);
    $('#search').focus().select();
  });
  
  $('#closeAll').click(function(e) {
    e.preventDefault();
    $('.ui-dialog-content').dialog('close');
  });
  
  $(window).keyup(function(e) {
    if (e.ctrlKey && (e.keyCode == 13 || e.which == 13)) {
      $('#inputBox').css('z-index', 600);
      $('#search').focus().select();
    }
  });
  
  $('.contentLink').live('click', function(e) {
    e.preventDefault();
    
    var t = $(this).attr('href').substr(1).replace('_', ' ');
    var c;
    for (var i=0, l=jk.content.length; i<l; ++i) {
      if (jk.content[i].title == t) {
        c = jk.content[i];
        break;
      }
    }
    if (c) {
      jk.addContentDiag(c.content, c.title, c.id);
    }
  });
}

jk.addContentDiag = function(content, title, id) {
  title = (title)?title:'More Information';
  id = (id || id===0)?id:(++jk.uid);
  
  var n = $('#diag_'+id);
  if (n.length > 0) {
    n.dialog('open');
    setTimeout(function() {
      $('#inputBox').css('z-index', 400);
    }, 100);
    return;
  }
  
  jk.ga._trackPageview("/content/"+title.replace(' ', '_', 'g'));
  
  var d = $("<div id='diag_"+id+"' title='"+title+"'>"+content+"</div>")
            .dialog({
              width: 420,
              height: 330,
              position: [0,0],
              resizable: false,
              closeText: 'hide',
              modal: false,
              autoFocus: false,
              zIndex: 500,
              show: 'fade',
              hide: 'fade',
              close: function() {
                // if there are no dialogs open, focus on search box
                var od = $('.ui-dialog:visible');
                if (od.length < 1) {
                  $('#inputBox').css('z-index', 600);
                  $('#search').focus().select();
                }
              }
            });
  
  var x = Math.random() * ($(window).width() - 430);
  var y = Math.random() * ($(window).height() - 340);
  d.dialog('option', 'position', [Math.floor(x), Math.floor(y)])
   .find('a[title]').simpleTip().end()
   .parent()
     .find('.ui-dialog-titlebar-close')
       .attr('title', 'Close this content')
       .end()
     .mousedown(function() {
       $('#inputBox').css('z-index', 400);
     });
  
  setTimeout(function() {
    $('#inputBox').css('z-index', 400);
  }, 100);
  
  return d;
}

jk._doWall = function() {
    $('#walle').animate({left: 150}, {
      duration: 4000,
      complete: function() {
        $('#walle').animate({left: 400}, {
          duration: 5000,
          complete: function() {
            $('#eva').animate({left: 2000}, {
              duration: 9000,
              complete: function() {
                $('#eva').fadeOut().remove();
              }
            });
            $('#walle').animate({left: 700}, {
              duration: 5000,
              complete: function() {
                $('#walle').animate({left: 2000}, {
                  duration: 7000,
                  complete: function() {
                    $('#walle').fadeOut().remove();
                  }
                });
              }
            });
          }
        });
      }
    });
}

jk._recenter = function(n) {
  n = $(n);
  if (!n) { return; }
  var nh = n.height();
  var wh = $(window).height();
  var nw = n.width();
  var dw = $(document).width();
  var tp;
  if (nh + 20 > wh) {
    tp = 10;
  } else {
    tp = (wh / 2) - (nh / 2);
  }
  var lt;
  if (nw + 20 > dw) {
    lt = 10;
  } else {
    lt = (dw - nw) / 2;
  }
  
  n.css({
    top: (tp - 50)+'px',
    left: lt+'px'
  })
}

jk._grabContent = function() {
  jk.content = [];
  
  $('.jkBlock').each(function(i) {
    jk.content.push({
      id: i,
      title: $(this).find('h2').text().trim(),
      content: $(this).find('.content').html().trim(),
      tags: $(this).find('.tags').text().toLowerCase().trim()
    });
  });
}

