/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/

var imagePath = "/library/common/js/modalcart/images/";
var tb_pathToImage = imagePath + "loadingAnimation.gif";
var close_button = imagePath + "close-button.gif";
var TB_WIDTH = 730;
var TB_HEIGHT = 580;

var slide_window_tmpl = '<div id="slidewindow_layer_template"> <span id="slidewindow_status"></span><div id="slidewindow_in_layer"><div id="slide-window"><div id="in-item-image"><span class="slide_item_image"></span></div><div class="in-item-name"><span class="slide_item_name"></span></div><div class="in-item-num">数量　<span class="slide_item_count"></span></div><div class="in-item-value">単価　<span class="slide_item_price"></span>円</div></div><div id="in-item-mes" class="in-item-messege" style="display: block;">カートに追加されました</div></div></div>';

var error_window = '<div style="width:200px;height:70px;border:1px solid #CCC;background-color:#FFF;margin-left:auto;margin-right:auto;padding:5px;z-index:100;position:relative;" class="error-message"><div id="error_msg"></div><a href="javascript:void(0)" id="error_close" style="width:71px;height:27px;text-indent:-9999px;display:block;background:url('+close_button+') no-repeat;margin:0 auto;overflow:hidden;">閉じる</a></div>';
var inner_template = "/library/common/js/modalcart/template.html";
//var url_item = "sample_json.json";
//var url_item = "http://192.168.0.22/~mizo/cgi/api_test/open.cgi";
//var url_item = "timeout.php";//デバッグ用
//var url_cartin = "cart_insert.json";
//var url_cart = "cart.json";
var url_item = "/api/item.php";
var url_cartin = "/api/cart_insert.php";
//var item_code = '11107';
//var item_code = false;

//
var cart_data;
//
var timerID;

j$(function(){
	if(navigator.userAgent.indexOf("MSIE 5") != -1) return false;
	tb_init('a.modalcart, area.modalcart');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
	
	j$("#all").append(slide_window_tmpl);
	if(j$("#container").length){
		j$("#container").append(slide_window_tmpl);
	}
});

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
	j$(domChunk).click(function(){
	var href_path = this.href.split("/");
	item_code = href_path[href_path.length-1].substr(0,5);
	if(item_code.match(/[0-9]{5}/)){
	   tb_show(item_code);
	}
	this.blur();
	return false;
	});
}

function tb_show(item_code) {//function called when the user clicks on a thickbox link

	try {
		if(document.getElementById("TB_overlay") === null){
			j$("body").append("<div id='overlay'></div><div id='TB_window'></div><div id='error_window_wrap'></div>");
			pageSize = getPageSize();
			j$("#overlay").css({
				"width":pageSize[0],
				"height":pageSize[1]
			});
			
			j$("#overlay").click(tb_remove);
		}		
		j$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		j$('#TB_load').show();//show loader
	   
		//code to show html
		
		j$("#TB_window").load(inner_template,function(){
		    j$(".window-close").click(tb_remove);//閉じるボタン
			j$("#TB_window").click(function(e){if(j$(e.target).is("div#TB_window")) tb_remove();});//背景閉じる
			
			j$.ajax({
				url:url_item,
				success:showItemData,
				dataType:'json',
				data:'type=json&code='+item_code,
				error:function(XHR, status, errorThrown){
					if(status == "timeout"){
						errorMSG("通信に失敗しました<br />もう一度お試しください");
					}else if(status == "error"){
						errorMSG("ファイルがありません");
					}
				},
				timeout:1000,
				cache:false
			});
		});
		
	} catch(e) {
		//nothing here
	}
}
//フローティングウィンドウを出す
function showItemData(data,status){
	if(status == "success"){
		tb_setItemData(data);
		j$("#TB_load").remove();
	}else{
		tb_remove();
	}
}
//エラーメッセージ
function errorMSG(msg){
	j$("#TB_load").remove();
	var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
	j$("#error_window_wrap").append(error_window);
	j$("#error_close").click(function(){tb_remove();});
	j$(".error-message #error_msg").html(msg);
	j$("#error_window_wrap").css({
		"top":scrollTop+200,
		"display":"block"
	});
}

