/*
 * project.js
 * URL
 * 
 * Copyright (c) 2009 IMG SRC Inc.
 *
 */

var Project = function(){}

Project.prototype = {
	init: function(){
		this.loadScript(),
		this.addRollover(),
		this.addTargetBlank(),
		this.addScroll(),
		this.addBlur()
	},

	checkOS: {
		win: navigator.userAgent.indexOf('Win',0) != -1//,
		//mac: navigator.userAgent.indexOf('Mac',0) != -1
	},
	
	checkBrowser: {
		//opera: navigator.userAgent.indexOf('Opera') > 0,
		chrome: navigator.userAgent.indexOf('Chrome') > 0,
		//firefox: navigator.userAgent.indexOf('Firefox') > 0,
		//safari: navigator.userAgent.indexOf('Safari') > 0,
    firefox35: navigator.userAgent.indexOf('Firefox/3.5') > 0,
		ie: navigator.userAgent.indexOf('MSIE') > 0,
		ie6: navigator.userAgent.indexOf('MSIE 6') > 0,
		ie7: navigator.userAgent.indexOf('MSIE 7') > 0
	},
	
	loadScript: function(){
		// js directory
		var path = '/js/';
		// js files
		var scripts = [
			'jquery.easing.min.js',
			'jquery.fancybox-1.2.6.js'//,
			//'swfobject.js'
		];
		// for IE6
		if(this.checkBrowser.ie6){
			scripts.push('jquery.pngFix.js');
		}

		for(var i = 0; i < scripts.length; i++){
			var element = document.createElement('script');
			element.src = [path, scripts[i]].join('');
			element.type = 'text/javascript';
			document.body.appendChild(element);
		}
	},
	
	addRollover: function(){
		// add 'class="rollover"' in image tags
		var images = $('img.rollover, input.rollover');

		if(!images.length) return;

		var offSuffix = "_off.";	// e.g. button-off.gif
		var onSuffix = "_on.";	// e.g. button-on.gif

		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));
				}
			}
		}	
	},

	addTargetBlank: function(){
		$('a[rel="external"][href]').attr('target', '_blank');	
	},

	addScroll: function(){
		if(!$('a[href^="#"]')) return;

		var durationTime = 1000;
		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;
		});
	},

	addBlur: function(){
		if(this.checkBrowser.ie){
			$('a').focus(function(){this.blur();});
		}
	},
	
	openPopup: function(linkObj, url, width, height, name){
		if(!linkObj || !url){
			alert('openPopup: params 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";
		
		$(linkObj).click(function(){
			window.open(url, name, params);
			return false;
		});
	},
	
	closePopup: function(linkObj){
		if(!linkObj){
			alert('closePopup: params not found');
			return;
		}
		
		var button = $(linkObj);
		if(!button.length) return;
		
		button.click(function(){
			window.close();
		});		
	}

}

var KOTORI = new Project();

/*
	KOTORI.searchArea = function(){
	var area = $('#search-area');
	var openButton = $('#search-open a');
	var closeButton = $('#search-close');
	openButton.click(function(){
		area.fadeIn('fast');
		return false;
	});
	closeButton.click(function(){
		area.fadeOut('fast');
	});
	$(document).keypress(function(e){
		if(e.keyCode == 27){
			area.fadeOut('fast');		
		}
	});
}
*/

// development tool
KOTORI.testNav = function(){
	if(this.checkBrowser.ie6) return;
	$('#container').append('<div id="TESTNAV" style="position:fixed;bottom:0px;right:-155px;font-size:9px;background:black;opacity:0.8;width:150px;padding:10px 10px 10px 20px;"></div>');
	var nav = $('#TESTNAV');
	nav.load('/_testnavi.html');
	nav.mouseover(function(){
		$(this).css('right','0px');			 
	});
	nav.mouseleave(function(){
		$(this).css('right','-155px');			 
	});
}

// this method is called by 'jquery.fancybox-1.2.5.pack.js'
KOTORI.addLightbox = function(){
	var element = $('.lightbox');
	if(!element.length) return;
	element.fancybox({
		'padding': 0,
		'overlayColor': '#fff',
		'overlayOpacity': 0.7,
		'zoomOpacity': true,
		'overlayShow': true,
		'zoomSpeedIn': 250,
		'zoomSpeedOut': 250
	});
}

KOTORI.slideArea = function(){
	var area = $('#destination-area');
	if(!area.length) return;

	var self = $('#address_delivery_other_address_flag_0');
	var other = $('#address_delivery_other_address_flag_1');
	var area = $('#destination-area');

	area.hide();
	
	self.click(function(){
		area.slideUp('fast');
	});
	other.click(function(){
		area.slideDown('fast');
	});
}

KOTORI.changeSeparator = function(){
	var images = $('.color-separator img');

	if(!images.length) return;
	
	var colors = 15; // number of color chips
	var table = [];
	var src;		
	var current;
	
	for(var i = 0; i < (colors - 1); i++){
		table.push(i + 2);
	}
	
	for(var j = 0; j < images.length; j++){
		current = Math.floor(Math.random() * (table.length - 1));
		
		src = $(images[j]).attr('src');
		src = src.replace(/colorchip[\d0-9]+/, 'colorchip' + table[current]);
		$(images[j]).attr('src', src);
		
		table.splice(current, 1);
	}
}

KOTORI.scrollTop = function(){
	$('html, body').animate({ scrollTop: 0 }, 1000, 'easeInOutCirc');
}

KOTORI.scrollToPosition = function(px){
	$('html, body').animate({ scrollTop: px }, 1000, 'easeInOutCirc');
}

KOTORI.fastScrollTop = function(){    
  $('html, body').animate({ scrollTop: 0 }, 250, 'swing');    
}

KOTORI.getScrollY = function(){
	var y = 0;
	y = document.body.scrollTop || document.documentElement.scrollTop;
	return y;
}

KOTORI.openFlashContent = function(height){
	area = $('#flashContent');

	if(!area.length) return;
	if(!height) height = 2100;
	
	contentHeight = height + 'px';
	
	area.animate({
		height: contentHeight
	}, 'slow');					 
}

KOTORI.getViewportRect = function(){
	var windowWidth, windowHeight, tmpWidth, tmpHeight;
	
	if(KOTORI.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(970 > tmpWidth){
			windowHeight = tmpHeight - 16;
		}
	}

	var scrl = KOTORI.getScroll();

	obj = {
		x:scrl.x,
		y:scrl.y,
 		width:windowWidth,
 		height:windowHeight
	}
	
	return obj
}

KOTORI.getScroll = function(){
	return {
		x: document.body.scrollLeft || document.documentElement.scrollLeft,
		y: document.body.scrollTop  || document.documentElement.scrollTop
	}
}

KOTORI.getSWF = function(movieName){
	if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName]
    }
    else {
        return document[movieName]
    }
}

