// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// Highlights specified div tag
function highlightEffect(element){
    new Effect.Highlight(element, 
                   {
                     startcolor: "#ff0000",
                     duration: 5
                   })
}

var _state_options_ary;

// Make sure the state dropdown and zipcode field are in the correct state
function elementInteractionGeographies(form_id, form_name, prefix) {

  var country_select = document.getElementById(form_id + '-' + prefix + 'country');
  var country_index = country_select.selectedIndex;
  if (!country_index) {
    return false;
  }
  var selected_country = country_select.options[country_index].text;

  var state_row = document.getElementById(form_id + '-' + form_name + '[' + prefix + 'state]_row');
  if (state_row) {
    var state_select = document.getElementById(form_id + '-' + prefix + 'state');
    var state_index = state_select.selectedIndex;
    var state_label = document.getElementById(form_id + '-' + prefix + 'state_label').firstChild;
  
    var i;
    var num_states = state_select.length;
  
    if (!_state_options_ary) {
      _state_options_ary = new Array();
    }
  
    if (!_state_options_ary[prefix]) {
      _state_options_ary[prefix] = new Array();
    }
  
    if (!_state_options_ary[prefix][form_id]) {
      _state_options_ary[prefix][form_id] = new Array();
  
      // Remove and store all states 
      // (start at option 2 since the '>>> Select' and '-------' rows come first
      // (note: hiding doesn't work in IE,  :(  )
      for (i = 2; i < num_states; i++) {
        _state_options_ary[prefix][form_id].push(state_select.options[2]);
        state_select.remove(2);
      }
    } else {
      // Remove and store all states 
      // (start at option 2 since the '>>> Select' and '-------' rows come first
      // (note: hiding doesn't work in IE,  :(  )
      for (i = 2; i < num_states; i++) {
        state_select.remove(2);
      }
    }
  
    switch (selected_country) {
      case 'United States':
        // Add 50 states + DC
        for (i = 0; i < 51; i++) {
          try {
            state_select.add(_state_options_ary[prefix][form_id][i], null);
          } catch (error_us) { // IE does not follow the standard
            state_select.add(_state_options_ary[prefix][form_id][i]);
          }
        }
        state_label.innerHTML = 'State';
        state_select.selectedIndex = state_index-0;

        // Display the state dropdown row
        state_row.style.display = '';
      break;
  
      case 'Canada':
        // Add provinces
        for (i = 51; i < 64; i++) {
          try {
            state_select.add(_state_options_ary[prefix][form_id][i], null);
          } catch (error_ca) { // IE does not follow the standard
            state_select.add(_state_options_ary[prefix][form_id][i]);
          }          
        }
        state_label.innerHTML = 'Province';
        state_select.selectedIndex = state_index-51;

        // Display the state dropdown row
        state_row.style.display = '';
      break;
    
      default:
        // Clear selection when country without states is selected
        state_select.selectedIndex = 0;
      
        // Hide the state dropdown row
        state_row.style.display = 'none';
    }
  }
  
  var zipcode_row = document.getElementById(form_id + '-' + form_name + '[' + prefix + 'zipcode]_row');
  if (zipcode_row) {
    var zipcode_label = document.getElementById(form_id + '-' + prefix + 'zipcode_label').firstChild;

    switch (selected_country) {
      case 'United States':
        // Display the zipcode
        if (zipcode_row) {
            zipcode_row.style.display = '';
        }
        zipcode_label.innerHTML = 'Zipcode';
      break;
    
      default:
        // Display the zipcode
        if (zipcode_row) {
            //zipcode_row.style.display = 'none';
            zipcode_row.style.display = '';
        }
        zipcode_label.innerHTML = 'Postal Code';
    }
  }
}


// Adjust the labels for the relation name field
function elementInteractionRelationAgentType(form_id, form_name) {
  var pat_select = document.getElementById(form_id + '-' + 'child_agent_type');
  var pat_index = pat_select.selectedIndex;
  var pat_selected = pat_select.options[pat_index].value;
  var pat_label = document.getElementById(form_id + '-' + 'name_label').firstChild;
  var rol_label = document.getElementById(form_id + '-' + 'role_label').firstChild;

  switch (pat_selected) {
    case 'RNST_INDV':
      pat_label.innerHTML = 'Name/Email';
      rol_label.innerHTML = 'Role';
    break;

    case 'RNST_HELP':
      pat_label.innerHTML = 'Open Role';
      rol_label.innerHTML = 'Description';
    break;

    default:
      pat_label.innerHTML = 'Name/Email';
      rol_label.innerHTML = 'Role';
  }
}