//ウィンドウ非表示
function tb_remove() {
	j$("#TB_closeWindowButton").unbind("click");
	j$("#TB_window").fadeOut("fast",function(){j$('#TB_window,#overlay').trigger("unload").unbind().remove();});
	j$("#error_window_wrap,.error-message").trigger("unload").unbind().remove();
	j$("#TB_load").remove();
	return false;
}

function tb_setItemData(data){
	if(data.result != undefined && data.result != "NG" && data.status != "非公開"){
		//analytics解析用
		page_location = location.href.replace("http://", "");
		pageTracker._trackPageview(page_location+'/'+data.code+'.mdc');
		//
		if(data.name) j$("#name").text(data.name);
		if(data.small_image) j$("#item-image").attr({src:'http://www.cuoca.com'+data.middle_image.url});
		if(data.code) j$("#code").text(data.code);
		if(data.price) j$("#price").text(data.price+"円");
		if(data.point) j$("#point").text(data.point);
		if(data.amount) j$("#amount").text(data.amount);
		if(data.preservation) j$("#preservation").text(data.preservation);
		if(data.material) j$("#material").html(data.material);
		if(data.made_in) j$("#made_in").text(data.made_in);
		if(data.feature) j$("#feature").html(data.feature);
		if(data.price) j$("#price-bottom").text(data.price);
		if(data.status == "販売終了"){
			j$("#itemCount").attr("disabled","disabled");
			j$("#cartIn-wrapper").html("こちらの商品は<br />販売終了いたしました。");
		}else if(data.status == "品切れ"){
			j$("#itemCount").attr("disabled","disabled");
			j$("#cartIn-wrapper").html("こちらの商品は<br />ただいま品切れ中です。");
		}else{
			j$("#cartIn").click(function(){
				cartIn(data.code,j$("#itemCount").val());
			});
		}
		if(data.code) j$("a#item-page-link").attr("href","http://www.cuoca.com/item/"+data.code+".html");
		//window show
		var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
		j$("#TB_window").css({
			"top":scrollTop+20,
			"display":"block"
		});
	}else{
		errorMSG("申し訳ございません。こちらの商品は取り扱いを終了しております。")
	}
}

//カートに追加する
function cartIn(sendItemCode,sendItemCount){
	j$.ajax({
		url:url_cartin,
		success:callbackCartIn,
		dataType:'json',
		data:'type=json&cd[0]='+sendItemCode+'&nu[0]='+sendItemCount+'&site[0]=1&cflg=cd',
		error:function(XHR, status, errorThrown){
			if(status == "timeout"){
				errorMSG("通信に失敗しました<br />もう一度お試しください");
			}else if(status == "error"){
				errorMSG("データがありません");
			}
		},
		timeout:1000,
		cache:false
	});
	//j$.getJSON(url_cartin,{type:'json','cd[0]':sendItemCode,'nu[0]':'1','site[0]':'1',cflg:'cd'},callbackCartIn);
}

function callbackCartIn(data,status){
    //UCRT = j$.cookie('UCRT');
	//CSD = j$.cookie('CSD');
	//if(UCRT && CSD){
		tb_remove();
		var ntime = (new Date()).getTime();
		
		j$.ajax({
			url:url_cart,
			success:callBackCartUpDate2,
			dataType:'json',
			data:'type=json&code=UCRT&key=CSD',
			error:function(XHR, status, errorThrown){
				if(status == "timeout"){
					errorMSG("通信に失敗しました<br />もう一度お試しください");
				}else if(status == "error"){
					errorMSG("データがありません");
				}
			},
			timeout:1000,
			cache:false
		});
		//j$.getJSON(url_cart,{type:'json',code:UCRT,key:CSD,ntime:ntime},callBackCartUpDate2);
	//}
	//else{
	//}
}