KOTORI.scrollHandler = function(){
	KOTORI.getSWF(swfName).setScroll(KOTORI.getScroll());
}

KOTORI.resizeHandler = function(){
	KOTORI.getSWF(swfName).setViewportRect(KOTORI.getViewportRect());
}

KOTORI.addCustomPageEvent = function(){
	if(!$('#customize-contents').length) return;
	
	var tmr;
  if(KOTORI.checkBrowser.firefox35){    
          tmr = setTimeout("KOTORI.addWindowEvent()", 1600);        
  }else{    
          tmr = setTimeout("KOTORI.addWindowEvent()", 200);       
  }
}

/*KOTORI.addTopPageEvent = function(){
	if(!$('#top-contents').length) return;
	
	var tmr;
  if(KOTORI.checkBrowser.firefox35){    
          tmr = setTimeout("KOTORI.addWindowEvent()", 1600);        
  }else{    
          tmr = setTimeout("KOTORI.addWindowEvent()", 200);       
  }
}*/

KOTORI.addWindowEvent = function(){
	$(window).scroll(function(){
		KOTORI.scrollHandler();
	});
	$(window).resize(function(){
		KOTORI.resizeHandler();
	});	
}

KOTORI.addHomeRollover = function(){
	var image = $('#home-button img');

	if(!image.length) return;

	var logo = $('#header h1 img');

	var offSuffix = "_off.";	// e.g. button-off.gif
	var onSuffix = "_on.";	// e.g. button-on.gif

	logo.mouseover(function(){
		image.attr("src", image.attr("src").replace(offSuffix, onSuffix));
	});
	logo.mouseleave(function(){
		image.attr("src", image.attr("src").replace(onSuffix, offSuffix));
	});
}
/*KOTORI.hideHTML = function(){   
  if(!$('#top-contents').length) return;    
  //$('#header dl').hide();   
  //$('#footer').css('opacity', 0);   
  var tmr2 = setTimeout(" KOTORI.fastScrollTop();", 300);   
}   
    
KOTORI.showHTML = function(){   
  $('#header dl').fadeIn('slow');   
  $('#footer').animate({opacity: 1.0});   
  $('#footer *').animate({opacity: 1.0});   
}*/

KOTORI.addTabEvent = function(){
	var tabs = $('#tabs img');
	tabs.click(function(){
		KOTORI.changeArea(this.id);
	});
}

