/**
 * Copyright (c) 2009 Mark S. Kolich
 * http://mark.koli.ch
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
*/

Kolich = {};
Kolich.root = "http://mark.koli.ch";

Kolich.isRoot = function(){
  try {
    return window.top.location.href.indexOf(Kolich.root) == 0;
  } catch(err) {
    return false;
  }
}

Kolich.Twitter = {};
Kolich.Twitter.div = {};
Kolich.Twitter.count = 0;
Kolich.Twitter.trigger = false;
Kolich.Twitter.tracker = "/tracker/Twitter/";
Kolich.Twitter.stream = "/twitter";
Kolich.Twitter.setup = function(){
  Kolich.Twitter.div = $("#lifestream");
  Kolich.Twitter.load();
  Kolich.Twitter.div.click(function(e){
    var url = encodeURIComponent(self.location.href);
    $.get(Kolich.Twitter.tracker+"?"+url);
    if(e.target.tagName!="A"){
      if(Kolich.Twitter.count<4){
        Kolich.Twitter.div.slideUp("fast",Kolich.Twitter.load);
      }
      else {
        alert("Dude, are you serious?  Stop " +
               "refreshing my Twitter stream like " +
               "a mad-man.");
      }
    }
  });
}
Kolich.Twitter.load = function(){
  Kolich.Twitter.count += 1;
  var token = (Math.random()*100).toString();
  $.get(Kolich.Twitter.stream+"?r="+token.substr(3,8),function(d,s){
     Kolich.Twitter.div.slideUp("fast",function(){
       Kolich.Twitter.div.html(d).slideDown("fast");
     });
     if(!Kolich.Twitter.trigger){
        Kolich.Twitter.trigger = !Kolich.Twitter.trigger;
        setTimeout("Kolich.Twitter.clearTrigger()",20000);
     }
  }, "html");
}
Kolich.Twitter.clearTrigger = function(){
  Kolich.Twitter.count = 0;
  Kolich.Twitter.trigger = !Kolich.Twitter.trigger;
}

Kolich.Sharing = {};
Kolich.Sharing.tracker = "/tracker/Sharing/";
Kolich.Sharing.setup = function(){
  $("p.shareitem > a").click(function(ev){
    var rel = $(this).attr("sharewith");
    var url = encodeURIComponent(self.location.href);
    var title = encodeURIComponent($("title:first").html());
    rel = rel.replace("%u",url);
    rel = rel.replace("%t",title);
    $.ajax({
      type:"GET",
      url:Kolich.Sharing.tracker+"?"+rel,
      complete:function(req,status){
        window.top.location.href = rel;
      }
    });    
    return false;
  });
}

Kolich.Translate = {};
Kolich.Translate.google = "http://translate.google.com/translate?u=%u&sl=en&tl=%tl";
Kolich.Translate.tracker = "/tracker/Translate/";
Kolich.Translate.setup = function(){
  $("p.translateflag").click(function(e){
    var gT = Kolich.Translate.google;
    var href = encodeURIComponent(window.location.href);
    var tl = $(this).attr("tl");
    gT = gT.replace("%u",href).replace("%tl",tl);
    $.ajax({
      type:"GET",
      url:Kolich.Translate.tracker+tl+"/?"+href,
      complete:function(req,status){
        window.top.location.href = gT;
      }
    });
  });
}

Kolich.Helpful = {};
Kolich.Helpful.tracker = "/tracker/Helpful/";
Kolich.Helpful.setup = function(){
  $("#helpful input:button").click(function(e){
    var href = encodeURIComponent(window.location.href);
    var feedback = $(this).attr("feedback");
    $.get(Kolich.Helpful.tracker+feedback+"/?"+href,function(r,s){
        var resp = "Thank you for your feedback!";
        if(feedback=="no"){
          resp = "Hmmm, OK, thanks for your feedback. Instead of just clicking No and bailing, maybe you could rise to the challenge and send me a direct message below to explain why this post wasn't helpful to you?";
        }
        $("#helpful-content").html(resp);
    });
  });
}

Kolich.SearchProvider = {};
Kolich.SearchProvider.tracker = "/tracker/SearchProvider/";
Kolich.SearchProvider.setup = function(){
  $("a[engineXML]").click(function(ev){
    var xml = $(this).attr("engineXML");
    var icon = $(this).attr("icon");
    var provider = $(this).attr("provider");
    var cat = $(this).attr("cat");
    var href = encodeURIComponent(window.location.href);
    Kolich.SearchProvider.addEngine(xml,icon,provider,cat);
    // IE dosen't like it when you trigger the provider install
    // on an ajax callback. So we trigger the installer then
    // ping the tracker service.
    $.ajax({
      type:"GET",
      url:Kolich.SearchProvider.tracker+"?"+href
    });    
    return false;
  });
}
Kolich.SearchProvider.addEngine = function addEngine(xml,icon,provider,cat){
  if((typeof window.sidebar=="object")&&(typeof window.sidebar.addSearchEngine=="function")){
   window.sidebar.addSearchEngine(xml,icon,provider,cat);
  }else{
   try{
    window.external.AddSearchProvider(xml);
   }catch(x){
    if(70==(x.number&0xFFFF)){
      alert("For security reasons, you must use the mouse\n(or the Enter key) to click the Install button.");
    }else{
      alert("Unable to add search provider. [" + (x.number & 0xFFFF) + "]");
    }
    return false;
  }
 }
}

