// 
//  project.js v0.3.3
//

var Project = function(){

	this.devMode = false;	// development mode (toggle navigation)
	
	this.containerWidth = 1024;	// div#container's width (for getViewportRect)
	
	this.jsPath = '/js/';
	
	this.sharedImagesPath = '/images/shared/';
	
	this.checkOS = {
		ios:this.isUserAgent('iPhone') || this.isUserAgent('iPod'),
		android:this.isUserAgent('Android'),
		//android1x:this.isUserAgent('Android 1'),
		//android2x:this.isUserAgent('Android 2'),
		win:this.isUserAgent('Win'),
		mac:this.isUserAgent('Mac')
	}
	this.checkBrowser = {
		//iphone:this.isUserAgent('iPhone'),
		//ipodtouch:this.isUserAgent('iPod'),
		//opera:this.isUserAgent('Opera'),
		//chrome:this.isUserAgent('Chrome'),
		//firefox:this.isUserAgent('Firefox'),
		//safari:this.isUserAgent('Safari'),
		ie6:this.isUserAgent('MSIE 6'),
		ie7:this.isUserAgent('MSIE 7'),
		ie:this.isUserAgent('MSIE')
	}
	this.preloadedImages = [];
}

Project.prototype = {

	// basic methods
	
	init:function(){
		//this.loadScript();
		this.setRollover();
		this.setCrossfade();
		this.setTargetBlank();
		this.setScroll();
		this.setBlur();
		this.setImgSizer();
	},	
	/*loadScript:function(){
		// js files
		var scripts = [
			'SCRIPT_FILE_NAME'
		];
			
		if(this.checkBrowser.ie6){
			scripts.push('SCRIPT_FILE_NAME');
		}
		
		for(var i = 0; i < scripts.length; i++){
			var element = this.create('script');
			element.src = [this.jsPath, scripts[i]].join('');
			element.type = 'text/javascript';
			document.body.appendChild(element);
		}
	},*/
	setRollover:function(){
		// add 'class="rollover"' in img or input tags
		var images = $('.rollover');

		if(!images.length) return;
		
		var offSuffix = "_off.";	// e.g. button-off.gif
		var onSuffix = "_on.";	// e.g. button-on.gif

		this.preloadImage('','.rollover',offSuffix,onSuffix);

		for(var i = 0; i < images.length; i++){
			if(images[i].getAttribute("src").match(offSuffix)){
				images[i].onmouseover = function(){
					this.setAttribute("src", this.getAttribute("src").replace(offSuffix,onSuffix));
				}
				images[i].onmouseout = function(){
					this.setAttribute("src", this.getAttribute("src").replace(onSuffix,offSuffix));
				}
			}
		}	
	},
	preloadImage:function(url,selector,offSuffix,onSuffix){
		var images = this.preloadedImages;
		var image;
		
		if(selector){
			// for rollover images		
			$(selector).each(function(){
				image = new Image();
				image.src = $(this).attr('src').replace(offSuffix,onSuffix);
				images.push(image);
			});
		}else if(url){
			// for other image
			if(this.isArray(url)){
				for(var i = 0; i < url; i++){
					image = new Image();
					image.src = url[i];
					images.push(image);					
				}
			}else{
				image = new Image();
				image.src = url;
				images.push(image);				
			}			
		}
	},
	setCrossfade:function(){
		// add 'class="crossfade"' in img or input tags
		var offImages = $('.crossfade');
		
		if(!offImages.length) return;
		
		var offSuffix = "_off.";	// e.g. button-off.gif
		var onSuffix = "_on.";	// e.g. button-on.gif

		this.preloadImage('','.crossfade',offSuffix,onSuffix);

		var offImage = {
			obj:{},
			top:0,
			left:0,
			width:0,
			height:0
		}
		
		var onImage = {
			obj:{},
			src:''
		}
		
		var beacon = {
			obj:{},
			html:'',
			className:'',	
			top:0,
			left:0
		}
		
		var offSuffix = "_off.";	// e.g. button_off.gif
		var onSuffix = "_on.";	// e.g. button_on.gif
		var fadeTime = 300;
		var blankSrc = [this.sharedImagesPath, 'blank.gif'].join('');

		var diffTop = 0;
		var diffLeft = 0;

		for(var i = 0; i < offImages.length; i++){
			
			offImage.obj = $(offImages[i]);
			
			offImage.top = offImage.obj.position().top;
			offImage.left = offImage.obj.position().left;
			offImage.width = offImage.obj.attr('width');
			offImage.height = offImage.obj.attr('height');

			beacon.className = ['crossfadeBeacon', i].join('');

			beacon.html = ['<img src="', blankSrc, '" width="', offImage.width, '" height="', offImage.height, '" alt="" class="', beacon.className, '" style="position:absolute;" />'].join('');

			$(offImage.obj).after(beacon.html);
					
			beacon.obj = $('.' + beacon.className);
			
			beacon.top = beacon.obj.position().top;
			beacon.left = beacon.obj.position().left;
			
			diffTop = offImage.top - beacon.top;
			diffLeft = offImage.left - beacon.left;
							
			beacon.obj.hide();
			
			onImage.src = offImage.obj.attr('src').replace(offSuffix, onSuffix);
		
			onImage.obj = offImage.obj.clone().attr({
				src:onImage.src
			}).css({
				display:'none',
				position:'relative',
				marginTop:diffTop,
				marginLeft:diffLeft
			});
		
			offImage.obj.after(onImage.obj);
		
			offImage.obj.mouseover(function(){
				$(this).next().fadeIn(fadeTime);
			});
			onImage.obj.mouseleave(function(){
				$(this).fadeOut(fadeTime);
			});
		}
	},
	setTargetBlank:function(){
		$('a[rel="external"][href]').attr('target', '_blank');	
	},
	setScroll:function(){
		if(!$('a[href^="#"]')) return;

		var durationTime = 500;
		var easingType = 'easeInOutCirc';

		$('a[href^="#"]').click(function(){
			var target = $(this).attr('href');

			if(target == "#"){
				$(this).blur();		
				$('html, body').animate({ scrollTop:0 }, durationTime, easingType);
				return false;
			}
					
			var targetOffset = $(target).offset().top;
					
			$(this).blur();
			$('html,body').animate({ scrollTop:targetOffset }, durationTime, easingType);
			
			return false;
		});
	},
	setBlur:function(){
		if(this.checkBrowser.ie){
			$('a').focus(function(){this.blur();});
		}
	},
	openPopup:function(linkObj, url, width, height, name){
		if(!linkObj || !url){
			alert('openPopup:params are not found');
			return;
		}
		
		if(!$(linkObj).length) return;
		
		width = width || 600;
		height = height || 500;
		name = name || 'popup';
	
		var params = ["width=", width, ",height=", height, ",toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes"].join('');
		
		$(linkObj).click(function(){
			window.open(url, name, params);
			return false;
		});
	},
	closePopup:function(linkObj){
		if(!linkObj){
			alert('closePopup:params are not found');
			return;
		}
		
		var button = $(linkObj);
		if(!button.length) return;
		
		button.click(function(){
			window.close();
		});
	},
	setImgSizer:function(){
		// source from Fluid Images : http://unstoppablerobotninja.com/entry/fluid-images/
		if(!(this.checkBrowser.ie6 || this.checkBrowser.ie7)) return;
		this.imgSizer = {
			Config: {
				imgCache: [],
				spacer: this.sharedImagesPath + 'blank.gif'
			},
			collate: function(aScope) {
				var isOldIE = (document.all && !window.opera && !window.XDomainRequest) ? 1 : 0;
				if (isOldIE && document.getElementsByTagName) {
					var c = this;					
					var imgCache = c.Config.imgCache;
		
					var images = (aScope && aScope.length) ? aScope : document.getElementsByTagName("img");
					for (var i = 0; i < images.length; i++) {
						images[i].origWidth = images[i].offsetWidth;
						images[i].origHeight = images[i].offsetHeight;
		
						imgCache.push(images[i]);
						c.ieAlpha(images[i]);
						//images[i].style.width = "100%";
					}
		
					if (imgCache.length) {
						c.resize(function() {
							for (var i = 0; i < imgCache.length; i++) {
								var ratio = (imgCache[i].offsetWidth / imgCache[i].origWidth);
								imgCache[i].style.height = (imgCache[i].origHeight * ratio) + "px";
							}
						});
					}
				}
			},
			ieAlpha: function(img) {
				var c = this;
				if (img.oldSrc) {
					img.src = img.oldSrc;
				}
				var src = img.src;
				img.style.width = img.offsetWidth + "px";
				img.style.height = img.offsetHeight + "px";
				img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')"
				img.oldSrc = src;
				img.src = c.Config.spacer;
			},
			// Ghettomodified version of Simon Willison's addLoadEvent() -- http://simonwillison.net/2004/May/26/addLoadEvent/
			resize: function(func) {
				var oldonresize = window.onresize;
				if (typeof window.onresize != 'function') {
					window.onresize = func;
				} else {
					window.onresize = function() {
						if (oldonresize) {
							oldonresize();
						}
						func();
					}
				}
			}
		}
	},
	
	// utilities
	
	isUserAgent:function(ua){
		return navigator.userAgent.indexOf(ua) != -1;
	},
	getElement:function(str){
		//str.replace('#', '');
		return document.getElementById(str);	
	},
	create:function(tagName){
		return document.createElement(tagName);
	},
	hasExistenceOf:function(str){
		var flag = this.getElement(str);
		if(flag){			
			return flag;
		}else{
			flag = $(str).length;
			return flag;
		}
		return false;
	},
	isArray:function(value){
		return value instanceof Array;
	},
	toInt:function(num){
		var value = Math.floor(Math.abs(num));
		num < 0 ? value = -value : value = value;
		return value;
	},
	
	// development tools
	
	testNav:function(){
		if(this.checkBrowser.ie6 || this.checkOS.ios || this.checkOS.android) return;
		var htmlStr = '<div id="TESTNAV" style="position:fixed;z-index:999999;bottom:0px;right:-153px;font-size:9px;background:black;opacity:0.8;width:150px;height:35px;padding:10px 10px 10px 20px;"></div>';
		$('body').append(htmlStr);
		var nav = $('#TESTNAV');
		nav.load('/_testnav.html');
		nav.mouseover(function(){
			$(this).css({right:'0px',height:'auto'});			 
		});
		nav.mouseleave(function(){
			$(this).css({right:'-153px',height:'35px'});
		});
	},
	benchmarkFunction:function(fn,arg,time){
		time = time || 1000000;
		var t = new Date().getTime();
		for(var i=0;i<time;i++)fn(arg);		
		alert(new Date().getTime()-t);
	}
}