// Make sure the address dropdown are in the correct state
function elementInteractionDisbursementsAccountType(form_id, form_name) {
  var this_select = document.getElementById('project_disbursement_account_type');
  var this_index = this_select.selectedIndex;
  var this_selected = this_select.options[this_index].value;

  // Make the address fields invisible by default
  var disbursement_domestic_div;
  disbursement_domestic_div = document.getElementById('disbursement_domestic');
  var disbursement_international_div;
  disbursement_international_div = document.getElementById('disbursement_international');

  switch (this_selected) {
    case 'DSAC_USCH':
      disbursement_domestic_div.style.display = 'block';
      $('disbursement_domestic').getElementsBySelector('input').each(function(e) { e.disabled = false });

      disbursement_international_div.style.display = 'none';
      $('disbursement_international').getElementsBySelector('input').each(function(e) { e.disabled = true });
    break;

    case 'DSAC_USSV':
      disbursement_domestic_div.style.display = 'block';
      $('disbursement_domestic').getElementsBySelector('input').each(function(e) { e.disabled = false });

      disbursement_international_div.style.display = 'none';
      $('disbursement_international').getElementsBySelector('input').each(function(e) { e.disabled = true });
    break;

    case 'DSAC_INTL':
      disbursement_domestic_div.style.display = 'none';
      $('disbursement_domestic').getElementsBySelector('input').each(function(e) { e.disabled = true });

      disbursement_international_div.style.display = 'block';
      $('disbursement_international').getElementsBySelector('input').each(function(e) { e.disabled = false });
    break;

    default:
      disbursement_domestic_div.style.display = 'none';
      $('disbursement_domestic').getElementsBySelector('input').each(function(e) { e.disabled = true });

      disbursement_international_div.style.display = 'none';
      $('disbursement_international').getElementsBySelector('input').each(function(e) { e.disabled = true });

      this_select.selectedIndex = 0;
  }
}

// Require Transit Code for Canada and show BSB in its place for Australia.
function elementInteractionDisbursementsBankCountry(form_id, form_name) {
  var this_select = document.getElementById('project_disbursement_bank_country');
  var this_index = this_select.selectedIndex;
  var this_selected = this_select.options[this_index].value;

  var transit_code_label = $('disbursement_international').getElementsBySelector('label[for="project_disbursement_transit_code"]')[0];
  var transit_code_tooltip = $('disbursement_international').getElementsBySelector('tr[id="submit_disbursements_setupproject-project[disbursement_transit_code]_row"]')[0].getElementsByTagName('div')[2];

  if (this_selected == 'CTRY_CA') {
    transit_code_label.innerHTML = 'Transit&nbsp;Code&nbsp;*<br />(8&nbsp;digits)'
    transit_code_tooltip.innerHTML = "Please enter your bank's three digit institution number and its five digit branch number, e.g. '12312345'"
  } else if (this_selected == 'CTRY_AU') {
    transit_code_label.innerHTML = 'BSB&nbsp;*'
    transit_code_tooltip.innerHTML = "Enter your Bank State Branch's six digit number."
  } else {
    transit_code_label.innerHTML = 'Transit&nbsp;Code&nbsp;<br />(8&nbsp;digits)'
    transit_code_tooltip.innerHTML = "Please enter your bank's three digit institution number and its five digit branch number, e.g. '12312345'"
  }
}


// Element specific code to react to user interaction 
function elementInteraction(element_id, form_id, form_name) {
  switch (element_id) {
    case 'country':
      elementInteractionGeographies(form_id, form_name, '');
    break;

    case 'shipping_country':
      elementInteractionGeographies(form_id, form_name, 'shipping_');
    break;

    case 'child_agent_type':
      elementInteractionRelationAgentType(form_id, form_name);
    break;

    case 'disbursement_account_type':
      elementInteractionDisbursementsAccountType(form_id, form_name);
    break;
  }
}