KOTORI.changeArea = function(id){
	var detail = $('#detail-tab');
	var spec = $('#spec-tab');
	var detailSrc;
	var specSrc;
	

	if(id == 'detail-tab'){
		$('#spec').hide();
		$('#detail').show();

		detailSrc = detail.attr('src').replace('_on', '_selected');
		specSrc = spec.attr('src').replace('_selected', '_off');

		detail.attr('src', detailSrc);
		spec.attr('src', specSrc);
		
	}else{
		$('#detail').hide();		
		$('#spec').show();		

		detailSrc = detail.attr('src').replace('_selected', '_off');
		specSrc = spec.attr('src').replace('_on', '_selected');

		detail.attr('src', detailSrc);
		spec.attr('src', specSrc);
	}
}
KOTORI.addThumbEvent = function(){
	var thumbs = $('#thumb-list li');
	thumbs.click(function(){
		KOTORI.changeImage(this.id);
		KOTORI.selectThumb(this.id);
	});
	thumbs.mouseover(function(){
		var outline = $('#' + this.id + ' span');
		
		if(outline.attr('class') == 'selected') return;
			
		outline.attr('class', 'hover');
	});
	thumbs.mouseout(function(){
		var outline = $('#' + this.id + ' span');

		if(outline.attr('class') == 'selected') return;

		outline.attr('class', 'outline');
	});
}
KOTORI.changeImage = function(id){
	
	var imagePath = '/images/set/';
	var imagePrefix = 'sample_spec';
	
	id = id.replace('thumb', '');

	var src = imagePath + imagePrefix + id + '.jpg';
	
	$('#spec-image').attr('src', src);
}
KOTORI.selectThumb = function(id){
	var outlines = $('#thumb-list span');
	var selected = $('#' + id + ' span');
	
	outlines.attr('class', 'outline');
	selected.attr('class', 'selected');
}
KOTORI.addOutline = function(){
	var thumbs = $('#thumb-list li[id!="thumb1"]');
	var outline = '<span class="outline"></span>';
	var selected = '<span class="selected"></span>';
	
	thumbs.append(outline);
	$('#thumb1').append(selected);
}
KOTORI.initTab = function(){
	var detail = $('#detail-tab');
	var detailSrc = detail.attr('src').replace('_off', '_selected');
	detail.attr('src', detailSrc);

	KOTORI.addTabEvent();
}
KOTORI.initSpec = function(){
	KOTORI.addOutline();
	KOTORI.addThumbEvent();
}
KOTORI.initPreview = function(){
	if(!$('div#preview').length)return;
	KOTORI.initTab();
	KOTORI.initSpec();
}

KOTORI.addPngFix = function(){
	if(!$('#top-contents').length) return;
	$('p.object').pngFix();
	$('dl.best,dl.worst').pngFix();
	$('#left-column').pngFix();
}

KOTORI.templateListStyle = function(){
	if(!$('#templates').length) return;
	$('.name').css({
		fontSize:'82%',
		letterSpacing: '0.03em'
	});
}
KOTORI.templateClickable = function(){
	if(!$('#templates').length) return;

	$('.template').mouseover(function(){
		$(this).addClass('over');
	});
	$('.template').mouseleave(function(){
		$(this).removeClass('over');
	});
	$('.template').click(function(){
		window.location.replace(this.getElementsByTagName('a')[0].href);
	});
}

KOTORI.stackVoice = function(){
	if(!$('#users').length) return;

	var voices = $('#voices');
	var voice = $('.voice');
	
	var usersHeight;

	var leftHeight = 0;
	var rightHeight = 0;
	
	var leftOffset = 0;
	var rightOffset = 20;
	
	var voiceMargin = 20;
	
	rightHeight = rightHeight + rightOffset;
	
	voices.append('<div id="voice-left"><span class="dummy">&nbsp;</span></div><div id="voice-right"><span class="dummy">&nbsp;</span></div>');

	voice.each(function(){
		var voiceEle = $(this);
		var voiceHeight = voiceEle.outerHeight();
		
		if(leftHeight <= rightHeight){
			$('#voice-left').append(voiceEle);
			voiceEle.addClass('left');
			
			leftHeight = leftHeight + voiceHeight + voiceMargin;
		}else{
			$('#voice-right').append(voiceEle);
			voiceEle.addClass('right');

			rightHeight = rightHeight + voiceHeight + voiceMargin;			
		}
	});
	
	if(KOTORI.checkOS.win){
		$('p.date span').css('letterSpacing','0.06em');
	}
	if(KOTORI.checkBrowser.ie6){
		$('.items img').mouseover(function(){
				$(this).css('border','1px solid #ccc');
		});
		$('.items img').mouseleave(function(){
				$(this).css('border','1px solid #fff');
		});
		
	}

}

