// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

var _state_options_ary;

// Make sure the state dropdown and zipcode field are in the correct state
function elementInteractionGeographies(form_id) {

  var country_select = document.getElementById(form_id + '-' + 'country');
  var country_index = country_select.selectedIndex;
  if (!country_index) {
    return false;
  }
  var selected_country = country_select.options[country_index].text;

  var form_name;
  if (form_id.match(/^obj_(\d+)(\w+)$/)) {
    form_name = form_id.match(/^obj_(\d+)(\w+)$/)[2];
  } else {
    form_name = '';
  }

  var state_row = document.getElementById(form_id + '-' + form_name + '[state]_row');
  if (state_row) {
    var state_select = document.getElementById(form_id + '-' + 'state');
    var state_index = state_select.selectedIndex;
    var state_label = document.getElementById(form_id + '-' + 'state_label').firstChild;
  
    var i;
    var num_states = state_select.length;
  
    if (!_state_options_ary) {
      _state_options_ary = new Array();
    }
  
    if (!_state_options_ary[form_id]) {
      _state_options_ary[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[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[form_id][i], null);
          } catch (error_us) { // IE does not follow the standard
            state_select.add(_state_options_ary[form_id][i]);
          }
        }
        state_label.data = 'State *';
        state_select.selectedIndex = state_index;

        // Display the state dropdown row
        state_row.style.display = '';
      break;
  
      case 'Canada':
        // Add provinces
        for (i = 51; i < 63; i++) {
          try {
            state_select.add(_state_options_ary[form_id][i], null);
          } catch (error_ca) { // IE does not follow the standard
            state_select.add(_state_options_ary[form_id][i]);
          }          
        }
        state_label.data = 'Province *';
        state_select.selectedIndex = state_index;

        // 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 + '[zipcode]_row');
  if (zipcode_row) {
    switch (selected_country) {
      case 'United States':
        // Display the zipcode
        if (zipcode_row) {
            zipcode_row.style.display = '';
        }
      break;
    
      default:
        // Hide the zipcode
        if (zipcode_row) {
            zipcode_row.style.display = 'none';
        }
    }
  }
}


// Adjust the labels for the relation name field
function elementInteractionRelationAgentType(form_id) {
  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.data = 'Username/Email *';
      rol_label.data = 'Role';
    break;

    case 'RNST_HELP':
      pat_label.data = 'Open Role *';
      rol_label.data = 'Description';
    break;

    default:
      pat_label.data = 'Username/Email *';
      rol_label.data = 'Role';
  }
}


// Make sure the address dropdown are in the correct state
function elementInteractionDisbursements(form_id) {
  var this_select = document.getElementById(form_id + '-' + '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_account_address_field;
  if (!disbursement_account_address_field) {
    disbursement_account_address_field = document.getElementById(form_id + '-' + 'submit_disbursements_setup[disbursement_account_address]_row');
  }
  var disbursement_bank_address_row;
  if (!disbursement_bank_address_row) {
    disbursement_bank_address_field = document.getElementById(form_id + '-' + 'submit_disbursements_setup[disbursement_bank_address]_row');
  }

  switch (this_selected) {
    case 'DSAC_USCH':
      disbursement_account_address_field.style.display = 'none';
      disbursement_bank_address_field.style.display = 'none';
    break;

    case 'DSAC_USSV':
      disbursement_account_address_field.style.display = 'none';
      disbursement_bank_address_field.style.display = 'none';
    break;

    case 'DSAC_INTL':
      disbursement_account_address_field.style.display = '';
      disbursement_bank_address_field.style.display = '';
    break;

    default:
      disbursement_account_address_field.style.display = 'none';
      disbursement_bank_address_field.style.display = 'none';
      this_select.selectedIndex = 0;
  }
}


// Element specific code to react to user interaction 
function elementInteraction(element_id, form_id) {
  switch (element_id) {
    case 'country':
      elementInteractionGeographies(form_id);
    break;

    case 'child_agent_type':
      elementInteractionRelationAgentType(form_id);
    break;

    case 'disbursement_account_type':
      elementInteractionDisbursements(form_id);
    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]);
      }
    }
  }
}

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 = 'inline';
      }
    }
  }
}

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 setPledgePaymentCheckboxes(form_name, 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(new RegExp(form_name+'-([0-9]{1,})'));
      if (good_id && !e[i].disabled) {
        e[i].checked = value;
      }
    }
  }
}

function updatePledgePaymentAmount(form_name, igg_pct, proc_pct, proc_fee) {
  var sum = 0;
  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(new RegExp(form_name+'-([0-9]{1,})'));
      if (good_id && e[i].checked && !e[i].disabled) {
        sum += parseInt(e[i].value);
      }
    }
  }

  var a = document.getElementById('pledge_payment_amount');
  if (a) {
    if (sum > 0) {
      pay = CurrencyFormatted(sum - sum*(igg_pct+proc_pct)/100.0 - proc_fee);
      var txt = '$'+sum+'&nbsp;-&nbsp;$'+sum+'*('+igg_pct+'%+'+proc_pct+'%)&nbsp;-&nbsp;$'+proc_fee+'&nbsp;=&nbsp;<b>$'+pay+'</b>';
      a.innerHTML = txt
    } else {
      a.innerHTML = '';
    }
  }

  var a = document.getElementById(form_name + '_' + 'gross_cents');
  if (a) {
    a.value = Math.round(sum*100);
  }

  var a = document.getElementById(form_name + '_' + 'platform_fee_cents');
  if (a) {
    a.value = Math.round(sum*igg_pct);
  }

  var a = document.getElementById(form_name + '_' + 'transaction_fee_cents');
  if (a) {
    a.value = Math.round(sum*proc_pct);
  }

  var a = document.getElementById(form_name + '_' + 'delivery_fee_cents');
  if (a) {
    a.value = Math.round(proc_fee*100);
  }

  var a = document.getElementById(form_name + '_' + 'net_cents');
  if (a) {
    a.value = Math.round(pay*100);
  }
}

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 = 'inline';
    } 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 = 'inline';
    } else {
      image_div.style.display = 'none';
    }
  }
}