var MR = new Project();

MR.fn = {}

// basic functions

MR.fn = {
	setPngFix:function(selector){
		if(!MR.checkBrowser.ie6)return;
		//$('img.pngfix').pngFix();
		DD_belatedPNG.fix(selector);
	},
	resizeImageForIE:function(){
		if(!(MR.checkBrowser.ie6 || MR.checkBrowser.ie7)) return;
		MR.imgSizer.collate($('img[class*=resize]'));
	},
	setCookie:function(newValue){
		if(!navigator.cookieEnabled) return;
		
		var date = '';
		var expire = 1; // days
		var cookieValue = MR.fn.getCookie();
	
		var dateObj = new Date();
		dateObj.setTime(dateObj.getTime() + expire * 24 * 60 * 60 * 1000);
		//dateObj.setTime(dateObj.getTime() + 10 * 60 * 1000);
		
		date = 	dateObj.toGMTString();
	
		if(cookieValue){
			cookieValue += "," + newValue;	
		}else{
			cookieValue = newValue;
		}
		
		document.cookie = ['VALUE_NAME=', cookieValue, ';expires=', date, ';path=/'].join('');
		
		return true;
	},
	getCookie:function(){
		if(!navigator.cookieEnabled) return;
	
		var cookie = document.cookie;
		var name = "VALUE_NAME="
		var matchStr = new RegExp(name + "[^;]*");
		var value;
		
		if(cookie.indexOf('voted') != -1){
			value = cookie.match(matchStr) + "";
			value = value.replace(name, '');
			return value;
		}
	},
	scrollToPosition:function(pos, time){
		var easingType = 'easeInOutCirc';
		time = time || 1000;
		pos = pos || 0;
		
		$('html, body').animate({ scrollTop:pos}, time, easingType);
	},
	hideScrollbar:function(){
		if(MR.checkBrowser.ie6 || MR.checkBrowser.ie7){
			document.body.setAttribute('scroll','no');
			$('html').addClass('noscroll');
		}else{
			$(document.body).addClass('noscroll');
		}
	},
	showScrollbar:function(){
		if(MR.checkBrowser.ie6 || MR.checkBrowser.ie7){
			document.body.setAttribute('scroll','yes');			
			$('html').removeClass('noscroll');
		}else{
			$(document.body).removeClass('noscroll');
		}
	},
	getScroll:function(){
		return {
			x:document.body.scrollLeft || document.documentElement.scrollLeft,
			y:document.body.scrollTop || document.documentElement.scrollTop
		}
	},
	getViewportRect:function(){
		var windowWidth, windowHeight, tmpWidth, tmpHeight;
	
		if(MR.checkBrowser.ie){
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else {
			windowWidth = tmpWidth = window.innerWidth;
			windowHeight = tmpHeight = window.innerHeight;

			if(document.body.offsetHeight > tmpHeight){
				windowWidth = tmpWidth - 16;
			}
			if(MR.containerWidth > tmpWidth){
				windowHeight = tmpHeight - 16;
			}
		}

		var scrl = MR.fn.getScroll();
	
		return {
			x:scrl.x,
			y:scrl.y,
	 		width:windowWidth,
	 		height:windowHeight
		}
	},
	parseFromString:function(xml){
		var root;
		if(window.DOMParser){
			var xmldom = new DOMParser();
			xmldom.async = false;
			var dom = xmldom.parseFromString(xml, "application/xml");
			if (!dom) return;
			root = dom.documentElement;
		}else if(window.ActiveXObject){
			xmldom = new ActiveXObject('Microsoft.XMLDOM');
			xmldom.async = false;
			xmldom.loadXML(xml);
			root = xmldom.documentElement;
		}
		return root;
	},
	getSWF:function(swfName){	// for External Interface
		if(MR.checkBrowser.ie){
			return window[swfName];
		} else {
			return document[swfName];
		}
	},
	setFooter:function(){
		var footer = $('#footer');
		
		if(MR.hasExistenceOf('#contents.works')){
			var headerHeight = 100;
			var contentsHeight = $('#contents').outerHeight();
			var winObj = $(window);

			var margin = 20;
			var offset = 10;
			
			var threshold = headerHeight + contentsHeight + margin;			
						
			var vp = MR.fn.getViewportRect;
					
			var vpHeight = vp().height;
			var vpY = vp().y;
			var currentBottom = vpHeight + vpY;

			footer.addClass('fixed');
			
			if(currentBottom < threshold){
				var diff = currentBottom - threshold;
				footer.css('bottom', diff + offset);
			}
			
			winObj.scroll(function(){
				vpHeight = vp().height;
				vpY = vp().y;
				currentBottom = vpHeight + vpY;
				
				if(currentBottom < threshold){
					footer.removeClass('fixed');
				}else{
					//footer.addClass('fixed');
					//footer.css('bottom', offset);					
				}
			});
			
			winObj.resize(function(){
				vpHeight = vp().height;
				vpY = vp().y;
				currentBottom = vpHeight + vpY;

				footer.addClass('fixed');

				if(currentBottom < threshold){
					var diff = currentBottom - threshold;
					footer.css('bottom', diff + offset);
				}else{
					footer.css('bottom', offset);					
				}
			});
		}
		
		MR.fn.setPngFix('#footer img');
		
		var timer = setTimeout(function(){
			footer.fadeIn(500);
			clearTimeout(timer);
		},200);
	},
	setTopButton:function(){
		if(MR.hasExistenceOf('#contents.works')) return;
		var top = $('#top');
		var winObj = $(window);	
		var vp = MR.fn.getViewportRect;
		var timer;
		var delayTime = 200;
		
		MR.fn.setPngFix('#top img');
		
		MR.fn.positTopButtonX(top, vp);
		MR.fn.positTopButtonY(top, vp);
				
		winObj.scroll(function(){
													 
			clearTimeout(timer);
			
			timer = setTimeout(function(){
				MR.fn.positTopButtonY(top, vp);																
			},delayTime);
			
		});
		
		winObj.resize(function(){
			
			MR.fn.positTopButtonX(top, vp);
													 
			clearTimeout(timer);
			
			timer = setTimeout(function(){
				MR.fn.positTopButtonY(top, vp);		
			},delayTime);
			
		});
		
	},
	positTopButtonX:function(top, vp){
		var width = vp().width;
		var diff = width - MR.containerWidth -15;
		
		if(diff < 0){
			top.css('right', diff);
		}else{				
			top.css('right', 0);
	}
	},
	positTopButtonY:function(top, vp){
		var y = vp().y;
		var height = vp().height;
		var offset = 72;
		
		top.animate({
			top: height * 4 / 5 + y	- offset					
		}, 600, 'easeInOutBack');
	},
	setEntryClass:function(){
		$('.text p:last-child').addClass('last');
	},
	setInfoEntries:function(){
		var contents = $('#contents');
		var info = $('#info');
		var entry = $('.entry');
		var clonedEntry = [];
		
		var entriesHeight = {
			info1:0,
			info2:0,
			info3:0
		}
		var entryHeight = 0;
		var entryMargin = 10;
		
		entry.hide();
		
		contents.append('<div id="info1" class="entries"></div><div id="info2" class="entries"></div><div id="info3" class="entries"></div>');
		
		entry.each(function(){
			var thisEntry = $(this);
			var height = thisEntry.outerHeight();
			var isCloned = false;
			
			var min = Math.min(entriesHeight['info1'],entriesHeight['info2'],entriesHeight['info3']);
			
			for(var i=1; i<4; i++){
				var targetID = 'info' + i;

				if(!isCloned && min == entriesHeight[targetID]){
					clonedEntry.push(thisEntry.clone().appendTo('#' + targetID));
					thisEntry.remove();
										
					entriesHeight[targetID] += height;					
					isCloned = true;
				}
			}				
		});
		
		$('#info').remove();
		
		MR.fn.setEntryClass();
		MR.fn.showEntries(clonedEntry);
	},
	showEntries:function(clonedEntry){
		var entry = $(clonedEntry);
		var entryIndex = 0;
		var duration = 500;
		
		if(!entry.length) return;
				
		var timer = setInterval(function(){
			if(entryIndex < entry.length){
		
				$(entry[entryIndex]).fadeIn(duration);
				entryIndex += 1;
	
			}else{
								
				clearInterval(timer);
				$('#paging').fadeIn(duration);
				
			}
		}, 100);
	},
	setTopEntry:function(){
		MR.fn.setPngFix('.cut');
		
		var cols = $('.col1:not(.placeholder), .col2:not(.placeholder), .col3:not(.placeholder), .col4:not(.placeholder), .col5:not(.placeholder)');
		
		cols.mouseover(function(){
			var thisEle = $(this);
			thisEle.addClass('on');
			if(MR.checkBrowser.ie6){
				thisEle.find('.top').css('background-position', 'bottom left');
			}
		});

		cols.mouseleave(function(){
			$(this).removeClass('on');
		});
		
		cols.click(function(){
			var path = $(this).find('a').attr('href');
			window.location.href = path;
		});
	},
	setWorks:function(){
		MR.fadeDuration = 400;
		MR.worksList = $('#works').find('li');
		MR.copyrightEle = $('#copyright');
		
		var total = MR.worksList.length;
		MR.current = 1;
	
		MR.copyrightEle.text($('.here').find('img').attr('alt'));	
	
		if(total < 2) return;
				
		$('#total').text(total);
		
		MR.currentEle = $('#current');
		var prev = $('#prev');
		var next = $('#next');
		
		MR.worksList.find('img').css('cursor', 'pointer');
		//prev.css('cursor', 'pointer');
		//next.css('cursor', 'pointer');
		
		MR.worksList.click(function(){
			MR.fn.showNextWorks(this);
		});
		
		/*prev.click(function(){
			MR.fn.showPrevWorks($('.here'));
		});
		
		next.click(function(){
			MR.fn.showNextWorks($('.here'));
		});*/
		
	},
	showPrevWorks:function(thisEle){
		var here = $(thisEle);
		var prev = $(thisEle).prev();
				
		if(!prev.length){
			prev = MR.worksList.eq(prev.length - 1);
			MR.current =  MR.worksList.length;
		}else{
			MR.current -= 1;
		}

		here.removeClass('here');
		here.fadeOut(0,function(){
														
			prev.fadeIn(MR.fadeDuration);
			
			MR.copyrightEle.text(prev.find('img').attr('alt'));				
			MR.currentEle.text(MR.current);
			
			MR.fn.setFooter();
			
		});
		
		prev.addClass('here');
		
	},
	showNextWorks:function(thisEle){
		var here = $(thisEle);
		var next = $(thisEle).next();
		
		if(!next.length){
			next = MR.worksList.eq(0);
			MR.current = 1;
		}else{
			MR.current += 1;
		}

		here.removeClass('here');
		here.fadeOut(0,function(){
														
			next.fadeIn(MR.fadeDuration);
			
			MR.copyrightEle.text(next.find('img').attr('alt'));				
			MR.currentEle.text(MR.current);
			
			MR.fn.setFooter();
			
		});
		
		next.addClass('here');
		
	}
}

// define custom functions (as MR.fn's methods)

MR.fn.works = {
}

MR.mod = {}

// define custom modules

MR.common = MR.mod.common = function(){
	MR.fn.setTopButton();
	MR.fn.setFooter();
}

MR.top = MR.mod.top = function(){
	MR.fn.setTopEntry();
}

MR.info = MR.mod.info = function(){
	MR.fn.setInfoEntries();
}

MR.works = MR.mod.works = function(){
	MR.fn.setWorks();
}

// propaties

MR.customPropaty = {}

// main routine

$(function(){
	MR.init();	// initialize
	
	if(MR.devMode){MR.testNav();}	// development mode
	
	MR.common();

	if(MR.hasExistenceOf('#contents.top')){
		MR.top();
	}
				
	if(MR.hasExistenceOf('#contents.info')){
		MR.info();
	}
			
	if(MR.hasExistenceOf('#contents.works')){
		MR.works();
	}
});

