/**
 * jQuery Gallery (for Mighty myT) plugin
 * 
 * 
 * @name jquery-mm-gallery.js
 * @author Mighty myT
 * @version 0.5
 * @date November 17, 2010
 * @category jQuery plugin
 * @copyright (c) 2010 Mighty myT (mighty2.com)
 * @license -
 * @example -
 */
(function($) {

	var G = {};
	var _ua = navigator.userAgent.toLowerCase();

	G.os      = {};
	G.browser = {};

	// Judge OS
	if ((_ua.indexOf("windows") > -1) || (_ua.indexOf("win32")>-1)) {
		G.os.windows = true;

	} else if (_ua.indexOf("iphone") > -1) {
		G.os.iphone = true;

	} else if (_ua.indexOf("ipad") > -1) {
		G.os.ipad = true;

	} else if (_ua.indexOf("ipod") > -1) {
		G.os.ipod = true;

	} else if ((_ua.indexOf("macintosh") > -1) || (_ua.indexOf("mac os x") > -1)) {
		G.os.mac = true;

	} else if (_ua.indexOf("linux") > -1) {
		G.os.linux = true;
	}

	// Judge Browser
	G.browser.ie     = _ua.indexOf("msie")>-1;
	G.browser.ie6    = _ua.indexOf("msie 6")>-1;
	G.browser.ie7    = _ua.indexOf("msie 7")>-1;
	G.browser.gecko  = (_ua.indexOf("gecko")>-1) && (_ua.indexOf("safari")==-1);
	G.browser.webKit = _ua.indexOf("applewebkit/")>-1;

	G.options = {
		stayInterval: 3000,
		hideInterval: 5,
		fadeInterval: 100,
		fadeOpacity: 1.0,
		swapType: 4,
		images: []
	};

	G._holder      = new Array();
	G._thumbHolder = new Array();

	G._current   = '';
	G._contentBg = '';

	G.support = {};
	G.support.fixed   = false;
	G.support.scroll  = false;
	G.support.opacity = false;
	G.support.touch   = (G.os.ipad || G.os.iphone || G.os.ipod)?true:false;

	G._thumbOn   = false;
	G._autoOutID = null;
	G._autoInID  = null;
	G._autoFeed  = true;

	G.event = {};
	G.event.DOWN = G.support.touch?'touchstart':'mousedown';
	G.event.UP   = G.support.touch?'touchend':'mouseup';
	G.event.OUT  = G.support.touch?'touchend':'mouseout';
	G.event.MOVE = G.support.touch?'touchmove':'mousemove';

	var isLoaded = false;

	// Functions ///////////////////////////
	/**
	 * 
	 * 
	 */
	G.init = function(options) {
		// Optionの取得
		if(options) {
			applyOption(G.options, options);
		}

		// preload
		if (G.options.list && (G.options.list.length > 0)) {
			for (var i=0; i<G.options.list.length; i++) {
				$('<img>').attr('src', G.options.list[i].full_img);
				$('<img>').attr('src', G.options.list[i].thumb_img);
			}
		} else {
			for (var i=0; i<G.options.images.length; i++) {
				$('<img>').attr('src', G.options.images[i]);
			}
		}

		// Load処理の実行
		$(function() {
			G.load();
		});
	};

	/**
	 * Load
	 *
	 */
	G.load = function() {
		if(isLoaded) {
			return;
		}

		isLoaded = true;
		checkSupport();

		// データの取得
		if (G.options.list && (G.options.list.length > 0)) {
			G.setup(G.options.list);
		} else {
			G.setup();
		}

	};


	/**
	 * 
	 * 
	 */
	G.setup = function(list) {

		// ipad, iphoneの場合の位置調整
		if (G.support.touch) {
			$('#header').css('min-width', '980px');
			$('#logo').css('margin-left', '20px');
			$('#menu').css('margin-right', '30px');
		}

		G._current     = 0;
		G.mainContent  = $('#main_content');
		G.thumbContent = $('#thumb_content');
		G.thumbBox     = $('#thumb');

		var _obj, _id, _cnt;

		if (list && list.length > 0) {
			$('#Footer').animate({height: '60px'});
			$('#PGInfo').animate({bottom: '28px'});
			$('address').animate({bottom: '12px'});

			G._thumbOn = true;
			G.thumbContent.empty();
			for (var i=0,_cnt=list.length; i<list.length; i++) {

				if (i >= 6)
					break;

				_cnt = _cnt - 1;
				_id  = G._holder.length;

				// 背景の設定
				var _obj = $('<img>');
				_obj.attr('id', 'cont' + _id);
				_obj.attr('src', list[i].full_img);
				_obj.css('z-index' ,1001 + _cnt);
				if (i > 0) {
					_obj.css({display: 'none'});
				}

				G.mainContent.append(_obj);
				G._holder.push(_obj);

				// サムネイルの設定
				var _thumbImg = $('<img>');
				_thumbImg.attr('src', list[i].thumb_img);
				_thumbImg.css('z-index' ,2001 + _cnt);

				var _thumbObj = $('<a>');
				_thumbObj.attr('id', 'thumb' + _id);
				_thumbObj.attr('href', list[i].url);
				_thumbObj.append(_thumbImg);
				_thumbObj.mouseover(function() {
						var _targetID = $(this).attr('id').replace('thumb', '');
						if (_targetID == G._current)
							return;

						G._autoFeed = false;

						clearTimeout(G._autoInID);
						clearTimeout(G._autoOutID);
						G._autoInID  = null;
						G._autoOutID = null;

						G.swapContentUnit(_targetID);
				});

				G.thumbContent.append($('<li>').append(_thumbObj));
				G._thumbHolder.push(_thumbObj);
			}

		} else {
			G._thumbOn = false;
			for (var i=0,_cnt=G.options.images.length; i<G.options.images.length; i++) {

				_cnt = _cnt - 1;
				_id  = G._holder.length;

				// 背景の設定
				var _obj = $('<img>');
				_obj.attr('id', 'cont' + _id);
				_obj.attr('src', G.options.images[i]);
				_obj.css('z-index' ,1001 + _cnt);
				if (i > 0) {
					_obj.css({display: 'none'});
				}

				G.mainContent.append(_obj);
				G._holder.push(_obj);
			}
		}

		if (G.support.touch) {
			$(window).bind('orientationchange', function() {
				G.setSize();
			});
		} else {
			$(window).bind('resize', function() {
				G.setSize();
			});
		}
		G.setSize()


		if (G._holder.length > 1) {
			if (G._thumbOn)
				G._thumbHolder[G._current].addClass('active');
			G._autoOutID = setTimeout('MmGallery.fadeoutContentUnit()', G.options.stayInterval);
		}

		if (G._thumbOn) {
			G.thumbBox.fadeIn('slow');
		}


	};

	G.fadeoutContentUnit = function() {
		$('#cont' + G._current).fadeOut(G.options.fadeInterval);
		G._autoInID = setTimeout('MmGallery.fadeinContentUnit()', Math.floor(G.options.fadeInterval/3));
	}

	G.fadeinContentUnit = function() {
		if (G._thumbOn)
			G._thumbHolder[G._current].removeClass('active');
		G._current += 1;
		if (G._current >= G._holder.length)
			G._current = 0;

		if (G._thumbOn)
			G._thumbHolder[G._current].addClass('active');
		G.setSize();

		$('#cont' + G._current).fadeIn(G.options.fadeInterval, function() {
			if (G._autoFeed)
				G._autoOutID = setTimeout('MmGallery.fadeoutContentUnit()', G.options.stayInterval);
		});
	}

	G.swapContentUnit = function(id) {
		$('#cont' + G._current).fadeOut(G.options.fadeInterval/5);
		//$('#cont' + G._current).stop().fadeOut(G.options.fadeInterval/5);
		if (G._thumbOn)
			G._thumbHolder[G._current].removeClass('active');

		G._current = id;
		G.setSize();
		$('#cont' + G._current).fadeIn(G.options.fadeInterval/5);
		if (G._thumbOn)
			G._thumbHolder[G._current].addClass('active');
	}

	/**
	 * 
	 * 
	 */
	G.setSize = function() {

		// 画像
		var _target = $('#cont' + G._current);
		var _dim = G.adjustImage(_target);

		_target.width(_dim.width);
		_target.height(_dim.height);

		if (_target.width() > $(window).width()) {
			_target.css('left', ($(window).width() - _target.width())/2 + 'px');
		} else {
			_target.css('left', '0');
		}

	};

	G.adjustImage = function(obj) {
		var _dim;
		var _rateWin = $(window).width() / $(window).height();

		if (obj.width() && obj.height())
			var _rateImg = obj.width() / obj.height();
		else
			var _rateImg = 1;

		if (G.support.touch) {
			if (Math.abs(window.orientation) === 90) {
				_dim = {
					width: $(window).width(),
					height: 'auto'
				};
			} else {
				_dim = {
					width: 'auto',
					height: ($(window).height()) //'100%'
				};
			}
		} else {
			if (_rateWin.toFixed(5) < _rateImg.toFixed(5)) {
				_dim = {
					width: 'auto',
					height: ($(window).height()) //'100%'
				};
			} else {
				_dim = {
					width: $(window).width(),
					height: 'auto'
				};
			}
		}

		return _dim;
	}

	// Common Function ///////////////////////////////////////////////////////////
	/**
	 *
	 *
	 */
	function checkSupport() {
		var body = document.body
		var div  = document.createElement("div");

		G.support.opacity = typeof div.style.opacity==="string";
		div.style.position = "fixed";
		div.style.margin   = 0;
		div.style.top      = "20px";
		body.appendChild(div,body.firstChild);

		G.support.fixed = (div.offsetTop==20);
		body.removeChild(div);
	}

	/**
	 * Marge Option
	 *
	 */
	function applyOption(original, extension) {
		for(var property in extension) {
			original[property] = extension[property];
		}

		return original;
	}

	function trim(str) {
		return str?str.replace(/(^\s+)|(\s+$)/g, ''):'';
	}

	window.MmGallery = G;
})(jQuery);




