/*A jQuery plugin to perform image rollovers.*/

/*Author: Sensis Agency*/

/*
Uasge: Pass an object to the rollover constructor containing one member named overStateSuffix.
overStateSuffix should be assigned a string value representing the suffix used to name the over-state images.
The expected naming convention is like this: imageOne.jpg / imageOneOver.jpg. In this example we would 
assign the value of 'Over' to overSateSuffix
*/

/*Example: $('#menu a img').rollover({overStateSuffix:'Over'});*/

/*
Known Issues: If this plugin is being used on a shared navigation module, it is assumed that rollover images 
are wrapped in anchor elements and that no anchor href attributes have the same page-file name.
*/

(function($){
	$.fn.rollover = function(options){
		if( ! options.overStateSuffix){
			alert('options.overStateSuffix is required!');
			return this;
		}
		var fileExtensionPattern = /(\.[a-z]{3,4}$)/i;
		var path = window.location.pathname;
		var pageFileName = path.slice((path.lastIndexOf('/') + 1));
		
		//var path = window.location.pathname.slice(1);
		return this.each(function(){
			var $img = $(this);
			var imgSrc = $img.attr('src');
			var $a = $img.parent('a');
			var href = $a.attr('href');
			var hrefFileName;
			var rollSrc = imgSrc.replace(fileExtensionPattern, options.overStateSuffix + '$1');
			if( ! $img.attr('src')){
				alert('selector did not return an image!');
				return false;
			}				
			//if the over-state image is displaying then exit this iteration
			var overStatePattern = new RegExp(options.overStateSuffix + '\\.[a-z]{3,4}$');
			if(overStatePattern.test(imgSrc)){
				return;
			}
			//set active state - assumes shared navigation resource
			if(href.lastIndexOf('/') != -1){
				hrefFileName = href.slice( (href.lastIndexOf('/') +1));
			}
			else{
				hrefFileName = href;
			}
			if(hrefFileName === pageFileName){
				$a.attr('href', 'javascript:;');
				$a.css('cursor', 'default');
				$img.attr('src', rollSrc);
				return;
			}					
			//preload
			var img = new Image();
			img.src = rollSrc;
			//rollover event
	        $img.parents('a').hover(function(){
	            $img.attr('src', rollSrc);
	        }, function(){
	            $img.attr('src', imgSrc);
	        });	
		});
	}
})(jQuery);
