/*
 * Copyright (c) 2009 Discovery Health Systems.
 * The information contained in this file is the intellectual property of Discovery Health Systems (the owner).
 * No part of this file may be changed, copied or removed by persons other than the owner or persons
 * authorised to do so by the owner.
 */

/**
 * JQuery Utility functions to help with object retrieval, interigation and debugging.
 */
var JQueryUtils = jQuery.extend({
    /**
     * Creates a jquery id selector and searches the DOM for a jQuery object using the new id selector .
     * @param id The id value to constuct a valid jquery id selector from.
     * @return JQueryObject The jquery retrieved from the DOM that matches the id. Null if nothing is found.
     */
    jqo:function(id) {
        if (id) {
            return $('#' + id);
        }
        return null;
    },
    /**
     * Get the id attribute of an jquery object.
     * @param obj The jQuery object to get the id attribute from.
     * @return String The id of the jQuery object, this could be null or empty.
     */
    getId:function(obj) {
        return obj.attr('id');
    },
    /**
     * Convenience function to alert the id attribute of a jQuery object.
     * @param obj The object to alert the id attribute from.
     */
    alertId:function(obj) {
        alert('Object id: ' + (obj.attr('id') ? obj.attr('id') : '[undefined]'));
    },
    /**
     * Convenience function to alert the class attribute of a jQuery object.
     * @param obj The object to alert the class attribute from.
     */
    alertClass:function(obj) {
        alert('Object css-class: ' + (obj.attr('class') ? obj.attr('class') : '[undefined]'));
    },
    /**
     * Convenience function to alert the specified attribute of a jQuery object.
     * @param obj The object the alert the attribute from.
     * @param attr The attribute to alert, if not found / set on the object this function will alert '[undefined]'
     */
    alertAttr:function(obj, attr) {
        alert('Object attribute: ' + attr + ' = ' + (obj.attr(attr) ? obj.attr(attr) : '[undefined]'));
    }
});
/**
 * String Utility functions to help with string manipilation and testing.
 */
var StringUtils = jQuery.extend({
    /**
     * Checks if a string contains the specified search string.
     * @param str The string to search for the specified search string.
     * @param searchStr The search string to check for in the specified string.
     * @return boolean True if the string contains the search string.
     */
    contains:function(str, searchStr) {
        if (str && searchStr) {
            return (str.toString().search(searchStr) >= 0);
        } else {
            return false;
        }
    },
    /**
     * Substrings a string returning the string part after the specified seperator.
     * @param str The string to substring.
     * @param seperator The seperator to substring on.
     * @return String The string part after the seperator.
     */
    substringAfter:function(str, seperator) {
        if (str && seperator) {
            return str.split(seperator)[1];
        } else {
            return str;
        }
    },
    /**
     * Substrings a string returning the string part before the specified seperator.
     * @param str The string to substring.
     * @param seperator The seperator to substring on.
     * @return String The string part before the seperator.
     */
    substringBefore:function(str, seperator) {
        if (str && seperator) {
            return str.split(seperator)[0];
        } else {
            return str;
        }
    }
});

/**
 * Checks if the size of a div with class or id contentRight is smaller than a sibling div
 * with a class or id of contentLeft. If so it will resize contentRight to be the same as
 * contentLeft
 */
var _resizeContentRight = function() {
  $('#contentright').map(function() {
    if ($(this).height() < $(this).prevAll('#contentleft').height()) {
      $(this).css('height', $(this).prevAll('#contentleft').height() + 'px');
    }
  });
};

