shortMonthArray = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May',
  'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
monthArray = new Array('January', 'February', 'March', 'April',
  'May', 'June', 'July', 'August', 'September', 'October',
  'November', 'December');

function testForCookies()
{
  var hasCookies = false;
  var x_cookieName = "myci_testcookie";
  var x_domain  = ".chipin.com";
  var x_expires = new Date();
  var oldDate = new Date(1970, 1, 1)
  x_expires.setFullYear(x_expires.getFullYear() + 1);
  document.cookie = x_cookieName + "=0; expires=" +
    oldDate.toGMTString();
  document.cookie = x_cookieName + "=test; expires=" +
    x_expires.toGMTString();
    // + "; domain=" + x_domain;
    var x_cookieString = document.cookie || "";
  var x_cookies = x_cookieString.split(/\s*;\s*/);
  for (var i in x_cookies) {
    var cookie = x_cookies[i];
    cookie = cookie.toString();
    var dough = cookie.split(/\s*=\s*/);
    if (dough[0] == x_cookieName) {
      hasCookies = true;
      break;
    }
  }
  document.cookie = x_cookieName + "=0; expires=" +
    oldDate.toGMTString();
  return hasCookies;
}

function writeCookieMessage()
{
  if (hasCookies == false) {
    document.write('<p id="nocookiemessage">');
    document.write('It looks like you don\'t have cookies enabled. Note that without enabling cookies, some of the functionality of this site may not be available to you. ');
    document.write('<a href="http:\/\/www.google.com\/cookies.html">Here\'s how to enable cookies<\/a>.');
    document.write('<\/p>');
    hasBrowserError = true;
  }
}

function hasFlash()
{
  return detectFlashVer(9, 0, 0);
}

// Taken from http://www.adobe.com/products/flashplayer/download/detection_kit/.
function controlVersion()
{
  var version;
  var axo;
  var e;

  // NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

  try {
    // version will be set for 7.X or greater players
    axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
    version = axo.GetVariable("$version");
  } catch (e) {
  }

  if (!version)
  {
    try {
      // version will be set for 6.X players only
      axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");

      // installed player is some revision of 6.0
      // GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
      // so we have to be careful.

      // default to the first public version
      version = "WIN 6,0,21,0";

      // throws if AllowScripAccess does not exist (introduced in 6.0r47)
      axo.AllowScriptAccess = "always";

      // safe to call for 6.0r47 or greater
      version = axo.GetVariable("$version");

    } catch (e) {
    }
  }

  if (!version)
  {
    try {
      // version will be set for 4.X or 5.X player
      axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
      version = axo.GetVariable("$version");
    } catch (e) {
    }
  }

  if (!version)
  {
    try {
      // version will be set for 3.X player
      axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
      version = "WIN 3,0,18,0";
    } catch (e) {
    }
  }

  if (!version)
  {
    try {
      // version will be set for 2.X player
      axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
      version = "WIN 2,0,0,11";
    } catch (e) {
      version = -1;
    }
  }

  return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function getSwfVer()
{
  // NS/Opera version >= 3 check for Flash plugin in plugin array
  var flashVer = -1;

  if (navigator.plugins != null && navigator.plugins.length > 0) {
    if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
      var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
      var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
      var descArray = flashDescription.split(" ");
      var tempArrayMajor = descArray[2].split(".");
      var versionMajor = tempArrayMajor[0];
      var versionMinor = tempArrayMajor[1];
      var versionRevision = descArray[3];
      if (versionRevision == "") {
        versionRevision = descArray[4];
      }
      if (versionRevision[0] == "d") {
        versionRevision = versionRevision.substring(1);
      } else if (versionRevision[0] == "r") {
        versionRevision = versionRevision.substring(1);
        if (versionRevision.indexOf("d") > 0) {
          versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
        }
      }
      flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
    }
  }
  // MSN/WebTV 2.6 supports Flash 4
  else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
  // WebTV 2.5 supports Flash 3
  else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
  // older WebTV supports Flash 2
  else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
  else if ( is_ie && is_win && !is_opera ) {
    flashVer = controlVersion();
  }
  return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns
// true if that version or greater is available
function detectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
  versionStr = getSwfVer();
  if (versionStr == -1 ) {
    return false;
  } else if (versionStr != 0) {
    if(is_ie && is_win && !is_opera) {
      // Given "WIN 2,0,0,11"
      tempArray         = versionStr.split(" ");  // ["WIN", "2,0,0,11"]
      tempString        = tempArray[1];     // "2,0,0,11"
      versionArray      = tempString.split(",");  // ['2', '0', '0', '11']
    } else {
      versionArray      = versionStr.split(".");
    }
    var versionMajor      = versionArray[0];
    var versionMinor      = versionArray[1];
    var versionRevision   = versionArray[2];

    // is the major.revision >= requested major.revision AND the minor version >= requested minor
    if (versionMajor > parseFloat(reqMajorVer)) {
      return true;
    } else if (versionMajor == parseFloat(reqMajorVer)) {
      if (versionMinor > parseFloat(reqMinorVer))
        return true;
      else if (versionMinor == parseFloat(reqMinorVer)) {
        if (versionRevision >= parseFloat(reqRevision))
          return true;
      }
    }
    return false;
  }
}