KOTORI.itemRollover = function(){
	if(!$('#main')) return;
	var itemImages = $('.items dt');
	var itemLinks = $('.items .link');
	
	itemImages.mouseover(function(){
		$(this).find('.selected').show();
		$(this).siblings('.link').addClass('selected');
	});
	itemImages.mouseleave(function(){
		$(this).find('.selected').hide();
		$(this).siblings('.link').removeClass('selected');
	});
	
	itemLinks.mouseover(function(){
		$(this).siblings('dt').find('.selected').show();
	});
	itemLinks.mouseleave(function(){
		$(this).siblings('dt').find('.selected').hide();
	});
}
KOTORI.itemRolloverTop = function(){
	if(!$('#top-contents').length) return;
	$('.item').mouseover(function(){
		$(this).find('.outline').show();															
	});
	$('.item').mouseleave(function(){
		$(this).find('.outline').hide();															
	});
	$('div.list .image').mouseover(function(){
		$(this).siblings('.title').addClass('over');
	});
	$('div.list .image').mouseleave(function(){
		$(this).siblings('.title').removeClass('over');
	});	
}
KOTORI.twitterRollover = function(){
	if(!$('#top-contents').length) return;
	$('#twitter .follow a').mouseover(function(){
		var bg = $(this).siblings('.bg');
		var overSrc = bg.attr('src');
		overSrc = overSrc.replace('_off.', '_on.');
		bg.attr('src', overSrc);		
	});
	$('#twitter .follow a').mouseleave(function(){
		var bg = $(this).siblings('.bg');
		var overSrc = bg.attr('src');
		overSrc = overSrc.replace('_on.', '_off.');
		bg.attr('src', overSrc);		
	});
	$('#twitter .read a').mouseover(function(){
		var bg = $(this).siblings('.bg');
		var overSrc = bg.attr('src');
		var follow = $('dd.follow .bg');
		var followSrc = follow.attr('src');

		overSrc = overSrc.replace('_off.', '_on.');
		followSrc = followSrc.replace('_off.', '_over.');
		
		bg.attr('src', overSrc);
		follow.attr('src', followSrc);
	});		
	$('#twitter .read a').mouseleave(function(){
		var bg = $(this).siblings('.bg');
		var overSrc = bg.attr('src');
		var follow = $('dd.follow .bg');
		var followSrc = follow.attr('src');

		overSrc = overSrc.replace('_on.', '_off.');
		followSrc = followSrc.replace('_over.', '_off.');

		bg.attr('src', overSrc);
		follow.attr('src', followSrc);
	});		
}

KOTORI.showCartQuantity = function(){
	if(!$('#cart-quantity-area')) return;
	KOTORI.loadJSON('/api/cartInfo', 'cart-quantity-area');
}
KOTORI.loadJSON = function(url, insertID){
	if(!url || !insertID) return;
	
	var date = new Date();
	var param = date.getTime();
	
	$.getJSON(url + '?param=' + param, function(data){
		KOTORI.displayData(data, insertID);																						
	});
}
KOTORI.displayData = function(data, insertID){

	var id = '#' + insertID;
	var line = '';
	line += '<span id="cart-quantity">';
	line += data.items_count;
	line += '<img src="/images/shared/icon_quantity.png" width="10" height="13" alt="ƒR" /></span>';
	
	$(id).html(line);
}

KOTORI.headerDropMenu = function(){
	var menu = $('#template-menu');
	if(!menu.length) return;
	
	var title = $('#template-menu dt');
	var buttons = $('#template-menu dd');

	var image = title.find('img')
	var src = image.attr('src');

	title.mouseover(function(){
		src = src.replace('_off.', '_on.');

		image.attr('src', src);
		menu.addClass('open');
		buttons.show();
	});
	menu.mouseleave(function(){
		src = src.replace('_on.', '_off.');

		image.attr('src', src);
		buttons.hide();
		menu.removeClass('open');
	});
}
KOTORI.rankingRollover = function(){
	if(!$('div#top10').length) return;
	
	var image = $('dd.image a');
	//var outline = '<img src="/images/ranking/outline.png" alt="" width="140" height="120" class="outline" />';
	
	image.mouseover(function(){
		$(this).find('.outline').show();													
	});
	image.mouseleave(function(){
		$(this).find('.outline').hide();													
	});
}
KOTORI.votingRollover = function(){
	if(!$('#voting').length) return;
	
	var image = $('dt.item a');
	//var outline = '<img src="/images/ranking/outline.png" alt="" width="140" height="120" class="outline" />';
	
	image.mouseover(function(){
		$(this).find('.outline').show();													
	});
	image.mouseleave(function(){
		$(this).find('.outline').hide();													
	});
}
KOTORI.lastEntry = function(){
	if(!$('#sidebar').length) return;
	if($('#paging .rollover').length) return;
	
	$('div.entry:last').addClass('last');
	$('#entries').addClass('none');
	//$('#paging').hide();
}
KOTORI.chromeHeader = function(){
	if(!KOTORI.checkBrowser.chrome) return;
	
	$('#press-menu').css('left', '102px');
	$('#home-button').css('top', '-7px');
	//$('#template-menu').css('left', '439px');
	//$('#guide-menu').css('left', '-20px');
}

