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





// This is some code for a giant popup from http://buywithme.com

GiantPopUp = Class.create({
  initialize:
    function(input) {
      this.button = $(input);
      this.dropdown = $('storePopUp');
      this.observe();
    },

  hide:
    function() {
      this.dropdown.hide(); 
      this.button.removeClassName('active');
      Event.stopObserving(document, 'click', this.boundClick);
    },

  show:
    function() {
      this.dropdown.show(); 
      this.button.addClassName('active');
      this.boundClick = this.handleDocumentClick.bind(this)
      Event.observe(document, 'click', this.boundClick);

	  this.load();
    },

  toggle:
    function() {
      if(this.visible()) {
        this.hide();
      } else {
        this.show();
      }
    },

  load:
	function() { 
		     
		// We only want to go to the navigation, if we haven't loaded the navigation.
		// In this case, if we detect the loading graphic, we should ask the server
		if ($('loading-navigation')) {
			
			// Pulls the navigation from the server
			new Ajax.Updater('storePopUp', '/js/store.js', {
				asynchronous: true, 
				evalScripts: true, 
				method:'get'
			});
		}
	},

  visible:
    function() {
      return this.dropdown.visible();
    },

  observe:
    function() {
      this.button.observe('click', this.toggle.bind(this));
    },

  handleDocumentClick:
    function(event) {
      element = Event.element(event);
      if(!element.descendantOf(this.dropdown) && element != this.button) {
        this.hide();
      }
    }
});


function focusFieldInError() {

	f = $$('.fieldWithErrors input')[0];
	if (f == null) { f = $$('input.txt')[0]; };
	if (f != null) { f.focus(); };
} 


function banner_swap() {

	var banner_images = $w('4x bmx dh fixie road');
	var random_val = Math.floor(Math.random()*banner_images.size());

	 $$('body')[0].style.backgroundImage = 'url(/images/template/banner/'+ banner_images[random_val] +'.png)'; 
	
}

// Make sure all links pointing out of the site open in a new window
function open_outbound_links_in_new_window() {

	// First we find all the links in the document
	$$('a').each(function(a) {

		// Check if our link goes within the site and that it's not a link to a feed
		if (!a.host.match(window.location.host) && (a.rel != 'alternate')) {
			// Open in a new window
			a.target = '_blank';
		};
	});
}



// Give focus to the first field with errors or is blank
document.observe('dom:loaded', function() {
    
	banner_swap();
	focusFieldInError();
	 
	// Setup the giant popup
	new GiantPopUp($('storePopUpLink'));
	                               
	open_outbound_links_in_new_window();

})







