/*

undercurrent - sho uchida photo journal

*/



var baseUrl = 'http://www.shouchida.com/blog/',
	mtp = 'cms/';



/* ----------------------------------------------------
	jQuery extend
---------------------------------------------------- */

(function($) {

	// userAgent
	var ua = navigator.userAgent.toLowerCase();
	$.ua = {
		// IE
		isIE: /msie (\d+)/.test(ua),
		// IE6
		isIE6: /msie (\d+)/.test(ua) && RegExp.$1 == 6,
		// IE9未満
		isLtIE9: /msie (\d+)/.test(ua) && RegExp.$1 < 9,
		// iOS
		isIOS: /i(phone|pod|pad)/.test(ua),
		// iPhone、iPod touch
		isIPhone: /i(phone|pod)/.test(ua),
		// iPad
		isIPad: /ipad/.test(ua),
		// Android
		isAndroid: /android/.test(ua),
		// モバイル版Android
		isAndroidMobile: /android(.+)?mobile/.test(ua)
	};



	// rollover
	$.fn.rollover = function(options) {
		var defaults = {
			over: '_ov',
			current: null,
			currentOver: null
		};
		var settings = $.extend({}, defaults, options);
		var over = settings.over;
		var current = settings.current;
		var currentOver = settings.currentOver;
		return this.each(function() {
			var src = this.src;
			var ext = /\.(gif|jpe?g|png)(\?.*)?/.exec(src)[0];
			var isCurrent = current && new RegExp(current + ext).test(src);
			if (isCurrent && !currentOver) return;
			var search = (isCurrent && currentOver) ? current + ext : ext;
			var replace = (isCurrent && currentOver) ? currentOver + ext : over + ext;
			var overSrc = src.replace(search, replace);
			new Image().src = overSrc;
			$(this).mouseout(function() {
				this.src = src;
			}).mouseover(function() {
				this.src = overSrc;
			});
		});
	};



	// smooth scroll
	$.scroller = function() {
		var self = arguments.callee.prototype;
		if (!arguments[0] || typeof arguments[0] == 'object') {
			self.init.apply(self, arguments);
		} else {
			self.scroll.apply(self, arguments);
		};
	};

	$.scroller.prototype = {
		defaults: {
			hashMarkEnabled: false,
			noScrollSelector: '.noscroll',
			pitch: 10,
			delay: 10
		},

		init: function(options) {
			var self = this;
			var settings = this.settings = $.extend({}, this.defaults, options);
			$('a[href^="#"]').not(settings.noScrollSelector).each(function() {
				var hash = this.hash || '#';
				$(this).click(function(e) {
					e.preventDefault();
					this.blur();
					self.scroll(hash);
				});
			});
		},

		scroll: function(id, options) {
			if (this.timer) this.clearScroll();
			var settings = (options) ? $.extend({}, this.defaults, options) : (this.settings) ? this.settings : this.defaults;
			if (!settings.hashMarkEnabled && id == '#') return;
			var self = this;
			var win = window;
			var $win = $(win);
			var d = document;
			var pitch = settings.pitch;
			var delay = settings.delay;
			var scrollLeft = $win.scrollLeft();
			if (($.ua.isIPhone || $.ua.isAndroidMobile) && win.pageYOffset == 0) win.scrollTo(scrollLeft, (($.ua.isAndroidMobile) ? 1 : 0));
			var scrollEnd = (id == '#') ? 0 : $(id + ', a[name="' + id.substr(1) + '"]').eq(0).offset().top;
			var windowHeight = ($.ua.isAndroidMobile) ? Math.ceil(win.innerWidth / win.outerWidth * win.outerHeight) : win.innerHeight || d.documentElement.clientHeight;
			var scrollableEnd = $(d).height() - windowHeight;
			if (scrollableEnd < 0) scrollableEnd = 0;
			if (scrollEnd > scrollableEnd) scrollEnd = scrollableEnd;
			if (scrollEnd < 0) scrollEnd = 0;
			scrollEnd = Math.floor(scrollEnd);
			if ($.ua.isAndroid && scrollEnd == 0) scrollEnd = 1;
			var dir = (scrollEnd > $win.scrollTop()) ? 1 : -1;
			(function() {
				var callee = arguments.callee;
				var prev = self.prev;
				var current = self.current || $win.scrollTop();
				if (current == scrollEnd || typeof prev == 'number' && (dir > 0 && current < prev || dir < 0 && current > prev)) {
					self.clearScroll();
					return;
				};
				var next = current + (scrollEnd - current) / pitch + dir;
				if (dir > 0 && next > scrollEnd || dir < 0 && next < scrollEnd) next = scrollEnd;
				win.scrollTo(scrollLeft, next);
				self.prev = current;
				self.current = next;
				self.timer = setTimeout(function() {
					callee();
				}, delay);
			})();
		},

		clearScroll: function() {
			clearTimeout(this.timer);
			this.timer = null;
			this.prev = null;
			this.current = null;
		}
	};



	// orientationchange
	var type = ($.ua.isAndroid) ? 'resize' : 'orientationchange';
	$.fn.extend({
		orientationchange: function(fn) {
			return this.bind(type, fn);
		},
		portrait: function(fn) {
			return this.bind(type, function() {
				if (window.orientation === 0) fn();
			});
		},
		landscape: function(fn) {
			return this.bind(type, function() {
				if (window.orientation !== 0) fn();
			});
		}
	});



	// get script root
	$.getScriptRoot = function(filename) {
		var elms = document.getElementsByTagName('script');
		for (var i = elms.length - 1; i >= 0; i--) {
			var src = elms[i].src;
			if (new RegExp('(.*)?' + filename + '([\?].*)?').test(src)) return RegExp.$1;
		};
		return false;
	};

})(jQuery);




