window.onload = function(){
  $('#hero_box').cycle({
      fx: 'fade',
      speed:    600,
      timeout:  4000,
      cleartypeNoBg: true
  });
  $('#after_market').cycle({
      fx: 'fade',
      speed:    300,
      timeout:  2000
  });
}

var DealerCountries;
var DealerCodeType;
var DealerCurrentCountry;
var DealerCurrentLength;
var DealerFirstClick = true;

$(document).ready(function(){
  
  


  $('#country_select').change(function(){
    var country_name = $('#country_select').val();
   $.get('http://'+document.location.hostname+'/index.php/contact/get_states/'+country_name, function(data){
      $('#state_select').empty();
      $('#state_select').append(data);
    });
    
  });
  $('#errors').ajaxError(function() {
      $(this).text('Triggered ajaxError handler.');
    });

  //handle dealer locator section
  $('#zipcode').focusin(function(){
    if(DealerFirstClick){
      DealerFirstClick = false;
      $(this).css('color','red');
      $(this).val('');
    }
    $('#zipcode').select();
  });

  //load countries
  $.get('http://'+document.location.hostname+'/index.php/contact/get_countries', function(data){
    DealerCountries = eval(data);
  });

  // Dealer Locator auto complete
  $('#zipcode').keyup(function(){
    var cposition = doGetCaretPosition(document.getElementById('zipcode'));
    var content = $('#zipcode').val();
      if(content.match(/^[0-9]{2,5}/)){
        DealerCodeType = "USZip";
        if(content.match(/^[0-9]{5}$/)){
          $(this).css('color','black')
        }else{
          $(this).css('color','red')
        }
      }
      if(content.match(/^[a-zA-Z][0-9]/)){
        DealerCodeType = "CANZip";
        if(content.match(/^[a-zA-Z][0-9][a-zA-Z]\s*[0-9][a-zA-Z][0-9]$/)){
          $(this).css('color','black')
        }else{
          $(this).css('color','red')
        }
      }
      if(content.match(/^[a-zA-Z]{2,}/)){
        if(content.length >= DealerCurrentLength){
          DealerCodeType = "Name";
          noCountryFound = true;
          for(var c in DealerCountries){
            if(DealerCountries[c].name.startsWith(content.substring(0,cposition))){
              content = DealerCountries[c].name;
              DealerCurrentCountry = content;
              noCountryFound = false;
              break;
            }
          }
          if(noCountryFound){content = content.substring(0,cposition);
            $(this).css('color','red');
          }else{
            $(this).css('color','black');
          }
        }
        else{
          content = content.substring(0,cposition);
        }
      }
      DealerCurrentLength = content.length;
      $('#zipcode').val(content);
      setCaretPosition(document.getElementById('zipcode'), cposition);
  });


});

jQuery(document).ready(function($) {
  // We only want these styles applied when javascript is enabled
  $('div.navigation').css({'width' : '300px', 'float' : 'left'});
  $('div.content').css('display', 'block');

  // Initially set opacity on thumbs and add
  // additional styling for hover effect on thumbs
  var onMouseOutOpacity = 0.67;
  $('#thumbs ul.thumbs li').opacityrollover({
    mouseOutOpacity:   onMouseOutOpacity,
    mouseOverOpacity:  1.0,
    fadeSpeed:         'fast',
    exemptionSelector: '.selected'
  });

  // Initialize Advanced Galleriffic Gallery
  var gallery = $('#thumbs').galleriffic({
    delay:                     2500,
    numThumbs:                 8,
    preloadAhead:              8,
    enableTopPager:            false,
    enableBottomPager:         true,
    maxPagesToShow:            7,
    imageContainerSel:         '#slideshow',
    controlsContainerSel:      '#controls',
    captionContainerSel:       '#caption',
    loadingContainerSel:       '#loading',
    renderSSControls:          false,
    renderNavControls:         false,
    playLinkText:              'Play Slideshow',
    pauseLinkText:             'Pause Slideshow',
    prevLinkText:              '&lsaquo; Previous Photo',
    nextLinkText:              'Next Photo &rsaquo;',
    nextPageLinkText:          'Next &rsaquo;',
    prevPageLinkText:          '&lsaquo; Prev',
    enableHistory:             false,
    autoStart:                 false,
    syncTransitions:           true,
    defaultTransitionDuration: 900,
    onSlideChange:             function(prevIndex, nextIndex) {
      // 'this' refers to the gallery, which is an extension of $('#thumbs')
      this.find('ul.thumbs').children()
        .eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
        .eq(nextIndex).fadeTo('fast', 1.0);
    },
    onPageTransitionOut:       function(callback) {
      this.fadeTo('fast', 0.0, callback);
    },
    onPageTransitionIn:        function() {
      this.fadeTo('fast', 1.0);
    }
  });
});

function doGetCaretPosition (ctrl) {
	var CaretPos = 0;	// IE Support
	if (document.selection) {
	ctrl.focus ();
		var Sel = document.selection.createRange ();
		Sel.moveStart ('character', -ctrl.value.length);
		CaretPos = Sel.text.length;
	}
	// Firefox support
	else if (ctrl.selectionStart || ctrl.selectionStart == '0')
		CaretPos = ctrl.selectionStart;
	return (CaretPos);
}
function setCaretPosition(ctrl, pos){
	if(ctrl.setSelectionRange)
	{
		ctrl.focus();
		ctrl.setSelectionRange(pos,pos);
	}
	else if (ctrl.createTextRange) {
		var range = ctrl.createTextRange();
		range.collapse(true);
		range.moveEnd('character', pos);
		range.moveStart('character', pos);
		range.select();
	}
}

if(!String.prototype.startsWith){
    String.prototype.startsWith = function (str) {
        return !this.toLowerCase().indexOf(str.toLowerCase());
    }
}