function hideBrowserError()
{
  if (hasBrowserError == false)
    $("#browserError").hide();
}

var is_mac = false;
var is_unix = false;
var is_win = false;
var is_ie = false;
var is_ff = false;
var is_safari = false;

agt = navigator.userAgent.toLowerCase();
is_win = ((agt.indexOf("win") != -1) ||
  (agt.indexOf("16bit") != -1));
is_mac = (agt.indexOf("mac") != -1);
is_unix = (agt.indexOf("x11") != -1);
if ($.browser.safari)
  is_safari = true;
else if ($.browser.msie)
  is_ie = true;
else if ($.browser.mozilla)
  is_ff = true;

// Just used for flash detection.
var is_opera = (agt.indexOf("opera") != -1) ? true : false;

var has_flash = hasFlash();
if (has_flash == undefined)
  has_flash = false;

var hasCookies = testForCookies();
var offset = new Date();
var gmtOffset = offset.getTimezoneOffset();
var hasBrowserError = false;

function modifierKeyIsDown(e)
{
  mkid = false;
  if (e.modifiers) {
    if (e.modifiers & Event.ALT_MASK ||
    e.modifiers & Event.CONTROL_MASK ||
    e.modifiers & Event.SHIFT_MASK ||
    e.modifiers & Event.META_MASK)
      mkid = true;
  } else if (e.altKey || e.ctrlKey ||
    e.shiftKey) {
      mkid = true;
  }
  return mkid;
}

function addEvent(obj, evType, fn)
{
  if (obj.addEventListener) {
    obj.addEventListener(evType, fn, true);
    return true;
  } else if (obj.attachEvent) {
    var r = obj.attachEvent("on" + evType, fn);
    return r;
  } else {
    return false;
  }
}

function initFunctions()
{
  // Field autofocus

  obj = $("input[@class=autofocus]");
  if (obj && obj[0] != undefined) {
    if (obj[0].value == "")
      obj[0].focus();
    else {
      obj[0].select();
      obj[0].focus();
    }
  }

  formFieldHover();

  // Form section backgrounds

  $("#miniloginform[@class=formbg]").hover(
  function() {
    this.style.backgroundColor = "#fff7c0";
    obj = $("input[@type=text]", this);
    if (obj && obj[0] != undefined) {
      if (obj[0].value == "")
        obj[0].focus();
      else {
        obj[0].select();
        obj[0].focus();
      }
    }
    $(this).find("h2").find("span").css("color", "#555555");
  },
  function() {
    this.style.backgroundColor = "";
    $(this).find("h2").find("span").css("color", "");
  });
  $(".formbg").hover(
  function() {
    if (this.options != undefined) {
      obj = $("input[@type=text]", this);
      if (obj && obj[0] != undefined) {
        if (obj[0].value == "")
          obj[0].focus();
        else {
          obj[0].select();
          obj[0].focus();
        }
      }
    }
    $(this).find("h2").find("span").css("color", "#555555");
  },
  function() {
    $(this).find("h2").find("span").css("color", "");
  });

  // Numeric fields

  $("input.numeric").each(function() {
    $(this).numeric(false);
    val = $(this).val();
    val = val.replace(/\.00/, "");
    $(this).val(val);
  });
  $("input.numericd").numeric(true);

  // Checkbox label toggles

  $(".checklabel").mousedown(function() {
    objId = this.getAttribute("target");
    $("input[@id=" + objId + "]")[0].click();
    return false;
  });
  $(".checklabel").each(function() {
    this.setAttribute("onmousemove", "return false");
    this.setAttribute("onmouseup", "return false");
  });

  // Menubar

  $("#menuitems li a").hover(
    function() {
      if ($(this).attr("class") != "selectedmenuitem")
        $(this).addClass("hovermenuitem");
    }, function() {
      if ($(this).attr("class") != "selectedmenuitem")
        $(this).removeClass("hovermenuitem");
    }
  );

  // IE object focus workaround and detection note

  flashFix();
}