KOTORI.voteDesign = function(eleId, voteType){

	var itemId = eleId.replace(/item.-/, "");
	
	if(KOTORI.isVoted(itemId)){
		return;
	}
	
	// API URL
	var url = '/api/voteDesign';
	
	if(!voteType){
		// love
		$.get(url, {goodsId: itemId, voteType: 0});
	}else{
		// hate
		$.get(url, {goodsId: itemId, voteType: 1});
	}

	KOTORI.setVoted(itemId);
	KOTORI.voteCount(itemId, voteType);
	KOTORI.setCookie(itemId);
}

KOTORI.voteCount = function(itemId, voteType){
	if(!$('#top-contents').length) return;
	
	for(var i = 1; i < 7; i++){
		if(!voteType){
			var countEle = $('#item' + i + "-" + itemId + ' .love');	
		}else{
			var countEle = $('#item' + i + "-" + itemId + ' .hate');	
		}
		
		var count = countEle.text();
		
		countEle.hide();
		countEle.text(parseInt(count) + 1);
		countEle.fadeIn(1000);
	}
}

KOTORI.addVoteEvent = function(){
	if(!$('#top-contents').length) return;
	
	KOTORI.voteInit();
	
	var love = $('#voting dd[class*="love"]');
	var hate = $('#voting dd[class*="hate"]');
	
	love.click(function(){
		KOTORI.voteDesign($(this).parent().attr('id'), 0);
	});
	hate.click(function(){
		KOTORI.voteDesign($(this).parent().attr('id'), 1);															
	});

	if(KOTORI.checkBrowser.ie6){
		love.mouseover(function(){
			if($(this).attr('class').indexOf('Voted') < 0){
				$(this).addClass('loveOver');
			}
		});
		hate.mouseover(function(){
			if($(this).attr('class').indexOf('Voted') < 0){
				$(this).addClass('hateOver');
			}
		});
	
		love.mouseleave(function(){
			if($(this).attr('class').indexOf('Voted') < 0){
				$(this).removeClass('loveOver');
			}
		});
		hate.mouseleave(function(){
			if($(this).attr('class').indexOf('Voted') < 0){
				$(this).removeClass('hateOver');
			}
		});

	}else{
		love.mouseover(function(){
			if($(this).attr('class').indexOf('voted') < 0){
				$(this).addClass('over');
			}
		});
		hate.mouseover(function(){
			if($(this).attr('class').indexOf('voted') < 0){
				$(this).addClass('over');
			}
		});
	
		love.mouseleave(function(){
			if($(this).attr('class').indexOf('voted') < 0){
				$(this).removeClass('over');
			}
		});
		hate.mouseleave(function(){
			if($(this).attr('class').indexOf('voted') < 0){
				$(this).removeClass('over');
			}
		});
	}
}

KOTORI.voteInit = function(){
	var items = document.getElementById('voting').getElementsByTagName('dl');

	for(var i = 0; i < items.length; i++){
		
		var itemId = items[i].getAttribute('id').replace(/item.-/, "");
		
		if(KOTORI.isVoted(itemId)){
			KOTORI.setVoted(itemId);
		}
	}
}

KOTORI.setVoted = function(itemId){
	for(var i = 1; i < 7; i++){
		var votedItem = $('#item' + i + "-" + itemId);
		var check = votedItem.find('.check');
		var love = votedItem.find('.love');
		var hate = votedItem.find('.hate');
			
		if(KOTORI.checkBrowser.ie6){
			love.addClass('loveVoted');
			hate.addClass('hateVoted');
		
			love.removeClass('loveOver');
			hate.removeClass('hateOver');
		}else{
			love.addClass('voted');
			hate.addClass('voted');
	
			love.removeClass('over');
			hate.removeClass('over');
		}
			
		check.show();
	
		love.mouseover(function(){
			$(this).siblings('.check').find('.balloon').show();												
		});
		love.mouseleave(function(){
			$(this).siblings('.check').find('.balloon').hide();												
		});
	
		hate.mouseover(function(){
			$(this).siblings('.check').find('.balloon').show();												
		});
		hate.mouseleave(function(){
			$(this).siblings('.check').find('.balloon').hide();												
		});
	
		check.mouseover(function(){
			$(this).find('.balloon').show();												 
		});
		check.mouseleave(function(){
			$(this).find('.balloon').hide();												 
		});
	}
}

