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

/*
This script is copyright (c) 2006 Elliot Swan under the
Creative Commons Attribution-ShareAlike 2.5 license:
http://creativecommons.org/licenses/by-sa/2.5/

More information on this script can be found at:
http://www.elliotswan.com/2006/04/12/move-and-copy/
*/

/* hides the parent of the link that called this */
function dismiss(event) {
  event.target.parentNode.hide();
}

var Move =	{

  copy	:   function(e, target)	{
	    var eId      = $(e);
	    var copyE    = eId.cloneNode(true);
	    var cLength  = copyE.childNodes.length -1;
	    copyE.id     = e+'-copy';

	    for(var i = 0; cLength >= i;  i++)	{
	    if(copyE.childNodes[i].id) {
	    var cNode   = copyE.childNodes[i];
	    var firstId = cNode.id;
	    cNode.id    = firstId+'-copy'; }
	    }
	    $(target).appendChild(copyE);
	    },
  element:  function(e, target, type)	{
	    var eId =  $(e);
	    if(type == 'move') {
	       $(target).appendChild(eId);
	    }

	    else if(type == 'copy')	{
	       this.copy(e, target);
	    }
	    }
}
/* Stateful Links lifted from Jamis on 37signals blog... thank you Jamis! */
/* http://www.37signals.com/svn/archives2/implementing_stateful_links.php */

/* Selektor */
/* special UL drop down list */
/* finds all <select> menu elements with class "Selektor" and replaces them with ul + special interface for dropdown */
var Selektor = {
	
	dropButtonOffset : 25,
	
	init: function() {
		i = 0;
		$$(".Selektor").each(function(div) {
		  // get the select and options
			s = div.firstDescendant();
			options = s.immediateDescendants();
			
			// build the ul
			ul = document.createElement("ul");
			ul.name = 'SelektorUL_' + i;
			lis = [];
			options.each(function(o) {
				li = document.createElement('li');
				a = document.createElement('a');
				text =  document.createTextNode(o.childNodes[0].nodeValue);
				href = (o.value);
				a.appendChild(text);
				a.setAttribute('href', href);
				
				if(o.selected == true) {
				  
					placeHolder = document.createElement('a');
					// Element.addClassName(placeHolder, 'selected');
					placeHolderText = text.cloneNode(true);
					placeHolder.appendChild(placeHolderText);
					// placeHolder.href =  "#";
					
				}	else {
					li.appendChild(a);
				}
				if( o.attributes.selected == true ) {
				  Element.addClassName(li,'selected');
				}
				lis.push(li);
			});
			for(i = 0; i < lis.length; i++ ) { 
			  lia = lis[i];
			  ul.appendChild(lia);
			}
			Element.hide(ul);
			dropButton = document.createElement('a');
			dropButton.name = 'dropButton';
			dropButton.href = '#t';
			Element.addClassName(dropButton, 'dropButton');
			Event.observe($(dropButton), 'click', function(event) { Selektor.toggle(event); });
			Event.observe($(placeHolder), 'click', function(event) { Selektor.toggle(event); });
			Element.addClassName( placeHolder, 'dropButton' );
			div.appendChild(placeHolder);
			// div.appendChild(dropButton);
			div.appendChild(ul);
			Element.remove(s);
			placeHolderWidth = placeHolder.getWidth();
			divWidth = placeHolderWidth + Selektor.dropButtonOffset;
			//div.setStyle({ 'width': divWidth + 'px' });	
		});
	},
	
	toggle: function(event) {
		
		el = Event.element(event);
		sel = el.parentNode;
		
		//placeHolder = sel.firstDescendant();
		dropButton = sel.firstDescendant();
		ul = dropButton.nextSibling;
		
		// placeHolder.toggle();
		 ul.toggle();
		// options = ul.immediateDescendants();
						
		if( ul.visible() ) {
			ulWidth = ul.getWidth();
			divWidth = ulWidth + Selektor.dropButtonOffset;
			Element.addClassName(dropButton, 'dropButtonUp');		
		} else {
			placeHolderWidth = placeHolder.getWidth();
			divWidth = placeHolderWidth + Selektor.dropButtonOffset;
			Element.removeClassName(dropButton, 'dropButtonUp');					
		}
		
		// sel.setStyle({ 'width': divWidth + 'px' });	
		
	}
}