// Page specific initialization
function initPage() {
  var e = document.getElementsByTagName('tr');
  for (var i = 0; i < e.length; i++){
    var id = e[i].id;
    if (id) {
      var info = id.match(/(\w+)-(\w+)\[(\w+)\]_row/);
      if (info && info[1] && info[3]) {
        elementInteraction(info[3], info[1], info[2]);
      }
    }
  }
}

function setVisibleByTypeAndPattern(type, re_pattern) {
  var e = document.getElementsByTagName(type);
  for (var i = 0; i < e.length; i++){
    var id = e[i].id;
    if (id) {
      var good_id = id.match(new RegExp(re_pattern));
      if (good_id) {
        e[i].style.display = 'block';
      }
    }
  }
}

function setContactCheckboxes(value) {
  var e = document.getElementsByTagName('input');
  for (var i = 0; i < e.length; i++){
    var id = e[i].id;
    if (id) {
      var good_id = id.match(/(\w+)-contact_(\w+)/);
      if (good_id && !e[i].disabled) {
        e[i].checked = value;
      }
    }
  }
}

function CurrencyFormatted(amount) {
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}

function setRadioBackground(radio_image, radio_value, this_zone) {
  if (radio_image) {
    radio_image.style.backgroundImage = 'url("/stylesheets/images/radios_' + this_zone + '.PNG")';
    radio_image.style.backgroundPosition = '0px -' + radio_value*22 + 'px';
    radio_image.style.backgroundRepeat = 'no-repeat';
  }
}

function setRadioChecked(radio_name, radio_value) {
  var radio_input = document.getElementById(radio_name + '_' + radio_value);
  if (radio_input) {
    radio_input.checked = 'checked';
  }
}

// Update the span which shows the characters left
function updateChars(fld_id, spn_id, max_len) {
  var fld = document.getElementById(fld_id);
  var spn = document.getElementById(spn_id);

  if (fld && spn) {
    var chars_left = max_len - fld.value.length - fld.value.split('\n').length+1;
    spn.innerHTML = '(' + chars_left + ' characters left)';
  }
}

// Update the username field based on an entered email address
function updateUsernameByEmail(e_id, u_id) {
  var e = document.getElementById(e_id);
  var u = document.getElementById(u_id);

  if (e && u) {
    var i = e.value.indexOf('@')
    if (i >= 0) {
      u.value = String(e.value).substring(0,i);
    } else {
      u.value = e.value;
    }
  }
}

// Make video with given index visible, hide all others
function switchVideo(video_index, num_videos) {
  var video_div;
  for (var i = 0; i < num_videos; i++) {
    video_div = document.getElementById('video' + i);

    if (i == video_index) {
      video_div.style.display = 'block';
    } else {
      video_div.style.display = 'none';
    }
  }
}

// Make image with given index visible, hide all others
function switchImage(image_index, num_images) {
  var image_div;
  for (var i = 0; i < num_images; i++) {
    image_div = document.getElementById('image' + i);

    if (i == image_index) {
      image_div.style.display = 'block';
    } else {
      image_div.style.display = 'none';
    }
  }
}

// Clear the default text from the field when first given focus
function clearIfDefault(obj, default_txt) {
  if (obj && obj.value == default_txt) {
    obj.value = '';
  }
}

// Restore the default text to the field when left empty
function restoreIfEmpty(obj, default_txt) {
  if (obj && obj.value == '') {
    obj.value = default_txt;
  }
}

// Set the value of an object
function setObjValue(objId, objVal) {
  var obj = document.getElementById(objId);
  if (obj) {
    obj.value = objVal;
  }
}

// Set the innerHTML of an object
function setObjInnerHTML(objId, objVal) {
  var obj = document.getElementById(objId);
  if (obj) {
    obj.innerHTML = objVal;
  }
}

// Check if the element contains the spinner or an error message
function needsAjaxUpdate(obj) {
  if (obj) {
    return obj.innerHTML.match(/spinner\.gif/) || obj.innerHTML.match(/support@indiegogo\.com/);
  } else {
    return false;
  }
}