KOTORI.setCookie = function(itemId){
	if(!navigator.cookieEnabled) return;
	
	var date = '';
	var expire = 1; // days
	var value = KOTORI.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(value){
		value += "/" + itemId;	
	}else{
		value = itemId;
	}
	
	document.cookie = 'voted=' + value + ';expires=' + date + ';path=/';
	
	return true;
}

KOTORI.getCookie = function(){
	if(!navigator.cookieEnabled) return;

	var cookie = document.cookie;
	var name = "voted="
	var matchStr = new RegExp(name + "[^;]*");
	var value;
	
	if(cookie.indexOf('voted') != -1){
		value = cookie.match(matchStr) + "";
		value = value.replace(name, '');
		return value;
	}
}

KOTORI.isVoted = function(goodsId){
	if(!navigator.cookieEnabled) return;

	var cookie = document.cookie;
	
	if(cookie.indexOf(goodsId) != -1){
		return true;
	}else{
		return false;
	}
}

KOTORI.toggleDate = function(){
	var later = $('input.sendLater');
	
	if(!later.length) return;
	
	var input = $('td.date select.dropdown');
	
	input.change(function(){
		later.attr('checked','checked');											
	});
}

KOTORI.checkGiftMode = function(){
	if(!$('.gift-mode').length) return;
	$.ajax({
		 type: "POST",
		 url: "/api/checkGiftMode",
		 error: function(res){
       if(res.status == 0){
         return;
       } else {
         alert('ERROR : Fail to access the API.');
       }
		 },
		 success: function(res){
			 var xml = $(KOTORI.parseFromString(res));
			 
			 if(xml.attr('status') == 'success'){
			 
				 if(xml.find('status').text() == 1){
						$('#header .gift-mode').show();
						$('#top-header .gift-mode').show();
						setInterval(KOTORI.dummy,30 * 60 * 1000);
				 }else{
		 			$('#header .normal-mode').show();
					$('#left-column .giftcode').show();
				 }
			 }else{
			 	alert('API ERROR : errorCode=' + xml.attr('errorCode'));
			 }
		 }
	 });
}

KOTORI.dummy = function(){
	$.get("/api/dummy");
}

KOTORI.releaseGiftMode = function(){
	$.ajax({
		 type: "POST",
		 url: "/api/releaseGiftMode",
		 error: function(){
			 alert('ERROR : Fail to access the API.');
		 },
		 success: function(res){
			 var xml = $(KOTORI.parseFromString(res));
			 
			 if(xml.attr('status') == 'success'){
				 	
				 	if(location.href.indexOf('/giftcode/use/') > 0){
				 		location.replace('/guide/giftcode');
					}else if(location.href.indexOf('/order_ssl/confirm') > 0){
				 		location.replace('/order_ssl/guest2#payment');
					}else{
			 			location.reload(true);
					}
			 }else{
					alert('ERROR : Fail to release GIFT CODE MODE.'); 
			 }
		 }
	 });
}

KOTORI.toggleGiftArea = function(){
	var area = $('#gift-area');
	if(!area.length) return;
	$('#header .gift-mode').mouseover(function(){
		area.show();															 
	});
	$('#top-header .gift-mode').mouseover(function(){
		area.show();															 
	});
	area.mouseleave(function(){
		area.hide();															 
	});
	$('#top-header').mouseleave(function(){
		area.hide();															 
	});
}


KOTORI.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;
}


KOTORI.slideshow = function(){
	
	if(!$('#magazine').length) return;
	
	if(KOTORI.checkBrowser.ie6){		
		DD_belatedPNG.fix('.outline');
	}

	KOTORI.fadeDuration = 1000;
	KOTORI.fadeFastDuration = 500;
	KOTORI.slideshowWidth = 930;
	
	var outline = $('.outline');
	
	outline.mouseover(function(){
		$(this).parent().parent().addClass('over');
	});
	outline.mouseleave(function(){
		$(this).parent().parent().removeClass('over');
	});
	
	outline.click(function(){
		var vol = $(this).attr('href').match(/[0-9]{2}/);
		KOTORI.showSlideshow(vol)
		return false;
	});

	if(location.href.indexOf('vol=') != -1){
		
		var vol = location.href.split('vol=');
		vol = vol[1];
		
		if(vol.length != 2) return;
				
		var slideTimer = setTimeout('KOTORI.showSlideshow(' + vol + ')', 1000);

	}
}

