/*
 * swapImage plugin
 * ver 1.0.0
 *
 * Copyright (c) 2010 Value Communications Inc.
 *
 *
 ***** 利用方法 **********************************
 *
 * マウスオーバーで画像を切り替えたいタグ
 * （imgタグ、または背景画像を指定したタグ）に
 * [attrName]で設定した名前の属性を付け、
 * 下記を値として設定する。
 *
 * フェード効果なし --- "static"
 * フェード効果あり --- "slow" "normal" "fast"
 *
 * 切り替え後の画像には[suffix]で設定した
 * 値を拡張子前に付加しておく。
 * 例）〜_on.gif
 *
 * ※クリッカブルマップの場合フェード機能は無効。
 * 画像名には[suffix]に続けてareaタグの記述順と
 * 合わせた連番を付加する。（最初は1から）
 * 例）〜_on1.gif、〜_on2.gif
 *
 *************************************************
*/

jQuery.fn.extend({
	swapImage: function() {
		var attrName = "sari"; //swapping attribute name
		var suffix = "_on"; //swapping suffix
		
		var swap = function(beforeElm, afterElm) {
			var speed = $(beforeElm).attr(attrName);
			
			//mouseover
			$(beforeElm).mouseover(function(){
				if(speed == "static") {
					afterElm.show();
				}else{
					afterElm.fadeIn(speed);
				}
			});
			
			//mouseout
			$(afterElm).mouseout(function(){
				if(speed == "static") {
					afterElm.hide();
				}else{
					afterElm.fadeOut(speed);
				}
			});
		}
		
		
		//image tag
		$("img["+ attrName+ "]").each(function() {
			if(!$(this).attr("src").match(suffix + ".")) {
				var cloneObj = $(this).clone()
					.insertBefore($(this))
					.attr("src", $(this).attr("src").replace(/(\.[^\.]*$)/, suffix + "$1"))
					.css("position", "absolute")
					.hide();
				
				swap(this, cloneObj);
			};
		})
		
		//background image
		$("*["+ attrName+ "]:not(img, area)").each(function() {
			if(!$(this).css("background-image").match(suffix + ".")) {
				var cloneObj = $(this).clone()
					.insertBefore($(this))
					.css("background-image", $(this).css("background-image").replace(/(\.[^\.]*$)/, suffix + "$1"))
					.css("position", "absolute")
					.hide();
				
				swap(this, cloneObj);
			};
		})
		
		//clickable map
		$("area["+ attrName+ "]").each(function() {
			var imgObj = $("img[usemap='#"+ $(this).parent("map").attr("id")+ "']");
			var areaNum = $(this).parent("map").children().index(this) +1;
			var reg = new RegExp(suffix + "[0-9]*\.");
			var preloadImg = new Image();
			
			if(!imgObj.attr("src").match(reg)) {
				//preload
				preloadImg.src = imgObj.attr("src").replace(/(\.[^\.]*$)/, suffix + areaNum + "$1");
				
				//mouseover
				$(this).mouseover(function(){
					imgObj.attr("src", imgObj.attr("src").replace(/(\.[^\.]*$)/, suffix + areaNum + "$1"))
				});
				
				//mouseout
				$(this).mouseout(function(){
					imgObj.attr("src", imgObj.attr("src").replace(suffix + areaNum, ""))
				});
			};
		})
	}
});

$(function(){
	$().swapImage();
});