// Show an ajax-able div
function showAjaxDiv(divId, url, divs_to_hide_array, anchor, force) {
  var parts;
  var outer_div_id;
  var outer_div;
  var content_div_id;
  var content_div;
  
  parts = divId.match(/^(\S+)_content(_\S+)$/);
  if (parts && parts[1] && parts[2]) {
    outer_div_id = parts[1] + parts[2];
    content_div_id = divId;
  } else {
    parts = divId.match(/^(\S+)(_id)$/);
    if (parts && parts[1] && parts[2]) {
      outer_div_id = divId;
      content_div_id = parts[1] + '_content' + parts[2];
    }
  }

  outer_div = document.getElementById(outer_div_id);
  if (outer_div) {
    outer_div.style.display = 'block';
  }

  content_div = document.getElementById(content_div_id);
  if (content_div) {
    if (force || needsAjaxUpdate(content_div)) {
      new Ajax.Updater(content_div_id, url, {asynchronous:true, evalScripts:true, method:'get', onComplete:function(){showAjaxDivOnComplete(divs_to_hide_array, anchor);}}); document.body.style.cursor = 'wait'; return false;
    } else {
      showAjaxDivOnComplete(divs_to_hide_array, anchor);
    }
  }
}

function initializeNicEditor() {
  new nicEditor({iconsPath : '/images/nicEditorIcons.gif', buttonList : 		['bold','italic','underline','fontFormat','left','center','right','indent','outdent','ol','ul','hr','undo','redo','link','unlink','image','removeformat','xhtml'], width : 600, maxHeight : 600}).panelInstance('niceditor');
}

function showAjaxDivOnComplete(divs_to_hide_array, anchor) {
  hideDivs(divs_to_hide_array);
  if (anchor) {
    jumpToAnchor(anchor);
  }

  document.body.style.cursor = 'default';
}

// Show a div if the passed value is defined
function showDivIfDefined(divId, value) {
  if (typeof value === 'undefined') {
    hideDiv(divId);
  } else {
    showDiv(divId);
  }
}

// Show a div
function showDiv(divId) {
  var obj = document.getElementById(divId);
  if (obj) {
    obj.style.display = 'block';
  }
}

// Hide a div
function hideDiv(divId) {
  var obj = document.getElementById(divId);
  if (obj) {
    obj.style.display = 'none';
  }

  if (divId.match(/^popupMessage_/)) {
    obj = document.getElementById('popupMessage_global');
    if (obj) {
      obj.style.display = 'none';
    }
  }

  if (divId.match(/^popupFieldMessage_/)) {
    obj = document.getElementById('popupFieldMessage_global');
    if (obj) {
      obj.style.display = 'none';
    }
  }
}

// Toggle a div
function toggleDiv(divId) {
  var obj = document.getElementById(divId);
  if (obj) {
    if (obj.style.display == 'block') {
      obj.style.display = 'none';
    } else {
      obj.style.display = 'block';
    }
  }
}

// Hide an array of divs
function hideDivs(divIds) {
  for (var i = 0; i < divIds.length; i++) {
    hideDiv(divIds[i]);
  }
}

// Fade a div
function fadeDiv(divId) {
  var obj = document.getElementById(divId);
  if (obj) {
    obj.style.filter = 'alpha(opacity=30)';
    obj.style.MozOpacity = .30;
    obj.style.opacity = .30;
  }
}

// Restore a div
function restoreDiv(divId) {
  var obj = document.getElementById(divId);
  if (obj) {
    obj.style.filter = 'alpha(opacity=100)';
    obj.style.MozOpacity = 1;
    obj.style.opacity = 1;
  }
}

// Show a div
function backgroundColorHighlight(divId) {
  var obj = document.getElementById(divId);
  if (obj) {
    obj.style.backgroundColor = '#FFF9D7';
  }
}

// Hide a div
function backgroundColorTransparent(divId) {
  var obj = document.getElementById(divId);
  if (obj) {
    obj.style.backgroundColor = 'transparent';
  }
}

// Show the bar div
function showBarDiv(divId, curleft, curtop) {
  var obj = document.getElementById(divId);
  if (obj) {
    obj.style.left = (curleft-14) + 'px';
    obj.style.top = (curtop-25) + 'px';
    obj.style.display = 'block';
  }
}