KOTORI.showSlideshow = function(vol){
	
	var limit = 3;
	
	if(vol == 0 || vol > limit) return;

	var slideshowOverlay = $('#slideshow-overlay');

	if(typeof vol == 'number' && vol < 10){
		vol = '0' + vol;
	}		
		
	KOTORI.loadSlideshow(vol);

	KOTORI.hideScrollbar();
	
	slideshowOverlay.fadeIn(KOTORI.fadeDuration, KOTORI.positSlideshow());
}

KOTORI.loadSlideshow = function(vol){
		
	var loadPath = '/magazine/' + vol + '.html';
	var loadId = '#slideshow-source';

	$('#slideshow-content').load(loadPath + ' ' + loadId, function(){
		var slideshowFrame = $('#slideshow-frame');
		var slideshowPages = $('.page');
	
		var countTotal = $('#count-total');
		var countHere = $('#count-here');
	
		KOTORI.pageTotal = slideshowPages.length;
		KOTORI.pageHere = 1;
		
		$('#slideshow-title span').addClass('vol' + vol);
		$('#slideshow-content').addClass('vol' + vol);
			
		KOTORI.showCount(countHere, countTotal);
		
		$('#slideshow-prev').hide();
		
		KOTORI.showButtons(countHere, countTotal);
	
		KOTORI.setSlideEvent(countHere, countTotal);
	});

	
}

KOTORI.showCount = function(countHere, countTotal){

	countTotal.text(KOTORI.pageTotal);
	countHere.text(KOTORI.pageHere);

}

KOTORI.showButtons = function(){
		
	var slideshowPrev = $('#slideshow-prev');
	var slideshowNext = $('#slideshow-next');

	// first page
	if(KOTORI.pageHere <= 1){
		if(KOTORI.checkBrowser.ie){
			slideshowPrev.hide();		
			slideshowNext.show();
		}else{
			slideshowPrev.fadeOut(KOTORI.fadeFastDuration);		
			slideshowNext.fadeIn(KOTORI.fadeFastDuration);
		}
		
	// last page
	}else if(KOTORI.pageHere >= KOTORI.pageTotal){
		if(KOTORI.checkBrowser.ie){
			slideshowPrev.show();		
			slideshowNext.hide();
		}else{
			slideshowPrev.fadeIn(KOTORI.fadeFastDuration);		
			slideshowNext.fadeOut(KOTORI.fadeFastDuration);
		}

	// others
	}else{
		if(KOTORI.checkBrowser.ie){
			slideshowPrev.show();		
			slideshowNext.show();
		}else{
			slideshowPrev.fadeIn(KOTORI.fadeFastDuration);		
			slideshowNext.fadeIn(KOTORI.fadeFastDuration);		
		}
	}
	
}

KOTORI.setSlideEvent = function(countHere, countTotal){

	var slideshowPrev = $('#slideshow-prev');
	var slideshowNext = $('#slideshow-next');
	var kotoriAnchor = $('.kotori a');

	var slideshowContent = $('#slideshow-content');
		
	slideshowPrev.click(function(){
		$(this).unbind();
		slideshowContent.animate({
			left: - (KOTORI.pageHere - 2) * KOTORI.slideshowWidth
		},
		KOTORI.fadeDuration, 'easeInOutCirc', function(){
			KOTORI.setSlideEvent(countHere, countTotal);
		});
		
		KOTORI.pageHere--;
		
		KOTORI.showCount(countHere, countTotal);

		KOTORI.showButtons(countHere, countTotal);
		
		return false;
	});
	slideshowNext.click(function(){
		$(this).unbind();
		slideshowContent.animate({
			left: KOTORI.pageHere * - KOTORI.slideshowWidth
		},
		KOTORI.fadeDuration, 'easeInOutCirc', function(){
			KOTORI.setSlideEvent(countHere, countTotal);
		});
		
		KOTORI.pageHere++;
		
		KOTORI.showCount(countHere, countTotal);

		KOTORI.showButtons(countHere, countTotal);
		
		return false;
	});
	kotoriAnchor.mouseover(function(){
		$(this).parent().parent().addClass('over');
	});
	kotoriAnchor.mouseleave(function(){
		$(this).parent().parent().removeClass('over');
	});
	
}