Kolich.Comment = {};
Kolich.Comment.messaging = "/messaging";
Kolich.Comment.maxLength = 400;
Kolich.Comment.success = "SUCCESS";
Kolich.Comment.setup = function(){
  $("#comment-box input[type='text']").mouseover( function(){$(this).focus();} );
  $("#comment-box textarea").unbind().bind("keyup",function(e){
    Kolich.Comment.adjustRemaining();
  });
  $("#comment-box input[type='button']").click(function(e){
    var val = $("#comment-box textarea").val();
    var size = val.length;
    if(size>Kolich.Comment.maxLength){
      $("#comment-box .error").html("Sorry, your message is too long. Please reduce the length of your message and try again.").slideDown("fast");
    }
    else {
      Kolich.Comment.send( $("#comment-box #kolich-name").val(),
      $("#comment-box #kolich-email").val(), location.href, $("title:first").html(), val);
    }
  });
}
Kolich.Comment.adjustRemaining = function(){
  var val = $("#comment-box textarea").val();
  var size = val.length;
  var max = Kolich.Comment.maxLength;
  $("#comment-box #remaining").html(((max-size)>0)?(max-size):((max-size)*-1));
  $("#comment-box #remaining-status").html((size>max)?"too many":"remaining");
  if(size>max){
    $("#comment-box p.remain").addClass("toomany");
  }
  else {
    $("#comment-box p.remain").removeClass("toomany");
  }
}
Kolich.Comment.send = function(name,email,page,title,msg){
  var msgs = [];
  msgs.push( {name:name,email:email,message:msg,title:title,page:page} );
  $("#comment-box input[type='button']").attr("disabled","disabled");
  $.post( Kolich.Comment.messaging,
    { payload: JSON.stringify(msgs) },
    function(r){
      if(r.status==Kolich.Comment.success){
        $("#comment-box").slideUp("fast",function(e){$("#comment-box").slideDown("fast").html(r.response);});
      }
      else {
        $("#comment-box .error").html(r.response).slideDown("fast");
        $("#comment-box input[type='button']").removeAttr("disabled");
      }
    },"json");
}

Kolich.Beacon = {};
Kolich.Beacon.url = "/beacon";
Kolich.Beacon.idx = 1;
Kolich.Beacon.max = 90;
Kolich.Beacon.interval = 30*1000;
Kolich.Beacon.ping = function(){
  var token = (Math.random()*100).toString().substr(3,8);
  var url = encodeURIComponent(self.location.href);
  $.ajax({
    type: "GET",
    url: Kolich.Beacon.url+"?u="+url+"&t="+token,
    error: function(xhr){ },
    success: function(){
      if(Kolich.Beacon.idx<Kolich.Beacon.max){
        setTimeout("Kolich.Beacon.ping()",Kolich.Beacon.interval);
        Kolich.Beacon.idx++;
      }
    }
  });
}
Kolich.Beacon.setup = Kolich.Beacon.ping;

Kolich.Selector = {};
Kolich.Selector.url = "/beacon";
Kolich.Selector.send = function(){
  // TODO
}
Kolich.Selector.getSelected = function(){
  var t = '';
  if(window.getSelection){
    t = window.getSelection();
  }else if(document.getSelection){
    t = document.getSelection();
  }else if(document.selection){
    t = document.selection.createRange().text;
  }
  return t;
}
Kolich.Selector.setup = function(){
  $(document).bind("mouseup",function(ev){
    
  });
}

// jQuery sets everything up when the DOM is ready.
$(document).ready(function(){
  (new Image).src="http://mark.koli.ch/favicon.ico";
  /*
  try {
    if((window.top !== window.self) && !Kolich.isRoot()) {
      window.top.location = window.self.location;
    }
  } catch (err) { }
  */
  if(Kolich.isRoot()){
    Kolich.Twitter.setup();
    Kolich.Sharing.setup();
    Kolich.Translate.setup();
    Kolich.Helpful.setup();
    Kolich.Comment.setup();
    Kolich.SearchProvider.setup();
    //Kolich.Beacon.setup();
    //Kolich.Selector.setup();
  }
});