var Nav = {
  
  tabs: Array(),
  activeTab: false,
  showEffect: '',
  hideEffect: '',
  effectDuration: .3,
  
  init: function() {
    // grab all the tabs
    Nav.tabs = $$(".nitro_tab");
    // find out if one is active
    activeTabs = $$("li.nitro_tab.activo");
    if( activeTabs.length > 0 ) {
      Nav.activeTab = activeTabs[0];
    } else {
      Nav.activeTab = false;
    }
    // set the link events to fire "toggle"
    Nav.tabs.each(function(tab) {
      tab_link = tab.firstDescendant();
      Event.observe( tab_link, 'click', function(event) {
        Nav.toggle(event);
        // alert(event);
      });
    });
  },
  toggle: function(event) {
    el = event.element();
    // make sure we have the right tag in case span was clicked
    if (el.tagName.toLowerCase() == 'span') {
      el = el.parentNode;
    }
    tab = el.parentNode;
    Nav.changeTab(tab);
  },
  changeTab: function(newTab) {
    if( Nav.activeTab != false ) {
      // hide the active menu
      tab_menu_to_hide = Nav.activeTab.childElements()[0];
      // remove active class name after animation is done...
      if(tab_menu_to_hide) {
        tab_menu_to_hide.parentNode.removeClassName('activo');
      }
    }
    // show the new menu
    if( Nav.activeTab != newTab ) {
      tab_menu_to_show = newTab.childElements()[1];
      // use first afterUpdate event to add the active class name
      newTab.addClassName('activo');
      // set new active tab
      Nav.activeTab = newTab;
    } else {
      // set active tab to empty
      Nav.activeTab = false;
    }
  }
}

EmailTip = function(message) {
  tipOptions = { 
    stem: 'bottomLeft',
    border: 2,
    borderColor: '#ffffff', 
    offset: { x: 0, y: -50 },
    className: 'email_prototip'
    };
  try {
    tip = new Tip($('email_input_field'), message, tipOptions); // element
    $('email_input_field').prototip.show();
  } catch (e) {
    alert(message);
  }
  //console.log(tip);
}
var OC =  {
  
  hideEffect: '',
  showEffect: '',
  statusHash : '',
  
  init: function( locale, js, jcs, ps, pcs ) {
    OC.statusHash = new Hash();
    OC.statusHash.set('locale',locale)
    OC.statusHash.set('jacket_shortname', js);
    OC.statusHash.set('jacket_color_shortname', jcs);
    OC.statusHash.set('pant_shortname', ps);
    OC.statusHash.set('pant_color_shortname', pcs);
    
    // check for color changes from hash
    if ( window.location.hash != '' && window.location.hash != '#outerwear_top') {
      OC.checkHash();
    }
  },
  
  writeHash: function() {
    h = OC.statusHash;
    ha = [ h.get('jacket_shortname'), h.get('jacket_color_shortname'), h.get('pant_shortname'), h.get('pant_color_shortname') ];
    urlhash = ha.join('/');
    location.hash = '#'+urlhash;
  },
  
  checkHash: function() {
    h = OC.statusHash;
    ha = [ h.get('jacket_shortname'), h.get('jacket_color_shortname'), h.get('pant_shortname'), h.get('pant_color_shortname') ];
    should_be = '#'+ha.join('/');
    actually_is = window.location.hash;
    if( should_be == actually_is ) {
      // nothin
    } else {
      //console.log('needs to change');
      //console.log(should_be);
      //console.log(actually_is);
      hash_value = actually_is.gsub("#",'');
      url_array = [ 'http:/', window.location.host, h.get('locale'), 'outerwear', hash_value ];
      url = url_array.join('/');
      window.location = url;
    }
  },
  
  toggleFeatures: function( target_id, title, tiptarget ) {
    
    target = $(target_id);
    
    message = target.innerHTML;
    //console.log(message);
    
    tipOptions = { 
      borderColor: '#111111',
      offset: { x: 0, y: 50 },
      closeButton: true,
      title: title,
      className: 'outerwear_features'
    };
      
    try {
      tip = new Tip($(tiptarget), message, tipOptions); // element
      $(tiptarget).prototip.show();
    } catch (e) {
      alert(title + ': ' + message);
    }
  },
  
  changeMainImage: function( target_id, new_image_url, short_name, lightbox_link_url ) {
    target = $(target_id);
    if ( target.src != new_image_url ) {
      
      // write to status Hash
      if( target_id == 'main_jacket_image') {
        OC.statusHash.set('jacket_color_shortname', short_name );
      }
      if( target_id == 'main_pant_image') {
        OC.statusHash.set('pant_color_shortname', short_name );
      }
      
      eventScope = target_id + '_event_scope';
      OC.hideEffect = Effect.Fade(target, { queue: { position: 'end', scope: eventScope } } );
      imagePreloader = new Image();
      imagePreloader.onload = function() {        
        target.src = imagePreloader.src;
        var queue = Effect.Queues.get(eventScope);
        queue.each(function(effect) { effect.cancel(); });
        OC.showEffect = Effect.Appear(target, { queue: { position: 'end', scope: eventScope } });
        // change lightbox target
        lightbox_link = target.parentNode;
        lightbox_link.href = lightbox_link_url;
      }
      imagePreloader.src = new_image_url;
      OC.writeHash();
    }
    return false;
  },
  
  rewriteLink: function(outerwear_type, shortname, color_shortname, anchor) {
    h = OC.statusHash;
    if(outerwear_type == 'jacket') {
      h.set('jacket_shortname', shortname);
      h.set('jacket_color_shortname', color_shortname);
    } else {
      h.set('pant_shortname', shortname);
      h.set('pant_color_shortname', color_shortname);
    }
    if (anchor == undefined) { anchor = ''; } // optional anchor to add to the end of the url
    ha = [ 'http:/', window.location.host, h.get('locale'), 'outerwear', h.get('jacket_shortname'), h.get('jacket_color_shortname'), h.get('pant_shortname'), h.get('pant_color_shortname') ];
    url = ha.join('/');
    window.location = url + anchor;
    //console.log(url)
    return false;
  }
  
}



