﻿/*************************************************************************
Description:  ProNeeds Core JS Library (using JQuery)
Created:      10/10/2008
Author:       Nick Elliott - Presentation Team
Copyright:    Vertex Financial Services 2008, All Rights Reserved.
**************************************************************************/

/******************** GLOBAL VARIABLES ************************/
var toolTips = new Array();

/******************** DOCUMENT READY **********************/
$(function() {
	initTooltips();
	initMandatoryIcons();
	initWrappers();
});

function pageLoad() {
	$("#divOuter").after($(".autocomplete_completionListElement"));
}

/******************** FUNCTIONS **********************/

function initMandatoryIcons() {

    $(".mandatoryRow").each(function() {
        var thisLabel = $(this).children("label");
        if ((thisLabel) && (!$(this).children("span").hasClass('mandatoryIndicator'))) {
            thisLabel.css({ paddingRight: "0px" });
            thisLabel.after("<span class=\"mandatoryIndicator\"><img src=\"images/forms/mandatoryIndicator.gif\" alt=\"This question is mandatory\" title=\"This question is mandatory\" /></span>");
        }
    });
}

/***-----------------------------------------------***/

function initWrappers() {
	$(".divWrapper").each(function(){
		this.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=25)";
		this.style.opacity=0.25;
	})
	$("#divUpdateProgressWrapper").each(function() {
		this.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=25)";
		this.style.opacity=0.25;
	})
	$('.divWrapper').bgiframe()
}
/***-----------------------------------------------***/
function initTooltips() {

  var toolTipID, toolTipText, associatedControlID, initType, tabIndex;  
  jQuery.each(toolTips, function(i) { //loop thru tooltip array created by ToolTip.vb

      toolTipID = this[0];
      toolTipText = this[1];
      associatedControlID = '#' + this[2];
      initType = this[3].toLowerCase();
      tabIndex = this[4];
      initTooltip(toolTipID, toolTipText, associatedControlID, initType, tabIndex); //add show event handlers
  })
}

/***-----------------------------------------------***/
function initTooltip(toolTipID, toolTipText, associatedControlID, initType, tabIndex) {

  var input = $(associatedControlID), inputWidth = input.width(), inputHeight = input.height(), inputOffset = input.offset(), iconTitle = "", inputType, tableTest;

  if (input.length > 0) {   
    var inputTag = input.get(0).tagName.toLowerCase();
    
    switch (inputTag) {
      case 'input': inputType = input.attr("type"); break;
      case 'select': inputType = "select"; break;
      case 'a': case 'span': case 'div': inputType = "link"; break;
    };
    
    switch (inputType) {
      case 'text': case 'select': case 'link': tableTest = input.parent().get(0).tagName.toLowerCase(); break;
      case 'checkbox': case 'radio': tableTest = input.parent().parent().get(0).tagName.toLowerCase(); break;
    };
    
    if (initType == "icon") { //if tooltip fired from an icon
      if (($("#" + toolTipID + "Icon").length == 0) && (toolTipText != "") && (toolTipText != null)) { //check icon does not already exist and that there is some text to show
        if (tableTest == 'td' || tableTest == 'th') {
          iconTitle = "Click here for help on: " + input.text();
          input.append("<a id=\"" + toolTipID + "Icon\" class=\"toolTipIcon\" title=\"" + iconTitle + "\" href=\"#\" tabindex=\"" + tabIndex + "\" ><img src=\"images/common/HelpIndicator.gif\" alt=\"" + iconTitle + "\" /></a>");         
        } else {
          iconTitle = "Click here for help on: " + $("label[for='" + input.attr("id") + "']").text();
          input.after("<a id=\"" + toolTipID + "Icon\" class=\"toolTipIcon\" title=\"" + iconTitle + "\" href=\"#\" tabindex=\"" + tabIndex + "\" ><img src=\"images/common/HelpIndicator.gif\" alt=\"" + iconTitle + "\" /></a>");
        }
        $("#" + toolTipID + "Icon").click(function() { renderTooltip(toolTipID, toolTipText, associatedControlID, initType, inputType, tableTest); return false; });
      }
    } else { //add default focus event handler
      $(associatedControlID).focus(function() { renderTooltip(toolTipID, toolTipText, associatedControlID, initType, inputType, tableTest); return false; });
    }
  }
}

