/*
 * JTip
 * By Cody Lindley (http://www.codylindley.com)
 * Under an Attribution, Share Alike License
 * JTip is built on top of the very light weight jquery library.
 */

//on page load (as soon as its ready) call JT_init
//silnet.pl - jezeli link ma postac #aaa to tresc do tipa jest pobierana z #aaa
//$(document).ready(JT_init);

function JT_init()
{
  $("a.jTip").map(function(){
    if($(this).attr("href").match(/^base64:(.+)$/))
    {
      tmp = $(this).attr("href").match(/^base64:(.+)$/)[1];
      $(this).attr("href", JT_base64(tmp));
    }
  });
  $("a.jTip").click(function(){
    if(!$(this).attr("id"))
    {
      tmp = new Date;
      $(this).attr("id","jTip_"+tmp.getTime());
    }
    JT_show($(this).attr("href"),$(this).attr("id"),$(this).attr("title"));
    $("body").data("jt_init",true);
    return false;
  });
  $("body").click(function() {
    if($("body").data("jt_init")){
      $('#JT').remove();
      $("body").data("jt_init",false);
      return false;
    }
    return true;
  });
}

function JT_show(url,linkId,title) {
  if(title == false)title="&nbsp;";
  var de = document.documentElement;
  var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
  var hasArea = w - getAbsoluteLeft(linkId);
  var clickElementy = getAbsoluteTop(linkId) - 3; //set y position
  
  var queryString = url.match(/\??([^\?]+)?$/,'')[1];
  //var queryString = url.replace(/^[^\?]+\??/,'');
  var params = parseQuery( queryString );
  if(params['width'] === undefined){params['width'] = 250};
  if(params['link'] !== undefined){
  $('#' + linkId).bind('click',function(){window.location = params['link']});
  $('#' + linkId).css('cursor','pointer');
  }
  
  if(hasArea>((params['width']*1)+75)){
    $("body").append("<div id='JT' style='width:"+params['width']*1+"px'><div id='JT_arrow_left'></div><div id='JT_close_left'>"+title+"</div><div id='JT_copy'><div class='JT_loader'><div></div></div>");//right side
    var arrowOffset = getElementWidth(linkId) + 11;
    var clickElementx = getAbsoluteLeft(linkId) + arrowOffset; //set x position
  }else{
    $("body").append("<div id='JT' style='width:"+params['width']*1+"px'><div id='JT_arrow_right' style='left:"+((params['width']*1)+1)+"px'></div><div id='JT_close_right'>"+title+"</div><div id='JT_copy'><div class='JT_loader'><div></div></div>");//left side
    var clickElementx = getAbsoluteLeft(linkId) - ((params['width']*1) + 15); //set x position
  }
  
  $('#JT').css({left: clickElementx+"px", top: clickElementy+"px"});
  $('#JT').show();
  if(url.match(/^#/))
    $('#JT_copy').html($(url).html());
  //Optymalizacja powtorzonych odwolan
  else if($("#"+linkId).attr("JT_data"))
    $('#JT_copy').html( $("a#"+linkId).attr("JT_data") )
  else
  {
    //$('#JT_copy').load(url);
    //Optymalizacja powtorzonych odwolan
    $("body").attr("JT_data",linkId);
    $.ajax({
      "url": url,
      "cache": true,
      "dataType": "html",
      "success": function(data, textStatus, XMLHttpRequest) {
        $('#JT_copy').html(data);
        //Optymalizacja powtorzonych odwolan
        linkId = $("body").attr("JT_data");
        $("a#"+linkId).attr("JT_data",data);
        $("body").removeAttr("JT_data");
        $("a.jTip[href='"+$("a#"+linkId).attr("href")+"']").attr("JT_data",data);
      }
    });
  }

}

function getElementWidth(objectId) {
  x = document.getElementById(objectId);
  return x.offsetWidth;
}

function getAbsoluteLeft(objectId) {
  // Get an object left position from the upper left viewport corner
  o = document.getElementById(objectId)
  oLeft = o.offsetLeft            // Get left position from the parent object
  while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
    oParent = o.offsetParent    // Get parent object reference
    oLeft += oParent.offsetLeft // Add parent left position
    o = oParent
  }
  return oLeft
}

function getAbsoluteTop(objectId) {
  // Get an object top position from the upper left viewport corner
  o = document.getElementById(objectId)
  oTop = o.offsetTop            // Get top position from the parent object
  while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
    oParent = o.offsetParent  // Get parent object reference
    oTop += oParent.offsetTop // Add parent top position
    o = oParent
  }
  return oTop
}

function parseQuery ( query ) {
   var Params = new Object ();
   if ( ! query ) return Params; // return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) continue;
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function blockEvents(evt) {
              if(evt.target){
              evt.preventDefault();
              }else{
              evt.returnValue = false;
              }
}


function JT_base64(input) {
   var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
         output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
         output = output + String.fromCharCode(chr3);
      }
   } while (i < input.length);

   return output;
}