// Show an action div
function showActionDiv(divId, curleft, curtop) {
  var obj = document.getElementById(divId);
  if (obj) {
    if (obj.innerHTML.length > 200 || obj.innerHTML.match(/<img/)) {
      obj.style.left = (curleft+25) + 'px';
    } else {
      obj.style.left = (curleft-14) + 'px';
    }
    if (divId.match(/^transcom_/)) {
      obj.style.top = (curtop-77) + 'px';
    } else {
      obj.style.top = (curtop-37) + 'px';
    }
    obj.style.display = 'block';
  }
}

// Show a message div
function showMessageDiv(divId, curleft, curtop) {
  var txt_obj = document.getElementById(divId);
  var obj = document.getElementById('popupMessage_global');
  if (txt_obj && obj) {
    obj.style.left = (curleft-22) + 'px';
    obj.style.top = (curtop-45) + 'px';
    obj.style.display = 'block';
    obj.innerHTML = txt_obj.innerHTML;
  }
}

// Show a tutorial top div
function showTutorialTopDiv(divId, curleft, curtop) {
  var obj = document.getElementById(divId);
  if (obj) {
    obj.style.left = (curleft-40) + 'px';
    obj.style.top = '110px';
    obj.style.display = 'block';
  }
}

// Show a tutorial bottom div
function showTutorialBottomDiv(divId, curleft, curtop) {
  var obj = document.getElementById(divId);
  if (obj) {
    obj.style.left = (curleft-40) + 'px';
    obj.style.top = '345px';
    obj.style.display = 'block';
  }
}

// Show a input field div
function showFieldDiv(divId, curleft, curtop, curwidth) {
  var txt_obj = document.getElementById(divId);
  var obj = document.getElementById('popupFieldMessage_global');
  if (txt_obj && obj) {
    if (curwidth) {
      obj.style.left = (curleft+curwidth+25) + 'px';
    } else {
      obj.style.left = (curleft+320+25) + 'px';
    }
    obj.style.top = (curtop) + 'px';
    obj.style.display = 'block';
    obj.innerHTML = txt_obj.innerHTML;
  }
}

// Show black border around image 
function showBorder(imgrnd, img_type, color) {
  var obj;

  if (img_type == 'mdia') {

    obj = document.getElementById(imgrnd + '_L');
    if (obj) {
      obj.style.backgroundImage = updatedBackgroundImage(obj, 'l', color);
      obj.style.backgroundPosition = '0 0';
      obj.style.backgroundRepeat = 'repeat-y';
    }
    obj = document.getElementById(imgrnd + '_R');
    if (obj) {
      obj.style.backgroundImage = updatedBackgroundImage(obj, 'r', color);
      obj.style.backgroundPosition = '100% 0';
      obj.style.backgroundRepeat = 'repeat-y';
    }
    obj = document.getElementById(imgrnd + '_B');
    if (obj) {
      obj.style.backgroundImage = updatedBackgroundImage(obj, 'b', color);
      obj.style.backgroundPosition = '0 100%';
      obj.style.backgroundRepeat = 'repeat-x';
    }
    obj = document.getElementById(imgrnd + '_BL');
    if (obj) {
      obj.style.backgroundImage = updatedBackgroundImage(obj, 'bl', color);
      obj.style.backgroundPosition = '0 100%';
      obj.style.backgroundRepeat = 'no-repeat';
    }
    obj = document.getElementById(imgrnd + '_BR');
    if (obj) {
      obj.style.backgroundImage = updatedBackgroundImage(obj, 'br', color);
      obj.style.backgroundPosition = '100% 100%';
      obj.style.backgroundRepeat = 'no-repeat';
    }
    obj = document.getElementById(imgrnd + '_TL');
    if (obj) {
      obj.style.backgroundImage = updatedBackgroundImage(obj, 'tl', color);
      obj.style.backgroundPosition = '0 0';
      obj.style.backgroundRepeat = 'no-repeat';
    }
    obj = document.getElementById(imgrnd + '_T');
    if (obj) {
      obj.style.backgroundImage = updatedBackgroundImage(obj, 't', color);
      obj.style.backgroundPosition = '0 0';
      obj.style.backgroundRepeat = 'repeat-x';
    }
    obj = document.getElementById(imgrnd + '_TR');
    if (obj) {
      obj.style.backgroundImage = updatedBackgroundImage(obj, 'tr', color);
      obj.style.backgroundPosition = '100% 0';
      obj.style.backgroundRepeat = 'no-repeat';
    }

  } else {
  
    obj = document.getElementById(imgrnd + '_' + img_type);
    if (obj) {
      obj.style.backgroundImage = updatedBackgroundImage(obj, img_type, color);
      obj.style.backgroundPosition = '100% 100%';
      obj.style.backgroundRepeat = 'no-repeat';
    }

  }
}

