﻿String.prototype.trim = function()
{
  return this.replace(/^\s+|\s+$/g, "");
}
String.prototype.ltrim = function()
{
  return this.replace(/^\s+/, "");
}
String.prototype.rtrim = function()
{
  return this.replace(/\s+$/, "");
}

jQuery.fn.limitMaxlength = function (options) {

  var settings = jQuery.extend({
    attribute: "maxlength",
    onLimit: function () { },
    onEdit: function () { }
  }, options);

  // Event handler to limit the textarea
  var onEdit = function () {
    var textarea = jQuery(this);
    var maxlength = parseInt(textarea.attr(settings.attribute));

    if (textarea.val().length > maxlength) {
      textarea.val(textarea.val().substr(0, maxlength));

      // Call the onlimit handler within the scope of the textarea
      jQuery.proxy(settings.onLimit, this)();
    }

    // Call the onEdit handler within the scope of the textarea
    jQuery.proxy(settings.onEdit, this)(maxlength - textarea.val().length);
  }

  this.each(onEdit);

  return this.keyup(onEdit)
				.keydown(onEdit)
				.focus(onEdit)
				.live('input paste', onEdit);
}


/**
* DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
*/
// Declaring valid date character, minimum year and maximum year
var dtCh = "/";
var minYear = 1900;
var maxYear = 2100;

function isInteger(s)
{
  var i;
  for (i = 0; i < s.length; i++)
  {
    // Check that current character is number.
    var c = s.charAt(i);
    if (((c < "0") || (c > "9"))) return false;
  }
  // All characters are numbers.
  return true;
}

function stripCharsInBag(s, bag)
{
  var i;
  var returnString = "";
  // Search through string's characters one by one.
  // If character is not in bag, append to returnString.
  for (i = 0; i < s.length; i++)
  {
    var c = s.charAt(i);
    if (bag.indexOf(c) == -1) returnString += c;
  }
  return returnString;
}

