// ==ClosureCompiler==
// @output_file_name actions.min.js
// @compilation_level SIMPLE_OPTIMIZATIONS
// ==/ClosureCompiler==

// 	js for car accessories pages.

$(document).ready(function(){

    var fadeSpeed = 300;
	
	$('.hijaxTool').hondaToolbox();

	//set vertical align of span
	$('#accessory-list a span.accessoryTitle').each(function(event) {
		var middlePos = ($(this).parent('a').outerHeight() - $(this).outerHeight()) / 2 + 'px';
		$(this).css('margin-top', middlePos);
	});

	//setup click event for each accessory listed 
	$('#accessory-list a').live('click',function(event) {
	
		event.preventDefault();
			
		if ($(this).parent('li').hasClass('selected')) return false;
			
		//loop through accessory objects set up in xsl
		for (var i = 0, len = accessoryList.length - 1; i <= len; i++) {
			
			if (accessoryList[i].id == $(this).parent('li').attr('id').replace('accessory-','')) {
				// accessory found so pull data
				var selectedAccessory = accessoryList[i];

				//attempt to load the image
				loadImage(selectedAccessory.mainImage);

				$('#accessory').fadeOut(fadeSpeed,function() { 
					$('#accessory h2').html(selectedAccessory.title);
					$('#accessory p:first').html(selectedAccessory.description);			
					$('#accessory p:last strong').html(selectedAccessory.price);						
				});
				
				$('#accessory').fadeIn(fadeSpeed);
				$('#accessory-list li').removeClass('selected');
				
                $(this).parent('li').addClass('selected');			
			}
		}
		
	});		
	
	//open pdf in new window
	$('#accessoryContent a.pdf').click(function(){
		var url = this.href;
		window.open(url);
		return false;
	});
		
	function loadImage(strImagePath) {

		//check to see if we are handling default image 
		if (strImagePath.indexOf('honda-logo') > -1 && $('#accessoryImageWrap img').attr('src').indexOf('honda-logo') > -1) {
			//image already in place so no need to load
			return false;	
		}
								  
		$('#accessoryImageWrap img').fadeOut(fadeSpeed, function() {
			var $img = $(new Image());    
		   
			$img.load(function () {
				$(this).hide();
				$('#accessoryImageWrap').empty().append(this);
				$('#accessoryImageWrap img').fadeIn(fadeSpeed);							  				
			});
		
			$img.error(function () {
				//final catch - if image is not found show default image
				//console.error('Image not found - loading default');
				loadImage('/cars/_assets/presentation/accessories/honda-logo.jpg');
			});
			
			//bind to img src
			$img.attr('src', strImagePath);
		});		
	}
}); 