var _tableStyling = function() {
  // style alternatingrows tables by assigning classes to alternating rows
  $("table.alternatingrowsab tbody tr:odd").addClass("gra");
  $("table.alternatingrowsab tbody tr:even").addClass("grb");
  $("table.alternatingrowscd tbody tr:odd").addClass("grc");
  $("table.alternatingrowscd tbody tr:even").addClass("grd");
  $("table.alternatingrowsef tbody tr:odd").addClass("gre");
  $("table.alternatingrowsef tbody tr:even").addClass("grf");

  //listen for hover event on tables with rowhover class and change the hover row
  var grClass = "";
  $("table.rowhover tbody tr, table .rowhover2 tbody tr").hover(
        function() {
          if ($(this).hasClass("grA") || $(this).hasClass("gra")) {grClass += "gra "; $(this).removeClass("gra grA");}
          if ($(this).hasClass("grB") || $(this).hasClass("grb")) {grClass += "grb "; $(this).removeClass("grb grB");}
          if ($(this).hasClass("grC") || $(this).hasClass("grc")) {grClass += "grc "; $(this).removeClass("grc grC");}
          if ($(this).hasClass("grD") || $(this).hasClass("grd")) {grClass += "grd "; $(this).removeClass("grd grD");}
          if ($(this).hasClass("grE") || $(this).hasClass("gre")) {grClass += "gre "; $(this).removeClass("gre grE");}
          if ($(this).hasClass("grF") || $(this).hasClass("grf")) {grClass += "grf "; $(this).removeClass("grf grF");}
          if ($(this).closest("table").hasClass("rowhover2")) {
            $(this).addClass("grhover2");
          } else {
            $(this).addClass("grhover");
          }
        },
        function () {
          if ($(this).hasClass("grhover2")) {
            $(this).removeClass("grhover2");
          } else  {
            $(this).removeClass("grhover");
          }
          $(this).addClass(jQuery.trim(grClass));
          grClass = "";
        }
      );
};

var _helpField = function() {
  // show help text when field with help text has focus
  $('.fieldhelp').find('input, select').focus(function() {
    $(this).closest('.fieldhelp').removeClass('fieldhelpfocus').addClass('fieldhelpfocus');
    $(this).nextAll('.fieldhelptext').show();
    $(this).nextAll('.fieldhelptextmore').show().each(function() {
      var divLeft = $(this).prev().position().left + $(this).prev().innerWidth();
      $(this).css('left', divLeft + "px");
      if ($(this).html().indexOf('fieldhelptextmore-border-eraser') < 0) {
        $(this).prepend('<span class="fieldhelptextmore-border-eraser">&nbsp;</span>');
      }
      $(this).children('.fieldhelptextmore-border-eraser').each( function() {
        $(this).show().height($(this).closest('.fieldhelp').innerHeight());
      });
      var tmpWidth = $(this).offset().left - $(this).closest('.fieldhelp').offset().left;
      var divWidth = $(this).closest('.fieldhelp').width() - tmpWidth;
      var divWidthtxt = (Math.round(divWidth)).toString() + 'px';
      $(this).width(divWidthtxt);
      if ($(this).outerHeight() <= $(this).closest('.fieldhelp').outerHeight()) {
        $(this).height($(this).closest('.fieldhelp').innerHeight() - 10);
      } else {
        $(this).css('height', 'auto');
      }
    });
  }).blur(function() {
    $(this).nextAll('.fieldhelptext').hide();
    $(this).nextAll('.fieldhelptextmore').hide().each(function() {
      $(this).children('.fieldhelptextmore-border-eraser').hide();
    });
    $(this).closest('.fieldhelp').removeClass('fieldhelpfocus');
  });
};

/**
 * Show/hide an expandablenode
 * @param opts -  headerBlock:      The CSS selctor of the element that is the header (optional)
 *                expandableBlock:  The CSS selctor of the element that is the expandableBlock
 *                showTrigger:      The CSS selctor of the element to which a click event is bound to show the expandable block
 *                hideTrigger:      The CSS selctor of the element to which a click event is bound to hide the expandable block
 *                hideHeader:       true/false - indicates whether the header should hide when the expandable block is shown
 */