var _username_has_had_focus = false;
var _password_has_had_focus = false;

// Clear the default text from the username field when first given focus
function quickLoginUsernameFocusHandler() {
  if (!_username_has_had_focus) {
    var username_input = document.getElementById('short_cuts_username');
    username_input.value = '';
    username_input.style.color = '#000000';
    
    _username_has_had_focus = true;
  }
}

// Clear the default text from the password field when first given focus,
// Select text thereafter
function quickLoginPasswordFocusHandler() {
  var password_input = document.getElementById('short_cuts_password');

  if (!_password_has_had_focus) {
    password_input.value = '';
    password_input.style.color = '#000000';

    _password_has_had_focus = true;
  } else {
    password_input.select();
  }
}

var _home_search_has_had_focus = false;

// Clear the default text from the username field when first given focus
function homeSearchFocusHandler() {
  if (!_home_search_has_had_focus) {
    var home_search_input = document.getElementById('home_search_input');
    home_search_input.value = '';
    home_search_input.style.color = '#000000';
    
    _home_search_has_had_focus = true;
  }
}

var _header_search_has_had_focus = false;

// Clear the default text from the username field when first given focus
function headerSearchFocusHandler() {
  if (!_header_search_has_had_focus) {
    var header_search_input = document.getElementById('header_search_input');
    header_search_input.value = '';
    
    _header_search_has_had_focus = true;
  }
}

var _home_signup_has_had_focus = false;

// Clear the default text from the username field when first given focus
function homeSignupFocusHandler() {
  if (!_home_signup_has_had_focus) {
    var home_signup_input = document.getElementById('home_signup_email');
    home_signup_input.value = '';
    home_signup_input.style.color = '#000000';
    
    _home_signup_has_had_focus = true;
  }
}

var _agent_signup_has_had_focus = false;

// Clear the default text from the username field when first given focus
function agentSignupFocusHandler() {
  if (!_agent_signup_has_had_focus) {
    var agent_signup_input = document.getElementById('agent_signup_email');
    agent_signup_input.value = '';
    agent_signup_input.style.color = '#000000';
    
    _agent_signup_has_had_focus = true;
  }
}

// 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 = 'inline';
  }

  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);}});
    } else {
      showAjaxDivOnComplete(divs_to_hide_array, anchor);
    }
  }
}

function showAjaxDivOnComplete(divs_to_hide_array, anchor) {
  hideDivs(divs_to_hide_array);
  if (anchor) {
    jumpToAnchor(anchor);
  }
}

// Show a div
function showDiv(divId) {
  var obj = document.getElementById(divId);
  if (obj) {
    obj.style.display = 'inline';
  }
}

// Hide a div
function hideDiv(divId) {
  var obj = document.getElementById(divId);
  if (obj) {
    obj.style.display = 'none';
  }
}

// Toggle a div
function toggleDiv(divId) {
  var obj = document.getElementById(divId);
  if (obj) {
    if (obj.style.display == 'inline') {
      obj.style.display = 'none';
    } else {
      obj.style.display = 'inline';
    }
  }
}

// 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 = 'inline';
  }
}

// Show an action div
function showActionDiv(divId, curleft, curtop) {
  var obj = document.getElementById(divId);
  if (obj) {
    obj.style.left = (curleft-14) + 'px';
    obj.style.top = (curtop-37) + 'px';
    obj.style.display = 'inline';
  }
}

// Show a message div
function showMessageDiv(divId, curleft, curtop) {
  var obj = document.getElementById(divId);
  if (obj) {
    obj.style.left = (curleft-22) + 'px';
    obj.style.top = (curtop-45) + 'px';
    obj.style.display = 'inline';
  }
}

// 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 = 'inline';
  }
}

// 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 = 'inline';
  }
}

// Show a input field div
function showFieldDiv(divId, curleft, curtop) {
  var obj = document.getElementById(divId);
  if (obj) {
    obj.style.left = (curleft+320+50) + 'px';
    obj.style.top = (curtop) + 'px';
    obj.style.display = 'inline';
  }
}

// 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");
}

// Popup to ensure correct perk/amount inputs
function pledge_perk_and_amount_confirm(formName, formId, perkField, amountField, perksHash) {
  obj = document.getElementById(formId+formName+'-'+amountField);
  if (obj && parseInt(obj.value) > 0) {
    amount_txt = 'a $' + obj.value + ' contribution';
  } else {
    amount_txt = 'no contribution';
  }

  obj = Form.getInputs(formName+'_'+formId, 'radio', formName+'['+perkField+']');
  if (obj.length > 0) {
    checkedObj = obj.find(function(radio) { return radio.checked; })
    if (checkedObj && checkedObj.value != '') {
      perk_txt = 'Perk: ' + perksHash.get(checkedObj.value);
    } else {
      perk_txt = 'No Perk';
    }
    perk_txt += ', and ';
  } else {
    perk_txt = '';
  }

  return 'You have specified ' + perk_txt + amount_txt + '. Please click the button below to continue, or cancel to modify your choices.'
}

// 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;
}