/***-----------------------------------------------***/
function renderTooltip(toolTipID, toolTipText, associatedControlID, initType, inputType, tableTest) { //render and position tooltip

  //create tooltip
  var input = $(associatedControlID);  
  var toolTipClass;
  switch (initType) {
    case "icon": toolTipClass = "iconToolTip"; break;
    case "errortooltip": 
        toolTipClass = "errorToolTip"; 
//        if (!$(associatedControlID).parent().hasClass(".tooltipErrorContainer"))
//        {
//            //don't show tooltip as there is no error
//            return;
//        }
        break;
    default: toolTipClass = "toolTip";
  }
  toolTipText = getToolTipText(toolTipID);
  //var toolTipClass = (initType == "icon") ? "iconToolTip" : "toolTip";
  input.after("<div id=\"" + toolTipID + "\" class=\"" + toolTipClass + "\"><span>" + toolTipText.replace(/&apos;/g, "'") + "</span></div>");

  var inputWidth = input.width(), inputHeight = input.height(), inputOffset = input.offset();
  var inputMarginRight = parseInt(input.css("marginRight").replace("px", ""));
  var inputBorderRight = getMeasurement(input, "borderRightWidth");
  var inputBorderTop = getMeasurement(input, "borderTopWidth");
  var inputPaddingLeft = getMeasurement(input, "paddingLeft");
  var inputPaddingRight = getMeasurement(input, "paddingRight");
  var inputPaddingBottom = getMeasurement(input, "paddingBottom");
  var tooltip = $("#" + toolTipID), tooltipHeight = tooltip.height(), tooltipWidth = tooltip.width();
  var tooltipPaddingBottom = getMeasurement(tooltip, "paddingBottom");
  var outerOffset = $("#divOuter").offset();

  if (inputWidth != null && inputHeight != null && inputOffset != null && tooltipHeight != null && outerOffset != null && toolTipText != "" && inputType != null) {

    var topPx, leftPx, marginTopPx;

    //position and show tooltip
    /***** if in a table *****/
    if (tableTest == 'td' || tableTest == 'th') { // tooltip fired by something in a table (absolute positioning works differently within tables)
      if (inputType == 'link') {
        if (initType == 'icon') {
          leftPx = inputOffset.left - outerOffset.left;
          marginTopPx = 0 - (tooltipHeight + tooltipPaddingBottom);
        } else { // a link, but not an icon
          leftPx = ((inputOffset.left + inputMarginRight) - outerOffset.left);
          //internet explorer doesn't quite work the same and I'm having to subtract an extra 15 pixels - not sure why!!!
          marginTopPx = (jQuery.browser.msie) ? 0 - (tooltipHeight + inputHeight + (tooltipPaddingBottom - 15)) : 0 - (tooltipHeight + inputHeight + tooltipPaddingBottom);
        }
      } else { // not a link
        leftPx = ((inputWidth + inputOffset.left + inputMarginRight + inputBorderRight + inputPaddingLeft + inputPaddingRight) - outerOffset.left);
        marginTopPx = 0 - (tooltipHeight + inputHeight + inputBorderTop);
      }
      tooltip.css({ left: leftPx + "px", marginTop: marginTopPx + "px" }).fadeIn("fast").bgiframe({ src: "/Public/proBlank.htm" });

    /***** else not in a table *****/
    } else {
      var outerOffsetLeft = outerOffset.left;
      leftPx = ((inputWidth + inputOffset.left - 3) - outerOffsetLeft);
      if (initType == "icon") {
        leftPx = leftPx + 1 + inputPaddingLeft + inputPaddingRight; // +1 is to bring it line with the icon 
        topPx = 0 - (tooltipHeight + 4);  // +4 is to bring it line with the icon 
      } else {
        topPx = 0 - (tooltipHeight + inputHeight);
      }
      tooltip.css({ left: leftPx + "px", top: topPx + "px" }).fadeIn("fast").bgiframe({ src: "/Public/proBlank.htm" });
    }
  }
  unRenderTooltip(toolTipID, associatedControlID, initType); // add hide event handlers to newly created tooltip
}