function flashFix()
{
  if (is_ie) {
    $(".flashembed").each(function() {
      wObj = $(this)[0];
      if (wObj != undefined) {
        wHTML = $(this).html();
        wObj.innerHTML = wHTML;
      }
    });
  }
}

function formFieldHover()
{
  $("input[@type=text],input[@type=password],textarea").hover(
  function() {
    $(this).removeClass("fieldmouseout");
    $(this).addClass("fieldmouseover");
    if (is_safari) this.style.backgroundColor = "#ffffdd";
  },
  function() {
    $(this).removeClass("fieldmouseover");
    $(this).addClass("fieldmouseout");
    if (is_safari) this.style.backgroundColor = "";
  });
}

// From http://www.mredkj.com/javascript/numberFormat.html

function addCommas(nStr)
{
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

function formatNumber(num)
{
  num = addCommas(num);
  num = num.replace(/\.00/g,"");
  return num.replace(/\.0$/g,"");
}

function formatDollar(num)
{
  if (num != null && String(num).indexOf("%") != -1)
    return num;
  if (num == null || num == "" || num == "0" || num == 0)
    return "$0";
  return '$' + formatNumber(num);
}

function parseTimestampLong(ts)
{
  return parseTimestampFull(ts, true);
}

function parseTimestamp(ts)
{
  return parseTimestampFull(ts, false);
}

function parseTimestampFull(ts, longMonths)
{
  monArray = shortMonthArray;
  if (longMonths)
    monArray = monthArray;
  // The timestamp is expected to be in GMT
  ts = parseInt(ts) // + (gmtOffset * 60 * 1000);
  now = new Date();
  thismonth = monArray[now.getMonth()];
  thisday = now.getDate();
  thisyear = now.getFullYear();
  now.setTime(ts);
  month = monArray[now.getMonth()];
  day = now.getDate();
  hour = now.getHours();
  min = now.getMinutes();
  year = now.getFullYear();
  if (min < 10)
    min = "0" + min;
  ampm = "am";
  if (hour > 11)
    ampm = "pm";
  if (hour > 12)
    hour = hour - 12;
  if (hour == 0)
    hour = 12;
  if (month == thismonth && day == thisday && year == thisyear)
    dstr = "today ";
  else {
    if (year == thisyear)
      year = "";
    else
      year = ", " + year;
    dstr = month + " " + day + year + " ";
  }
  dstr += (hour + ":" + min + ampm);
  return dstr;
}

function makeEndTimeStr(ts)
{
  monArray = shortMonthArray;
  // The timestamp is expected to be in GMT
  ts = parseInt(ts) // + (gmtOffset * 60 * 1000);
  now = new Date();
  thismonth = monArray[now.getMonth()];
  thisday = now.getDate();
  thisyear = now.getFullYear();
  thistime = now.getTime();
  now.setTime(ts);
  month = monArray[now.getMonth()];
  day = now.getDate();
  hour = now.getHours();
  min = now.getMinutes();
  year = now.getFullYear();
  endtime = now.getTime();
  if (endtime <= thistime)
    return "Ended";
  if (month == thismonth && day == thisday && year == thisyear) {
    dstr = "Ends in ";
    diff = endtime - thistime;
    hours = Math.floor(diff / (1000 * 60 * 60));
    diff -= hours * (1000 * 60 * 60);
    mins = Math.floor(diff / (1000 * 60));
    diff -= hours * (1000 * 60);
    secs = Math.floor(diff / 1000);
    if (hours > 0)
      dstr += (hours + "h");
    else if (mins > 0)
      dstr += (mins + "m");
    else if (secs > 0)
      dstr += (secs + "s");
    return dstr;
  } else
    return "Ends " + month + " " + day;
}

function endTimeIsUrgent(ts)
{
  // The timestamp is expected to be in GMT
  ts = parseInt(ts) // + (gmtOffset * 60 * 1000);
  now = new Date();
  thistime = now.getTime();
  now.setTime(ts);
  endtime = now.getTime();
  if (endtime <= thistime)
    return false;
  if (getDays(thistime, endtime) <= 3)
    return true;
  return false;
}

function getDayTime(sectime)
{
  newdate = new Date();
  newdate.setTime(sectime);
  newdate.setHours(0, 0, 0, 0);
  return Math.floor(newdate.getTime());
}

function getDays(time1, time2)
{
  return Math.floor(Math.abs(getDayTime(time1) -
    getDayTime(time2)) / (86400 * 1000)) + 1;
}

function loadDataFromTable(tableid)
{
  returnArray = new Array();
  tempArray = $("#" + tableid + " tr").get();
  $.each(tempArray, function(i) {
    tempRowArray = $(this).find("td").get();
    $.each(tempRowArray, function(j) {
      tempRowArray[j] = $(tempRowArray[j]).html();
    });
    returnArray[i] = tempRowArray;
  });
  return returnArray;
}

function summarize(str)
{
  maxChars = 200;
  if (str.length > maxChars) {
    len = str.length;
    str = str.substr(0, maxChars);
    str = rtrim(str, ' -?!.,"\'' + "\t\n\r");
    str += '...';
  }
  return str;
}

function rtrim(str, trimstr)
{
  len = str.length;
  for (i = len; i > 0; i--) {
    c = str.charAt(i);
    if (trimstr.indexOf(c) == -1)
      break;
  }
  return str.substr(0, i);
}

addEvent(window, 'load', initFunctions);

// Safari page refresh bug fix

function refreshPage()
{
  if (!is_safari) return;
  if ($("#refreshDiv")[0] == undefined)
    $("#content").children("*:eq(0)").before('<div id="refreshDiv"><img src="/images/spacer.gif" width="1" height="1"/></div>');
  else
    $("#refreshDiv").remove();
  window.scrollBy(0, 0);
  if (self.screenTop && self.screenX) {
    window.resizeTo(self.outerWidth + 1, self.outerHeight);
    window.resizeTo(self.outerWidth - 1, self.outerHeight);
  }
}

/*
 * Copyright (c) 2006 Sam Collett (http://www.texotela.co.uk)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * See http://www.texotela.co.uk/code/jquery/numeric/
 */

jQuery.fn.numeric = function(allowdecimals)
{
  decimal = ".";
  this.keypress(function(e) {
    if (modifierKeyIsDown(e))
      return false;
    var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
    if (key == 44)
      return true;
    if (key == 13 && this.nodeName.toLowerCase() == "input") {
      return true;
    } else if (key == 13) {
      return false;
    }
    var allow = false;
    if ((e.ctrlKey && key == 97) ||
    (e.ctrlKey && key == 65)) return true;
    if ((e.ctrlKey && key == 120) ||
    (e.ctrlKey && key == 88)) return true;
    if ((e.ctrlKey && key == 99) ||
    (e.ctrlKey && key == 67)) return true;
    if ((e.ctrlKey && key == 122) ||
    (e.ctrlKey && key == 90)) return true;
    if ((e.ctrlKey && key == 118) ||
    (e.ctrlKey && key == 86) ||
    (e.shiftKey && key == 45)) return true;
    if (key < 48 || key > 57) {
      if (key == 45 && this.value.length == 0) return true;
      // if (key == decimal.charCodeAt(0) &&
      // this.value.indexOf(decimal) != -1) {
      //  allow = false;
      // }
      if (key == decimal.charCodeAt(0))
        allow = allowdecimals;
      if (key != 8 && key != 9 && key != 13 &&
      key != 35 && key != 36 && key != 37 &&
      key != 39 && key != 46) {
        allow = false;
      } else {
        if (typeof e.charCode != "undefined") {
          if (e.keyCode == e.which &&
          e.which != 0) {
            allow = true;
          } else if (e.keyCode != 0 &&
          e.charCode == 0 && e.which == 0) {
            allow = true;
          }
        }
      }
      // if (key == decimal.charCodeAt(0) &&
      // this.value.indexOf(decimal) == -1) {
      //  allow = true;
      // }
      if (key == decimal.charCodeAt(0))
        allow = allowdecimals;
    } else {
      allow = true;
    }
    return allow;
  })
  return this;
}