function daysInFebruary(year)
{
  // February has 29 days in any year evenly divisible by four,
  // EXCEPT for centurial years which are not also divisible by 400.
  return (((year % 4 == 0) && ((!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28);
}
function DaysArray(n)
{
  for (var i = 1; i <= n; i++)
  {
    this[i] = 31
    if (i == 4 || i == 6 || i == 9 || i == 11) { this[i] = 30 }
    if (i == 2) { this[i] = 29 }
  }
  return this
}

function isDate(dtStr, ignoreAlerts)
{
  var daysInMonth = DaysArray(12)
  var pos1 = dtStr.indexOf(dtCh)
  var pos2 = dtStr.indexOf(dtCh, pos1 + 1)
  var strMonth = dtStr.substring(0, pos1)
  var strDay = dtStr.substring(pos1 + 1, pos2)
  var strYear = dtStr.substring(pos2 + 1)

  if (strYear.length == 2)
  {
    // account for people entering 2 digits for year
    var today = new Date();
    var todayYear = today.getYear();

    strYear = todayYear.toString().substring(0, 2) + strYear;
  }

  strYr = strYear;
  if (strDay.charAt(0) == "0" && strDay.length > 1) strDay = strDay.substring(1)
  if (strMonth.charAt(0) == "0" && strMonth.length > 1) strMonth = strMonth.substring(1)


  for (var i = 1; i <= 3; i++)
  {
    if (strYr.charAt(0) == "0" && strYr.length > 1) strYr = strYr.substring(1)
  }

  month = parseInt(strMonth)
  day = parseInt(strDay)
  year = parseInt(strYr)

  if (pos1 == -1 || pos2 == -1)
  {
    if (ignoreAlerts == false)
      alert("The date format should be : mm/dd/yyyy")
    return false
  }
  if (strMonth.length < 1 || month < 1 || month > 12)
  {
    if (ignoreAlerts == false)
      alert("Please enter a valid month")
    return false
  }
  if (strDay.length < 1 || day < 1 || day > 31 || (month == 2 && day > daysInFebruary(year)) || day > daysInMonth[month])
  {
    if (ignoreAlerts == false)
      alert("Please enter a valid day")
    return false
  }
  if (strYear.length != 4 || year == 0 || year < minYear || year > maxYear)
  {
    if (ignoreAlerts == false)
      alert("Please enter a valid 4 digit year between " + minYear + " and " + maxYear)
    return false
  }
  if (dtStr.indexOf(dtCh, pos2 + 1) != -1 || isInteger(stripCharsInBag(dtStr, dtCh)) == false)
  {
    if (ignoreAlerts == false)
      alert("Please enter a valid date")
    return false
  }
  return true
}

/* 
LOADING DIV
*/
function showLoading()
{
  showWaitingDiv("loading", "Loading please wait...");
}

function hideLoading()
{
  hideWaitingDiv("loading");
}

function showWaitingDiv(key, message)
{
  hideWaitingDiv(key);
  var div = getWaitingDiv(key, message);
  $("body").append(div);
  div.center();
}

function hideWaitingDiv(key)
{
  $("#waitingDiv-" + key).remove();
}

// Creates a new div with a loading message plus image
function getWaitingDiv(key, message)
{
  var waitingDiv = $("<div>").attr(
    {
      id: "waitingDiv-" + key
    }
  ).text(message);

  waitingDiv.addClass("waitingDiv");

  var img = $("<img>").attr(
    {
      id: "loadingImage",
      src: "/images/content/ajax-loader.gif"
    }
  );

  waitingDiv.append(img);

  return waitingDiv;
}

function addWaitingImageToCenterOfDiv(id) {
  var div = $('#' + id);

  if (div == null || div.length == 0)
    return;

  // find center of div
  var imageWidth = 16;
  var imageHeight = 16;

  var parentHeight = div.height();
  var parentWidth = div.width();

  var topMargin = (parentHeight - imageHeight) / 2;
  var leftMargin = (parentWidth - imageWidth) / 2;

  var left = div.position().left + leftMargin;
  var top = div.position().top + topMargin;

  var img = $("<img>").attr(
    {
      id: "loadingImage",
      src: "/images/content/ajax-loader.gif",
      style: 'position:absolute; z-index: 1000; top: ' + top + 'px; left: ' + left + 'px;'
    }
  );

  div.append(img);
}

function addWaitingImageToSLCHeader(id) {
  var div = $('#' + id + ' .caption');
  var span = $('#' + id + ' .caption span');

  if (div == null || div.length == 0)
    return;

  if (span == null || span.length == 0)
    return;

  //find the left position of the image we will be adding
  var left = span.position().left + span.width();

  var imageHeight = 16;

  var parentHeight = div.height();

  var topMargin = (parentHeight - imageHeight) / 2;

  var top = div.position().top + topMargin;

  var img = $("<img>").attr(
    {
      id: "loadingImage_" + id,
      src: "/images/content/ajax-loader.gif",
      style: 'margin-left: 5px; z-index: 1000; top: ' + top + 'px; left: ' + left + 'px;'
    }
  );

  div.append(img);
}

function removeWaitingImageToSLCHeader(id) {
  var img = $('#loadingImage_' + id);

  if (img != null && img.length > 0)
    img.remove();
}
/*
END LOADING DIV
*/

/*
DELETE
*/

function confirmDelete()
{
  var ret = false;

  ret = confirm('Do you want to delete this item?');

  return ret;
}

function confirmMultipleDelete()
{
  var ret = false;

  ret = confirm('Do you want to delete the selected item(s)?');

  return ret;
}

/*
END OF DELETE
*/


function toggleShowHideCart()
{
  var link = $(".toggleCart");

  if (link.text() == "Hide")
  {
    // hide cart and switch text
    $("#productCartInfo").hide('fast');

    link.text("Show");
  }
  else
  {
    // show cart and switch text
    $("#productCartInfo").show('fast');

    link.text("Hide");
  }
}

/* 
QTip - Tooltips
*/
function setWebComboTooltip(id, message)
{
  $("#" + id + "_input").attr("tooltip", message);
}

function addSimpleTooltip(id, message)
{
  $("#" + id).qtip({ content: message });
}





/* 
Search
*/
function search()
{
  var searchText = $("#SearchTextBox").val();

  if (searchText == '' || searchText == searchWatermark)
    return;

  location.href = '/Search/Site.aspx?search=' + searchText;
}

function showPrinterFriendlyReport(html, width, height)
{
  //half the screen width minus half the new window width
  var left = (window.screen.width - width) / 2;
  //half the screen height minus half the new window height
  var top = (window.screen.height - height) / 2;


  var settings = 'location=0,status=0,toolbar=0,menubar=0,directories=0,' +
                  'resizable=0,scrollbars=1,height=' + height + ',width=' + width +
                  ',left=' + left + ',top=' + top;

  var printerWindow = window.open('', 'printerFriendlyReport', settings);

  printerWindow.document.close();
  printerWindow.document.open();

  printerWindow.document.writeln('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' +
                ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">');
  printerWindow.document.writeln('<html xmlns="http://www.w3.org/1999/xhtml" >');
  printerWindow.document.writeln('<head>');
  // add our style sheets
  printerWindow.document.writeln('<link href="/css/main.css" rel="stylesheet" type="text/css" />');
  printerWindow.document.writeln('<link href="/css/members_print.css" rel="stylesheet" type="text/css" />');
  printerWindow.document.writeln('</head>');
  printerWindow.document.writeln('<body>');
  printerWindow.document.writeln('<div style="text-align: left; margin: 0px auto;">');
  printerWindow.document.writeln(html);
  printerWindow.document.writeln('</div>');
  printerWindow.document.writeln('</body></html>');
  printerWindow.focus();
  printerWindow.print();

  // required for the print to work
  printerWindow.document.close();
}

function showPopupWindowInBrowser(url, name, width, height)
{
  //half the screen width minus half the new window width
  var left = (window.screen.width - width) / 2;
  //half the screen height minus half the new window height
  var top = (window.screen.height - height) / 2;

  var settings = 'location=0,status=0,toolbar=0,menubar=0,directories=0,' +
                  'resizable=1,scrollbars=1,height=' + height + ',width=' + width +
                  ',left=' + left + ',top=' + top;

  var win = window.open(url, name, settings);

  return win;
}

function showPopupWindow(divId, url, title, width, height)
{

  $("#" + divId).remove();
  $("body").append("<div id=\"" + divId + "\"></div>");

  var div = $("#" + divId);
  div.load(url, function()
  {
    div.dialog(
      { width: width, height: height, resizable: false, title: title }
    );
  });
}

function showClaimInstructions()
{
  var url = "/Claim/instructions.html";
  var title = "Instructions for Claim Report Forms";

  showPopupWindow("claimReportInstructions", url, title, 400, 600);
}

function showContactInfo()
{
  var url = "/contactPopup.html";
  var title = "Contact Information";

  $("#contactInfo").remove();
  $("body").append("<div id=\"contactInfo\"></div>");

  $("#contactInfo").load(url, function()
  {
    $("#contactInfo").dialog(
      { width: 250, height: 135, minHeight: 135, resizable: false, title: title }
    );
  });
}

function showStateUserInfo(stateAbbr)
{
  var url = "/StateUserInfo.aspx?stateAbbr=" + stateAbbr;
  var title = "Contact Information";

  $("#contactInfo").remove();
  $("body").append("<div id=\"contactInfo\"></div>");

  $("#contactInfo").load(url, function()
  {
    $("#contactInfo").dialog(
      { width: 300, height: 200, minHeight: 135, resizable: false, title: title }
    );
  });
}

function confirmDeletion()
{
  var answer = confirm('Are you sure you want to delete the selected item(s)?');

  if (answer == false)
    return false;
}

function setupClaimTips()
{
  // Notice the use of the each() method to acquire access to each elements attributes
  $(".qtip").each(function()
  {
    var tooltip = $(this).attr('tooltip');

    if (tooltip != '' & tooltip != null)
    {
      $(this).qtip({
        content: $(this).attr('tooltip'), // Use the tooltip attribute of the element for the content
        style: 'red', // Give it a cream style to make it stand out
        position: {
          corner: {
            target: 'topRight',
            tooltip: 'bottomLeft'
          }
        }
      });
    }
  });
}

function checkRadioSelection(radioName, checkFor, divId)
{
  var opt = $("input[type=radio][id*=" + radioName + "]:checked").val();

  if (opt == checkFor)
    $("#" + divId).show();
  else
    $("#" + divId).hide();
}



function formatNumber(val)
{
  val += '';
  x = val.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';

  x1 = x1.replace(/,/g, '');

  var rgx = /(\d+)(\d{3})/;

  while (rgx.test(x1))
  {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }

  val = x1 + x2;
  return val;
}


function exportToExcel(html, filename)
{
  // create a form on the page so we can post our data
  var $f = $('<form></form>')
        .attr({
          method: 'post',
          target: '_blank',
          action: '/ExcelExport.aspx'
        })
        .appendTo(document.body)
    ;

  // setup our hidden variables
  var myHiddenVariables = {
    filename: filename,
    html: html
  };

  // add the hidden variables to the new form
  for (var i in myHiddenVariables)
  {
    $('<input type="hidden" />')
            .attr({
              name: i,
              value: myHiddenVariables[i]
            })
            .appendTo($f)
        ;
  }
  $f[0].submit();
}

function replaceLinksWithText(html)
{
  // parse out any links
  html.find('a').each(function()
  {
    var $this = $(this);
    var text = $this.text()
    $this.parent().html(text);
  });

  return html;
}