/***-----------------------------------------------***/
//added by sapient - changes tooltip text when control is in a table and there is a validation error (the text in the array is changed on the fly)
function getToolTipText(toolTipId) {
  var index, toolTipText;            
    if (toolTips != undefined) {
        for (index=0;index<toolTips.length;index++) {
            if (toolTips[index][0] == toolTipId) {
               toolTipText = toolTips[index][1];
               break;
            }
        }
    }
    return toolTipText;
  }

function pushToolTipData(toolTipId,toolTipText,attachedControlId,toolTipType,tabIndex)
{
    var indexFound=-1;   
    if (toolTips != undefined) {
        for (var index=0;index<toolTips.length;index++) {
            if (toolTips[index][0] == toolTipId) {
               indexFound = index;
               break;
            }
        }
        
        if (indexFound != -1) {
            toolTips[indexFound][0] = toolTipId;
            toolTips[indexFound][1] = toolTipText;
            toolTips[indexFound][2] = attachedControlId;
            toolTips[indexFound][3] = toolTipType;
            toolTips[indexFound][4] = tabIndex;
        }
        else {
            toolTips.push(new Array(toolTipId,toolTipText,attachedControlId,toolTipType,tabIndex));
        }
    }
}
  /***-----------------------------------------------***/
  function getMeasurement(element, measurementRequired) {
    var measurement = (isNaN(parseInt(element.css(measurementRequired).replace("px", "")))) ? 0 : parseInt(element.css(measurementRequired).replace("px", ""));
    return measurement;
  }
/***-----------------------------------------------***/
function unRenderTooltip(toolTipID, associatedControlID, initType) { //remove tooltip

  associatedControlID = (initType != "icon") ? associatedControlID : $("#" + toolTipID + "Icon");
  $(associatedControlID).blur(function() { $("#" + toolTipID).remove(); });
}

/***-----------------------------------------------***/
function initLinkListeners() { //

  var linkID, divToHide, divToShow;

  jQuery.each(links, function(i) { //loop thru links array

    linkID = this[0];
    divToHide = this[1];
    divToShow = this[2];

    initLink(linkID, divToHide, divToShow); //add click event handler
  })
}

/***-----------------------------------------------***/
function initLink(linkID, divToHide, divToShow) { //

  $("#" + linkID).click(function() {
    $("#" + divToHide).hide();
    $("#" + divToShow).fadeIn("fast");
    return false;
  })
}

/******************** EXTENSIONS **********************/

/***-------------------BGIFRAME---------------------***/
/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
* $LastChangedDate: 2007-07-22 01:45:56 +0200 (Son, 22 Jul 2007) $ * $Rev: 2447 $ * Version 2.1.1
* To use: $('yourElement').bgiframe();*/
(function($) {
$.fn.bgIframe = $.fn.bgiframe = function(s) {
	// This is only for IE6
	if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
		s = $.extend({
			top     : 'auto', // auto == .currentStyle.borderTopWidth
			left    : 'auto', // auto == .currentStyle.borderLeftWidth
			width   : 'auto', // auto == offsetWidth
			height  : 'auto', // auto == offsetHeight
			opacity : true,
			src     : 'javascript:false;'
		}, s || {});
		var prop = function(n){return n&&n.constructor==Number?n+'px':n;},
		    html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
		               'style="display:block;position:absolute;z-index:-1;'+
			               (s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+
					       'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+
					       'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+
					       'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+
					       'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+
					'"/>';
		return this.each(function() {
			if ( $('> iframe.bgiframe', this).length == 0 )
				this.insertBefore( document.createElement(html), this.firstChild );
		});
	}
	return this;
};

})(jQuery);
