
// Function requried to set selected index based on value
function setSelectedIndex(s, v) {
    for ( var i = 0; i < s.options.length; i++ ) {
        if ( s.options[i].value == v ) {
            s.options[i].selected = true;
            return;
        }
    }
}


window.addEvent('domready', function() {

	if($('productImg')) {
			

			var original_img = $('productImg').src;
			var hiding;				
			
			$$('.swapper').each(function(element) {
			
				element.setStyle('cursor','pointer');
				
				element.addEvent('mouseover', function() {					
					hiding = $clear(hiding);						
					var this_src = element.getElement('img').get('src').replace('t_','s_');										
					$('productImg').set('src', this_src);
					
				});
					
				element.addEvent('mouseout', function() {				
					hiding = (function(){ 
						$('productImg').set('src',original_img);												
					}).delay(300);	
				}),this;				
				
		})		
	
	}

	if($('product_color')) {
		
		// Add onclick to swaches to change dropdown
		$$('.colourswatch').each(function(element) {
	
			// Set the defauly property
			element.setProperty('class','colourswatch unselected');
	
			element.addEvent('click', function() { 		
								
				setSelectedIndex($('product_color'),parseInt(this.id.replace('colourThumb', "")));							
				
				// Set the style of every swatch as unselected
				$$('.colourswatch').each(function(swatchElement) {
					swatchElement.setProperty('class','colourswatch unselected');
				})	
							
				// Set this one as selected
				$('colourThumb'+parseInt(this.id.replace('colourThumb', ""))).setProperty('class','colourswatch selected');						
												
			});
				
		})
	
		// Set the initial select state
		var selectedValue = $('product_color').options[$('product_color').selectedIndex].value;		
		$('colourThumb'+selectedValue).setProperty('class','colourswatch selected');
				
		// Add onchange to dropdown to set swatches as active
		$('product_color').addEvent('change', function() {			
			var selectedValue = this.options[this.selectedIndex].value;					
			// Set the style of every swatch as unselected
			$$('.colourswatch').each(function(element) {
				element.setProperty('class','colourswatch unselected');
			})
			// Set this one as selected
			$('colourThumb'+selectedValue).setProperty('class','colourswatch selected');
		})
		
		// Add onchange to dropdown to set swatches as active
		$('product_color').addEvent('keypress', function() {			
			var selectedValue = this.options[this.selectedIndex].value;					
			// Set the style of every swatch as unselected
			$$('.colourswatch').each(function(element) {
				element.setProperty('class','colourswatch unselected');
			})		
			// Set this one as selected
			$('color'+selectedValue).setProperty('class','colourswatch selected');
			
		})
	
	}
		 	
});