/* ----------------------------------------------------
	init
---------------------------------------------------- */

({
	init: function() {
		var self = this;
		$.siteRoot = $.getScriptRoot('common.js');
		this.setDevice();
		this.setOrientation();
		$(function() {
			$.scroller();
		});
		$(window).load(function() {
			self.hideURLTextField();
		});
	},

	setDevice: function() {
		var device = ($.ua.isAndroid) ? 'android'
			: ($.ua.isIPhone) ? 'iphone'
			: ($.ua.isIPad) ? 'ipad'
			: false;
		if (device) $('html').eq(0).addClass(device);
	},

	setOrientation: function() {
		var orientation = (window.orientation === 0) ? 'portrait' : 'landscape';
		var elm = $('html').eq(0).addClass(orientation);
		$(window).portrait(function() {
			elm.removeClass('landscape').addClass('portrait');
		}).landscape(function() {
			elm.removeClass('portrait').addClass('landscape');
		});
	},

	hideURLTextField: function() {
		if (!$.ua.isIPhone && !$.ua.isAndroidMobile) return;
		var win = window;
		if (win.pageYOffset > 0) return;
		var h = $(document).height();
		if ($.ua.isIPhone && h < ((win.orientation === 0) ? screen.availHeight : screen.availWidth)) return;
		if ($.ua.isAndroid && h < Math.ceil(win.outerHeight / win.devicePixelRatio)) return;
		var top = ($.ua.isAndroid) ? 1 : 0;
		var delay = 100;
		setTimeout(function() {
			win.scrollTo(0, top);
		}, delay);
	}
}).init();




/* ----------------------------------------------------
	share open/close
---------------------------------------------------- */

$(function() {

	$('.entry a[class*="share"]').click(function() {
		var shareId = $(this).attr('class');
		if(shareId.indexOf('close')==-1){
			$('#'+shareId+'').show('fast');
			$(this).html('&times; close').addClass('close');
		} else {
			shareId = shareId.slice(0,-5);
			$('#'+shareId+'').hide('fast');
			$(this).html('share').removeClass('close');
		}
		return false;
	});

});




/* ----------------------------------------------------
	navigation rewrite
---------------------------------------------------- */