//
//smartCart表示
function callBackCartUpDate2(data,status){
	cart_data = data;
	//analytics解析用
	page_location = location.href.replace("http://", "");
	pageTracker._trackPageview(page_location+'/'+cart_data.last_adding[0].code+'.cart');
	//slide_window
	j$("#slidewindow_layer_template").css("display","block");
	if(cart_data.last_adding[0].image) j$(".slide_item_image").html('<img src="'+cart_data.last_adding[0].image+'" />');
	if(cart_data.last_adding[0].name) j$(".slide_item_name").html(cart_data.last_adding[0].name);
	if(cart_data.last_adding[0].count) j$(".slide_item_count").html(cart_data.last_adding[0].count);
	if(cart_data.last_adding[0].price) j$(".slide_item_price").html(cart_data.last_adding[0].price);
	
	j$("#slidewindow_layer_template").css("right",((pageSize[0]-878)/2)+"px");
	if (typeof document.body.style.maxHeight === "undefined"){//ie6対策
		var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
		j$("#slidewindow_layer_template").css("top",j$("#slidewindow_layer_template").height()*(-1)+scrollTop+"px");
		j$("#slidewindow_layer_template").animate({"top":scrollTop},300,"swing",callBackCartUpDate3);
	}else{
		j$("#slidewindow_layer_template").css("top",j$("#slidewindow_layer_template").height()*(-1)+"px");
		j$("#slidewindow_layer_template").animate({"top":"0px"},300,"swing",callBackCartUpDate3);
	}
}

function callBackCartUpDate3(){
	timerID = setTimeout("callBackCartUPDate4()", 1000);
}
function callBackCartUPDate4(){
	clearTimeout(timerID);
	data = cart_data;
	//j$.dump(data,true);
	if (typeof document.body.style.maxHeight === "undefined"){//ie6対策
		var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
		j$("#slidewindow_layer_template").animate({"top":j$("#slidewindow_layer_template").height()*(-1)+scrollTop+"px"},300,"swing",slideWindowHide);
	}else{
		j$("#slidewindow_layer_template").animate({"top":j$("#slidewindow_layer_template").height()*(-1)+"px"},300,"swing",slideWindowHide);
	}
	
	if(data.item_count  >= 1){
		j$("#smartcart-mes,#cart-item-etc").css("display","none");
		j$("#cart-items,#to-order-step-header,#to-order-step-footer").css("display","block");
		var last = data.last_adding[0];
		var innerContents = '';
		innerContents += '<div id="add-item-image"><a href="#"><img src="'+last.image+'" alt="'+last.name+'" width="100"></a></div>';
		innerContents += '<div class="cart-item clearfix">';
		innerContents += '<div class="cart-item-name"><a href="'+last.url+'">'+last.name+'</a></div>';
		innerContents += '<div class="cart-item-num">数量　'+last.count+'</div>';
		innerContents += '<div class="cart-item-value">単価　'+last.price+'円</div>';
		j$("#com_data_publish_last_in0").html(innerContents);
		//合計金額
		j$("#com_data_publish_count_all_sum").html(data.item_count);
		j$("#com_data_publish_price_all_sum").html(data.price_sum);
		j$("#com_data_publish_carry_sum").html(data.soryo_sum);
		j$("#com_data_publish_total_sum").html(data.total_sum);
		j$("#com_data_publish_soryo_alert_sum").html(data.soryo_alert);
	}
	if(data.item_count > 1){
		j$("#cart-item-etc").css("display","block");
		j$("#cart-item-etc").html("");
		//
		for(i=1;i<data.items.length;i++){
			innerContents = ''; 
			innerContents += '<div class="cart-item clearfix">';
			innerContents += '<div class="cart-item-name"><a href="'+ data.items[i].url +'">'+ data.items[i].name +'</a></div>';
			innerContents += '<div class="cart-item-num">数量　'+ data.items[i].count +'</div>';
			innerContents += '<div class="cart-item-value">単価　'+ data.items[i].price +'円</div>';
			innerContents += '</div>';
			j$("#cart-item-etc").append(innerContents);
		}
	}
}
//slideWindowHide
function slideWindowHide(){
	j$("#slidewindow_layer_template").css("display","none");
}
//getPageSize
function getPageSize() {
	        
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}

	return [pageWidth,pageHeight];
}