var Scroller = {
  
  objects: '',
  oImages: [],
  loadSkip: 3,
  xTarget: 0,
  animationInterval: '',
  targetElement: '',
  scrollWidth: 0,
  imageDir: '/product_images/boards/m/',
  hrefPrefix:'/en/boards/',
  
  changeTarget: function(el) {
    
    left = $(el).getStyle('left').gsub('px','');
    center = $(el).getStyle('width').gsub('px','');
    percent = left / 800;
    scroll_box = $('scroll_box');
    Scroller.xTarget = Math.round( ( scroll_box.scrollWidth - scroll_box.offsetWidth ) * percent );
    if ( Scroller.animationInterval != '' ) { 
      clearInterval( Scroller.animationInterval ); 
    }
    Scroller.animationInterval = setInterval( "Scroller.scrollCheck()" , 50 );
    
  },
  
  init: function( objectos, image_dir, href_prefix ) {
    // write links
    Scroller.objects = objectos;
    Scroller.imageDir = image_dir;
    Scroller.hrefPrefix = href_prefix;
    
    for(i=0;i<Scroller.objects.length;i++) {
      
      o = Scroller.objects[i];
      a = new Element('a',{ href: Scroller.hrefPrefix + o.shortname , 'id': o.shortname + "_link"  });
      $('scroll_content').insert( a, { position: 'bottom' } );
      
    }
    // start loading
    for(i=0;i<Scroller.loadSkip;i++) {
      Scroller.loadNext(i);
    }
    Scroller.slider = new Control.Slider('scroll_handle', 'scroll_track', {
      onSlide: function(v) { Scroller.scrollHorizontal(v, $('scroll_box'), Scroller.slider); },
      onChange: function(v) { Scroller.scrollHorizontal(v, $('scroll_box'), Scroller.slider); }
    });
    
  },
  
  loadNext: function(n) {      
    o = Scroller.objects[n];
    if(o != undefined) {        
      Scroller.oImages[n] = new Image();
      Scroller.oImages[n].onload = function() {
        o = Scroller.objects[n];
        oname = o.name;
        oname = oname.gsub('PRO ONE-OFF ','');
        oname = oname.gsub('PRO-ONE OFF ','');
        link_id = o.shortname + "_link";
        image = Scroller.oImages[n];
        $( link_id ).insert( image, { position: 'top' });
        $( link_id ).insert( '<br/><h4>'+oname+'</h4>', { position: 'bottom' } );
        Scroller.loadNext( n + Scroller.loadSkip );
        Scroller.scrollWidth += Element.getWidth(image);
        $('scroll_content').setStyle({ width: ( Scroller.scrollWidth + 120 ) + 'px' });
        // console.log($('scroll_content').getWidth() + ' ' + Scroller.scrollWidth);
      }
      o = Scroller.objects[n];
      host = window.location.host;
      // for testing loading from local host = 'test.nitro-snowboards.com';
      img_url =  'http://' + host + Scroller.imageDir + o.shortname + '.jpg'
      Scroller.oImages[n].src = img_url;
      //console.log(img_url);
      Scroller.scrollCheck();
    }
  },
  
  scrollCheck: function() {
    diff = Scroller.xTarget - Scroller.targetElement.scrollLeft;
    Scroller.targetElement.scrollLeft = Scroller.targetElement.scrollLeft + ( ( diff ) / 4 );
    if( Math.abs(diff) < 5 ) {
      clearInterval( Scroller.animationInterval );
    }
  },
  
  // scroll the element horizontally based on its width and the slider maximum value
  scrollHorizontal: function(value, element, slider) {
    Scroller.targetElement = element;
    Scroller.xTarget = Math.round( value/slider.maximum * ( element.scrollWidth - element.offsetWidth ) );
    clearInterval( Scroller.animationInterval );
    Scroller.animationInterval = setInterval( "Scroller.scrollCheck()" , 50 );
  }
  
}
inited = false;
Event.observe(document, 'dom:loaded', function() {
  Nav.init();
  Selektor.init();
  inited = true;
});
Event.observe(window, 'load', function() {
  if(inited == false) {
    Nav.init();
    Selektor.init();
  }
});