$(function() {
	$('a[href*="'+mtp+'mt-search.cgi?search="]').each(function() {
		var oriUrl = $(this).attr('href'),
			lo = oriUrl.indexOf('search='),
			loend = oriUrl.indexOf('%2F&__');
		if(loend != -1){
			var lon = oriUrl.slice(lo+7,loend);
		} else {
			var loend = oriUrl.indexOf('&__'),
				lon = oriUrl.slice(lo+7,loend);
		}

		var os = oriUrl.indexOf('offset=');
		if(os!=-1){
			var osnum = oriUrl.slice(os+7,oriUrl.length-1),
				osn = Number(osnum)+1+'/';
		} else {
			var osn = '';
		}

		var newUrl = baseUrl+'location/'+lon+'/'+osn+'';
		$(this).attr('href',newUrl);
		
	});
});




/* ----------------------------------------------------
	archives open/close
---------------------------------------------------- */

$(function() {
	var yhead = $('#archives h4'),
		ylist = $('#archives ul'),
		oc = '#bcbcbc',
		cc = '#878787';

	yhead.css({ cursor: 'pointer', color: ''+oc+'' });
	$('#archives h4:first').css({ color: ''+cc+'' });
	ylist.css({ display: 'none' });
	$('#archives ul:first').css({ display: 'block' });
	
	yhead.hover(function() {
		if($(this).next().is(':hidden')){
			$(this).css({ color: ''+cc+''});
		};
	},function(){
		if($(this).next().is(':hidden')){
			$(this).css({ color: ''+oc+''});
		};
	});

	yhead.click(function() {
		if($(this).next().is(':hidden')){
			ylist.hide('fast');
			$(this).next().show('fast');
			yhead.css({ color: ''+oc+'' });
			$(this).css({ color: ''+cc+'' });
		}
	});
});




/* ----------------------------------------------------
	Twitter
---------------------------------------------------- */

!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");




/**
 * m5LazyDisplay
 *
 * @author       nori (norimania@gmail.com)
 * @copyright    5509 (http://5509.me/)
 * @license      The MIT License
 * @link         https://github.com/5509/m5lazydisplay
 *
 * @Modified     2011-03-05 10:49
 *
 */
;(function($) {

	$.fn.m5LazyDisplay = function(options) {
		var _this = this,
			thisLen = _this.length,
			scrollPos = document.body.scrollTop || document.documentElement.scrollTop,
			clientHeight = $("html").attr("clientHeight"),
			line = clientHeight,
			c = $.extend({
				posFix: 0,
				duration: 400
			}, options),
			imgObjs = [],
			currentImg = 0;
			
		for ( var i=0; i<_this.length; i++ ) {
			imgObjs[i] = {};
			imgObjs[i].y = $(_this[i]).offset().top;
			imgObjs[i].obj = $(_this[i]);
			
			if ( (scrollPos + clientHeight) < imgObjs[i].y ) {
				imgObjs[i].obj.css("opacity", 0);
			} else {
				currentImg++;
			}
		}
		
		imgObjs.sort(
			function(a, b) {
				return a.y - b.y;
			}
		);
		
		$(window)
			.resize(function() {
				clientHeight = document.body.clientHeight || document.documentElement.clientHeight;
			})
			.bind("scroll.LazyDisplayScroll", function() {
				if ( currentImg === thisLen ) {
					$(window).unbind("scroll.LazyDisplayScroll");
					return false;
				}
				scrollPos = document.body.scrollTop || document.documentElement.scrollTop;
				while ( imgObjs[currentImg].y <= (scrollPos + c.posFix + clientHeight) ) {
					imgObjs[currentImg].obj.fadeTo(c.duration, 1);
					currentImg++;
					if ( currentImg === thisLen ) {
						$(window).unbind("scroll.LazyDislayscroll");
						break;
					}
				}
			});
	}

})(jQuery);

$(function() {
	if(!$.ua.isIPhone && !$.ua.isIPad){$(".entry img").m5LazyDisplay();}
});