var _expandableNode = function(opts) {
  var header = opts.headerBlock;
  var expandableBlock = opts.expandableBlock;
  var showTrigger = opts.showTrigger;
  var hideTrigger = opts.hideTrigger;
  var hideHeader = false;
  if (opts.hideHeader != null && opts.hideHeader.toString().toLowerCase() == 'true') hideHeader = true;
  var toggle = false;

  if (showTrigger != null && $.trim(showTrigger).length > 0 && expandableBlock != null && $.trim(expandableBlock).length > 0) {
    if (hideTrigger == null || $.trim(hideTrigger).length <= 0) {hideTrigger = showTrigger; toggle = true;}
    $(showTrigger).click( function () {
      if (hideHeader) {
        if (header != null && $.trim(header).length > 0) $(header).hide();
      }
      if (toggle) {
        if ($.browser.msie && $.browser.version.substr(0,1)<8) {$(expandableBlock).toggle();} else {$(expandableBlock).slideToggle();}
      } else {
        if ($.browser.msie && $.browser.version.substr(0,1)<8) {$(expandableBlock).show();} else {$(expandableBlock).slideDown();}
      }
    });
    if (!toggle && hideTrigger != showTrigger) {
      $(hideTrigger).click(function() {
        if ($.browser.msie && $.browser.version.substr(0,1)<8) {$(expandableBlock).hide();} else {$(expandableBlock).slideUp();}
        if (hideHeader) {
          if (header != null && $.trim(header).length > 0) $(header).show();
        }
      });
    }
  }
};

/**
 * adds correct behaviour for <label> tag around radio buttons containing text boxes, selects, etc. in browsers like IE
 */
var _radioOptionFocus = function() {
  $('.radiofocushelp input, .radiofocushelp select').focus(function() {
    if ($(this).prevAll('input:radio').length > 0) {
      $(this).prevAll('input:radio').attr('checked', true);
    } else {
      $(this).closest('input:radio').attr('checked', true);
    }
  });
};

/**
 * Wrap a block level type element with an anchor tag
 */
var _blockLinks = function() {
    // Loop through the block level elements
    $('.blockLink').each(function() {
        // find the anchor tag specified.
        var anchorElement = $(this).children('a');
        var divElement = $(this).children('div');

        anchorElement.css('cursor', 'pointer');
        anchorElement.html(divElement);

        $(this).html(anchorElement);
    });
};


/**
 * returns a reference to either IframeInterface or IframePArentIngerface depending on which one is instantiated.
 * - dvdm 20101220
 */
var _getActiveFrame = function() {
    try {if (IFrameInterface != null){return  IFrameInterface;}} catch(e) {/**alert("IFrameInterface does NOT exist")**/}
    try {if (IFrameParentInterface != null) {return IFrameParentInterface;}} catch(e) {/**alert("IFrameInterface does NOT exist")**/}
    return null;
};


/**
 * Register modal pop-ups for links created in content
 */

var _modalContentLinks = function() {
    var activeIframeInterface = _getActiveFrame();

    // loop through the decorated modal links in the content
    $('.modalContentLink').each(function() {
        var triggerId = $(this).attr('id');
        activeIframeInterface.initModalDialog({
           	target: "#decoratedModalIframe",
           	trigger: "#"+triggerId,
           	isIframe: "true",
           	scrolling: "auto"
        });
    });

    // loop through the undecorated modal links in the content
    $('.unDecoratedModalContentLink').each(function() {
        var triggerId = $(this).attr('id');
        activeIframeInterface.initModalDialog({
           	target: "#unDecoratedModalIframe",
           	trigger: "#"+triggerId,
           	isIframe: "true",
           	scrolling: "auto"
        });
    });
};

var _tooltips = function() {
    $('.tooltip').each(function() {
        $(this).easyTooltip({
            useElement: $(this).attr('tooltipItem')
        });
    });
};


/*Start the resizeContentRight script...*/
$(document).ready(function() {
    _resizeContentRight();
    _tableStyling();
    _helpField();
    _radioOptionFocus();
    _blockLinks();
    _modalContentLinks();
    _tooltips();
});

