/*
 * 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.
 */

// URLDecode half of plugin for jQuery : http://plugins.jquery.com/project/URLEncode
$.extend({URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;
  while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);
  t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}
});

//on page load (as soon as its ready) call JT_init
$(document).ready(JT_init);

function JT_init(){
    // Modified to pass the help_text into the function directly using a.title,
    // rather than looking it up with another request.

    // Display tip whenever the form element has input focus.
    $("div.fieldWrapper input,"
        + "div.fieldWrapper textarea,"
        + "div.fieldWrapper select,"
        + "div.formfield input,"
        + "div.formfield textarea,"
        + "div.formfield select")
        .focus(function(){JT_showOnFocus(this.id)},function(){$('#JT').remove()})
        .blur(function(){$('#JT').remove()})
        .click(function(){JT_showTipReturnClick(this.id)});

    $("a.jTip")
        .hover(function(){JT_show(this.href,this.id,this.name,this.title)},function(){$('#JT').remove()})
        .click(function(){return false});
}

function JT_showTipReturnClick(id) {
    // HACK Enable clicking the multicheck options, but otherwise return false
    return id in {
        id_disbursementDate:1,
        id_purposes:1,
        id_eligibilities:1,
        id_otherServices:1
    };
}

function JT_showOnFocus(id) {
    /* Wrapper for JT_show:
     * convert field id into jTip link id
     * skip certain labels
    */
    var jt_link_id = "help_" + id;
    var jt_link = $("#" + jt_link_id);
    if (document.documentElement.clientWidth < 930) {
        //alert("Your screen is not wide enough to display the help text");
    } else if (jt_link.length > 0) {
	    JT_show(jt_link.attr("href"), jt_link_id, jt_link.attr("name"));
    }
}


function JT_show(url,linkId,title,help_text){
    // Modified Function to pass the description, rather than initiating another request to look it up
    var width = 375;
    var link = "#" + linkId;
    var width_re = /\?width=(\d+)$/;
    var width_match = url.match(width_re);
    if (width_match) width = parseInt(width_match[1]);
    if (!help_text) {
        var help_span = $("#span_" + linkId);
        if (help_span.length > 0) {
            // backward compatibility: show_formField uses a span for help text
            // Aside: is it possible to put a " (double quote) character in the help text?
            help_text = help_span.attr("title");
        } else {
            // TODO fix issue with literal % (percent) character in help text.
            help_text = url.replace(width_re, "").match(/ajax\/help-text\/(.*)/);
            help_text = $.URLDecode(help_text[1]);
        }
    }

	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

	if(hasArea>(width+75)){
		$("body").append("<div id='JT' style='width:"+width+"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:"+width+"px'><div id='JT_arrow_right' style='left:"+((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) - ((width*1) + 15); //set x position
	}

	$('#JT').css({left: clickElementx+"px", top: clickElementy+"px"});
	$('#JT').show();
	$('#JT_copy').html(help_text);
}

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;
              }
}