var PhotoShow = {
  
  imageArray: [],
  imageFolder: '',
  imageContainer: '',
  imageIDPrefix: '',
  currentIndex: 0,
  nextIndex: 1,
  doneLoading: false,
  
  
  init: function( imageArray, imageFolder, imageIDPrefix, imageContainer ) {
    
    // setup
    PhotoShow.imageArray = imageArray;
    PhotoShow.imageFolder = imageFolder;
    PhotoShow.imageContainer = imageContainer;
    PhotoShow.imageIDPrefix = imageIDPrefix;
    
    // start
    setInterval('PhotoShow.changeImage()',10000);
  },
  changeImage: function() {
    // figure out previous and next
    previousImageId = PhotoShow.imageIDPrefix + PhotoShow.currentIndex;
    nextImageId = PhotoShow.imageIDPrefix + PhotoShow.nextIndex;
    
    // to load, or not to load?
    if(PhotoShow.doneLoading == false) {
      nextImage = new Image();
      nextImage.onload = function() {
        // insert new image
        Element.extend(nextImage);
        nextImage.setStyle('opacity: 0');
        $(PhotoShow.imageContainer).insert( nextImage, { id: nextImageId, position: 'bottom' });
        // fade out the old one
        PhotoShow.fadeThem(PhotoShow.nextIndex, PhotoShow.currentIndex);
      }
      // load it up
      host = window.location.host;
      img_url =  'http://' + host + PhotoShow.imageFolder + PhotoShow.imageArray[PhotoShow.nextIndex];
      nextImage.id = nextImageId;
      nextImage.src = img_url;
      
    } else {
      // all images loaded... what to do?
      PhotoShow.fadeThem(PhotoShow.nextIndex, PhotoShow.currentIndex);
    }
    // insert
    
    // hide image on top (previous image)
    
  },
  fadeThem: function(next,previous) {
    //console.log(next + ' - ' + previous);
    previousImageId = PhotoShow.imageIDPrefix + previous;
    nextImageId = PhotoShow.imageIDPrefix + next;
    new Effect.Opacity(previousImageId, { from: 1, to: 0 });
    new Effect.Opacity(nextImageId, { from: 0, to: 1 });
    PhotoShow.currentIndex = next;
    PhotoShow.nextIndex = PhotoShow.currentIndex + 1;
    if (PhotoShow.nextIndex >= PhotoShow.imageArray.length) { PhotoShow.nextIndex = 0; PhotoShow.doneLoading = true; }
  }

}


