Array.prototype.contains = function(obj) {
  var i = this.length;
  while (i--) {
    if (this[i] === obj) {
      return true;
    }
  }
  return false;
}

function selectReplacement(obj, zindex) {
  obj.className += ' replaced';
  var ul = document.createElement('ul');
  ul.className = 'selectReplacement';
  ul.style.zIndex = zindex;
  var opts = obj.options;
  var selectedOpt = (!obj.selectedIndex) ? 0 : obj.selectedIndex;
  for (var i=0; i<opts.length; i++) {
    var li = document.createElement('li');
    var txt = document.createTextNode(opts[i].text);
    li.appendChild(txt);
    li.selIndex = i;
    li.selectID = obj.id;
    li.onclick = function() {
      selectMe(this);
    };
    if (i == selectedOpt) {
      li.className = 'selected';
      li.onclick = function() {
        this.parentNode.className += ' selectOpen';
        this.onclick = function() {
          selectMe(this);
        };
      };
    }
    if (window.attachEvent) {
      li.onmouseover = function() {
        this.className += ' hover';
      };
      li.onmouseout = function() {
        this.className = 
          this.className.replace(new RegExp(" hover\\b"), '');
      };
    }
    ul.appendChild(li);
  }
  obj.onfocus = function() {
    ul.className += ' selectFocused';
  };
  obj.onblur = function() {
    this.className = 'selectReplacement';
    console.info(this, 'blurred!');
  };
  obj.onchange = function() {
    var idx = this.selectedIndex;
    selectMe(ul.childNodes[idx]);
  };
  obj.onkeypress = obj.onchange;
  obj.parentNode.insertBefore(ul,obj);
}
function selectMe(obj) {
  var lis = obj.parentNode.getElementsByTagName('li');
  for (var i=0; i<lis.length; i++) {
    if (lis[i] != obj) {
      lis[i].className='';
      lis[i].onclick = function() {
        selectMe(this);
      };
   } else {
      setVal(obj.selectID, obj.selIndex);
      obj.className='selected';
      obj.parentNode.className = 
        obj.parentNode.className.replace(new RegExp(" selectOpen\\b"), '');
      obj.onclick = function() {
        obj.parentNode.className += ' selectOpen';
        this.onclick = function() {
          selectMe(this);
        };
      };
    }
  }
}
function setVal(objID,val) {
  var obj = document.getElementById(objID);
  obj.selectedIndex = val;
}
function setForm() {
  var s = document.getElementsByTagName('select');
  for (var i=0; i<s.length; i++) {
    selectReplacement(s[i]);
  }
}
function selectGlass(elem, loc) {
  $('#car-image-boxes div').removeClass('active');
  $(elem).addClass('active');
  $('#damage_location_input').val(loc);
}
function equalHeightHBlockQuotes(container) {
  var tallest = 0;
  container.children('blockquote').each(function() {
    var thisHeight = $(this).height();
    if(thisHeight > tallest) {
      tallest = thisHeight;
    }
  });
  container.height(tallest + 36);
}

function equalHeightVBlockQuotes(container) {
  var total = 0;
  container.children('blockquote').each(function() {
    total += $(this).height();
  });
  container.height(total + 64);
}

function equalHeightSideBySide(container) {
  var c = $(container),
      tallest = 0;
  c.children().each(function() {
    var height = $(this).children().first().height();
    if (height > tallest) {
      tallest = height;
    }
  }).each(function() {
    $(this).children().first().height(tallest);
  });
}

function supports_geolocation() {
  return !!navigator.geolocation;
}

function autoZipCodeInput(position) {
  var latitude = position.coords.latitude;
  var longitude = position.coords.longitude;
  $.ajax({
    type: 'GET',
    url: 'http://ws.geonames.org/findNearbyPostalCodes?lat='+latitude+'&lng='+longitude,
    dataType: 'xml',
    success: function(xml) {
      var zipinput = $('input[name=zipcode]').first()
      zipinput.removeClass('throbber');
      if (zipinput.val() == 'Getting location...') {
        zipinput
          .val($(xml)
               .find('postalcode')
               .first()
               .text()
               );
        }
      }
    })
}

$(document).ready(function() {
  var input_zindex = 150;
  $("#form-table select").selectbox({debug:true});/*each(function(){
    console.log('Converting <select> box: ', this);
    selectReplacement(this, input_zindex);
    input_zindex -= 1;
    });*/
  equalHeightHBlockQuotes($('.info-box > blockquote').parent());
  equalHeightVBlockQuotes($('.side-by-side > .info-box > blockquote').parent());
  $('.side-by-side-container').each(function(){equalHeightSideBySide(this)});
  
  if ($('input[name=zipcode]').not(':hidden').length && supports_geolocation()) { // Attempt geolocation
    var input = $('input[name=zipcode]').first();
    // Allow the user to set the zipcode manually, without acknowledging the geo permission box.
    input.click(function(){
      if (['Getting location...', 'Failed...'].contains($(this).val())) {
        $(this).val(''); // Clear the box if we set it's contents.
        }
      if ($(this).hasClass('throbber')) { $(this).removeClass('throbber'); }
      });
    
    input.val('Getting location...').addClass('throbber');
    navigator.geolocation.getCurrentPosition(autoZipCodeInput, function(e){
      if (input.val() == 'Getting location...') {
        input.val('Failed...');
        }
      input.removeClass('throbber');
      setTimeout(function(){
        if (input.val() == 'Failed...') {
          input.val('');
          }
        }, 3000);
      });
    } // End geolocation attempt
  });