function updatedBackgroundImage(obj, img_type, color) {
  var currentBackgroundImage;

  if (obj) {
    if (obj.currentStyle) {
      currentBackgroundImage = obj.currentStyle.backgroundImage;
    } else {
      currentBackgroundImage = getComputedStyle(obj, '').getPropertyValue('background-image');
    }
  } else {
    currentBackgroundImage = '';
  }

  return currentBackgroundImage.replace(/[a-z]*_[a-z]*\.PNG/, img_type + '_' + color + '.PNG');
}

// Get absolute LEFT position of an object
function findLeft(obj) {
  var curleft = 0;
  if (obj && obj.offsetParent) {
    while (1) {
      curleft += obj.offsetLeft;
      if (!obj.offsetParent) {
        break;
      }
      obj = obj.offsetParent;
    }
  }
  else if (obj && obj.x) {
    curleft += obj.x;
  }
  return curleft;
}


// Get absolute TOP position of an object
function findTop(obj) {
  var curtop = 0;
  if (obj && obj.offsetParent) {
    while (1) {
      curtop += obj.offsetTop;
      if (!obj.offsetParent) {
        break;
      }
      obj = obj.offsetParent;
    }
  }
  else if (obj && obj.y) {
    curtop += obj.y;
  }
  return curtop;
}