KOTORI.positSlideshow = function(){
	
	var container = $('#container');
	var slideshowContainer = $('#slideshow-container');
	
	KOTORI.containerWidth = container.outerWidth();
	KOTORI.containerHeight = container.outerHeight();
		
	var slideshowContainerWidth = 972;
	var slideshowContainerHeight = 570;

	if(KOTORI.checkBrowser.ie6){

		slideshowForIE6();
		
		DD_belatedPNG.fix('.pngfix');
		
	}else{
		$(window).resize(function(){

			getSlideshowPosition();
			
			if(KOTORI.slideshowTop <= 0){
				slideshowContainer.css('top', slideshowContainerHeight / 2);
			}else{
				slideshowContainer.css('top', '50%');
			}
			
			if(KOTORI.slideshowLeft <= 0){
				slideshowContainer.css('left', slideshowContainerWidth / 2);
			}else{
				slideshowContainer.css('left', '50%');
			}
			
		});
	}
	
	KOTORI.setCloseEvent();
	
	function slideshowForIE6(){
		
		var slideshowOverlay = $('#slideshow-overlay');
		var viewport = KOTORI.getViewportRect();
		
		getSlideshowPosition();
		
		slideshowOverlay.css('height', KOTORI.containerHeight);
		slideshowContainer.css('top', KOTORI.slideshowTop + KOTORI.getViewportRect().y);
				
		$(window).scroll(function(){
			var currentTop = KOTORI.slideshowTop + KOTORI.getViewportRect().y;
			
			slideshowContainer.css('top', currentTop);
						
		});
		$(window).resize(function(){
															
			getSlideshowPosition();
			
			slideshowContainer.css('top', KOTORI.slideshowTop + KOTORI.getViewportRect().y);
	
			if(KOTORI.slideshowLeft <= 0){
				slideshowContainer.css('left', slideshowContainerWidth / 2);
			}else{
				slideshowContainer.css('left', '50%');
			}
		});
	}
	
	function getSlideshowPosition(){
		
		KOTORI.slideshowTop = parseInt((KOTORI.getViewportRect().height - slideshowContainerHeight) / 2);
		KOTORI.slideshowLeft = parseInt((KOTORI.getViewportRect().width - slideshowContainerWidth) / 2);
				
		if(KOTORI.slideshowTop < 0){
			KOTORI.slideshowTop = 0;
		}
		if(KOTORI.slideshowLeft < 0){
			KOTORI.slideshowLeft = 0;
		}
	}
}

KOTORI.setCloseEvent = function(){
	
	// close button
	$('#slideshow-close a').click(function(){
																				 
		KOTORI.resetSlideEvent();

		return false;
	});
}

KOTORI.resetSlideEvent = function(){

	if(KOTORI.checkBrowser.ie6 || KOTORI.checkBrowser.ie7){
		$('#slideshow-prev').unbind().hide();
		$('#slideshow-next').unbind().hide();
	}
	
	$('#slideshow-overlay').fadeOut(KOTORI.fadeDuration, function(){

		$('#slideshow-prev').unbind().hide();
		$('#slideshow-next').unbind().hide();
		
		$('#slideshow-title span').removeClass();
		$('#slideshow-content').removeClass();

		KOTORI.showScrollbar();

		$('#slideshow-content').css('left',0);

		$('#slideshow-content').empty();

	});
}

KOTORI.hideScrollbar = function(){
	if(KOTORI.checkBrowser.ie6 || KOTORI.checkBrowser.ie7){
		document.body.setAttribute('scroll','no');			
	}else{
		$(document.body).addClass('noscroll');
	}
}
KOTORI.showScrollbar = function(){
	if(KOTORI.checkBrowser.ie6 || KOTORI.checkBrowser.ie7){
		document.body.setAttribute('scroll','yes');			
	}else{
		$(document.body).removeClass('noscroll');
	}
}




$(function(){
	KOTORI.init();
	//KOTORI.searchArea();
	//KOTORI.openPopup($('#open-guide'), '/guide/index.html')
  //KOTORI.hideHTML();
	KOTORI.changeSeparator();
	KOTORI.addHomeRollover();
	KOTORI.headerDropMenu();
	KOTORI.showCartQuantity();
	KOTORI.chromeHeader();
	KOTORI.slideArea();
	KOTORI.closePopup($('#close-guide'));
	KOTORI.initPreview();
	if(KOTORI.checkOS.win && !(KOTORI.checkBrowser.ie)) KOTORI.templateListStyle();
	KOTORI.lastEntry();
	KOTORI.templateClickable();
	KOTORI.stackVoice();
	KOTORI.addVoteEvent();
	KOTORI.itemRollover();
	KOTORI.itemRolloverTop();
	KOTORI.twitterRollover();
	KOTORI.rankingRollover();
	KOTORI.votingRollover();
	KOTORI.toggleDate();
	KOTORI.checkGiftMode();
	KOTORI.toggleGiftArea();
	KOTORI.slideshow();
	//KOTORI.testNav();
});