function jumpToAnchor(anchor) {
   window.location = String(window.location).replace(/\#.*$/, '') + '#' + anchor;
}

function alertPaymentsSetup(payment_types, default_txt) {
  var obj;
  var alert_txt = '';

  for (var i = 0; i < payment_types.length; i++) {
    obj = document.getElementById(payment_types[i]['id']);

    if (obj && obj.checked) {
      alert_txt += '\n\n' + payment_types[i]['message'];
    }
  }

  if (alert_txt != '') {
    alert(default_txt+alert_txt);
  }
}



/*
 * This script depends on the Prototype JavaScript library
 * http://prototypejs.org
 */

var Inflector = Class.create();

Inflector.prototype = {
    /*
     * The order of all these lists has been reversed from the way 
     * ActiveSupport had them to keep the correct priority.
     */
    plural: [
        [/(quiz)$/i,               "$1zes"  ],
        [/^(ox)$/i,                "$1en"   ],
        [/([m|l])ouse$/i,          "$1ice"  ],
        [/(matr|vert|ind)ix|ex$/i, "$1ices" ],
        [/(x|ch|ss|sh)$/i,         "$1es"   ],
        [/([^aeiouy]|qu)y$/i,      "$1ies"  ],
        [/(hive)$/i,               "$1s"    ],
        [/(?:([^f])fe|([lr])f)$/i, "$1$2ves"],
        [/sis$/i,                  "ses"    ],
        [/([ti])um$/i,             "$1a"    ],
        [/(buffal|tomat)o$/i,      "$1oes"  ],
        [/(bu)s$/i,                "$1ses"  ],
        [/(alias|status)$/i,       "$1es"   ],
        [/(octop|vir)us$/i,        "$1i"    ],
        [/(ax|test)is$/i,          "$1es"   ],
        [/s$/i,                    "s"      ],
        [/$/,                      "s"      ]
    ],
    singular: [
        [/(quiz)zes$/i,                                                    "$1"     ],
        [/(matr)ices$/i,                                                   "$1ix"   ],
        [/(vert|ind)ices$/i,                                               "$1ex"   ],
        [/^(ox)en/i,                                                       "$1"     ],
        [/(alias|status)es$/i,                                             "$1"     ],
        [/(octop|vir)i$/i,                                                 "$1us"   ],
        [/(cris|ax|test)es$/i,                                             "$1is"   ],
        [/(shoe)s$/i,                                                      "$1"     ],
        [/(o)es$/i,                                                        "$1"     ],
        [/(bus)es$/i,                                                      "$1"     ],
        [/([m|l])ice$/i,                                                   "$1ouse" ],
        [/(x|ch|ss|sh)es$/i,                                               "$1"     ],
        [/(m)ovies$/i,                                                     "$1ovie" ],
        [/(s)eries$/i,                                                     "$1eries"],
        [/([^aeiouy]|qu)ies$/i,                                            "$1y"    ],
        [/([lr])ves$/i,                                                    "$1f"    ],
        [/(tive)s$/i,                                                      "$1"     ],
        [/(hive)s$/i,                                                      "$1"     ],
        [/([^f])ves$/i,                                                    "$1fe"   ],
        [/(^analy)ses$/i,                                                  "$1sis"  ],
        [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i, "$1$2sis"],
        [/([ti])a$/i,                                                      "$1um"   ],
        [/(n)ews$/i,                                                       "$1ews"  ],
        [/s$/i,                                                            ""       ]
    ],
    irregular: [
        ['move',   'moves'   ],
        ['sex',    'sexes'   ],
        ['child',  'children'],
        ['man',    'men'     ],
        ['person', 'people'  ]
    ],
    uncountable: [
        "sheep",
        "fish",
        "series",
        "species",
        "money",
        "rice",
        "information",
        "equipment"
    ],
    initialize: function() {
        // Nothing here now
    },
    ordinalize: function(number) {
        if (11 <= parseInt(number) % 100 && parseInt(number) % 100 <= 13) {
            return number + "th";
        } else {
            switch (parseInt(number) % 10) {
                case  1: return number + "st";
                case  2: return number + "nd";
                case  3: return number + "rd";
                default: return number + "th";
            }
        }
    },
    pluralize: function(word) {
        for (var i = 0; i < this.uncountable.length; i++) {
            var uncountable = this.uncountable[i];
            if (word.toLowerCase() == uncountable) {
                return uncountable;
            }
        }
        for (var i = 0; i < this.irregular.length; i++) {
            var singular = this.irregular[i][0];
            var plural   = this.irregular[i][1];
            if ((word.toLowerCase() == singular) || (word == plural)) {
                return plural;
            }
        }
        for (var i = 0; i < this.plural.length; i++) {
            var regex          = this.plural[i][0];
            var replace_string = this.plural[i][1];
            if (regex.test(word)) {
                return word.replace(regex, replace_string);
            }
        }
    },
    singularize: function(word) {
        for (var i = 0; i < this.uncountable.length; i++) {
            var uncountable = this.uncountable[i];
            if (word.toLowerCase() == uncountable) {
                return uncountable;
            }
        }
        for (var i = 0; i < this.irregular.length; i++) {
            var singular = this.irregular[i][0];
            var plural   = this.irregular[i][1];
            if ((word.toLowerCase() == singular) || (word == plural)) {
                return singular;
            }
        }
        for (var i = 0; i < this.singular.length; i++) {
            var regex          = this.singular[i][0];
            var replace_string = this.singular[i][1];
            if (regex.test(word)) {
                return word.replace(regex, replace_string);
            }
        }
    }
}

function ordinalize(number) {
    var i = new Inflector;
    return i.ordinalize(number);
}

/*
 * pluralize expects between 2 to 3 arguments.
 * 1. The count of items to pluralize
 * 2. The singular form of the item to pluralize
 * 3. The plural form of the item to pluralize (optional)
 */
function pluralize() {
    var i = new Inflector;
    
    var count    = arguments[0];
    var singular = arguments[1];
    var plural   = arguments[2];
    
    if (arguments.length < 2) return "";
    if (isNaN(count))         return "";
    
    return count + " " + (1 == parseInt(count) ?
            singular :
            plural || i.pluralize(singular));
}

function singularize(plural) {
    var i = new Inflector;
    return i.singularize(plural);
}

function definedValueOrDefault(new_value, default_value) {
  if (typeof new_value === 'undefined') {
    return default_value;
  } else {
    return new_value;
  }
}

function checked_perk_id(formName, formId, perkField) {
  obj = Form.getInputs(formName+'_'+formId, 'radio', formName+'['+perkField+']');
  if (obj && obj.length > 0) {
    checkedObj = obj.find(function(radio) { return radio.checked; })
    if (checkedObj && checkedObj.value != '') {
      perk_id = checkedObj.id;
    } else {
      perk_id = '';
    }
  } else {
    perk_id = '';
  }

  return perk_id;
}

// Popup to ensure correct perk/amount inputs
function pledge_perk_and_amount_confirm(formName, formId, perkField, amountField, emailField, perksHash, pledgeType, userAgent) {
  obj = document.getElementById('confirm_'+formName+'_'+formId+'_continue');
  if (obj) {
    continue_txt = obj.innerHTML;
  } else {
    continue_txt = 'CONTINUE';
  }

  obj = document.getElementById(formId+formName+'-'+amountField);
  if (obj && parseInt(obj.value) > 0) {
    amount_txt = '$' + obj.value;
  } else {
    amount_txt = 'No contribution entered';
  }

  obj = Form.getInputs(formName+'_'+formId, 'radio', formName+'['+perkField+']');
  if (obj && obj.length > 0) {
    checkedObj = obj.find(function(radio) { return radio.checked; })
    if (checkedObj && checkedObj.value != '') {
      perk_txt = perksHash.get(checkedObj.value);
    } else {
      perk_txt = 'No Perk';
    }
  } else {
    perk_txt = '';
  }

  obj = document.getElementById(formId+formName+'-'+emailField);
  if (obj) {
    if (obj.value != '') {
      email_txt = obj.value;
    } else {
      email_txt = 'No email entered';
    }
  } else {
    email_txt = '';
  }

  return_txt = '<table>';
  return_txt += '<tr><td><span class="agHomeTitle">REVIEW & ' + continue_txt + '</span></td></tr>';
  return_txt += '<tr><td><br/>Please review your information below.</td></tr>';
  return_txt += '<tr><td><br/><span class="agLabel">Contribution amount:</span> <span class="agHomeLabel">' + amount_txt + '</span></td></tr>';
  if (perk_txt != '') {
    return_txt += '<tr><td><span class="agLabel">Perk selected:</span>  <span class="agHomeLabel">' + perk_txt + '</span></td></tr>';
  }
  if (email_txt != '') {
    return_txt += '<tr><td><span class="agLabel">Email address:</span>  <span class="agHomeLabel">' + email_txt + '</span></td></tr>';
  }
  return_txt += '<tr><td><br/>Click "' + continue_txt + '" to proceed, or "CANCEL" to modify your choices.</td></tr>';
  return_txt += '</table>';

  return return_txt;
}

// Popup to ensure correct funding_ends_at
function funding_ends_at_confirm(formName, formId, goalField, fundingEndsAtField, defaultFundingEndsAt) {
  objG = document.getElementById(formId+formName+'-'+goalField);
  objFEA = document.getElementById(formId+formName+'-'+fundingEndsAtField);
  if (objG && objFEA) {
    return 'Your funding period is currently set to end on ' + objFEA.value + ' ' + ((objFEA.value) ? '('+pluralize((((new Date(objFEA.value))-(new Date()).stripTime())/1000/60/60/24), 'day')+' from now)' : '') + '.<br/><br/>Please click "Continue" to keep $' + objG.value + ' as your Campaign Goal and ' + objFEA.value + ' as your Campaign Deadline, or click "Cancel" to change them.'
  } else {
    return null
  }
}

// Dynamically update the number of days until a campaign ends when user selects end date
function calendarPrintDaysFromNow(inputId, subtextId) {
  inputField = document.getElementById(inputId);
  daysFromNowSpan = document.getElementById(subtextId);
  daysFromNowSpan.innerHTML = ' '+((inputField.value) ? ' '+pluralize(parseInt(((new Date(inputField.value))-(new Date()).stripTime())/1000/60/60/24), 'day')+' from now' : '')+' ';
}


