var cartItemList = new Array();
var cookieName = "setsubiCart";
var cookieEntryKey = "cart";
var thumbnailWidth = 74;
var thumbnailHeight = 55;
var cartWindow;

function displayCart(cartWindowInstance) {
	if (cartWindowInstance) {
		bindCartWindow(cartWindowInstance);
	}
	loadCartFromCookie();
	updateCartHTML();
	initItemCursor();
}

function bindCartWindow(cartWindowInstance) {
	cartWindow = cartWindowInstance;
}

function unbindCartWindow() {
	cartWindow = null;
}

function addCart(code, title, eventObj) {
	startCursorMotion(code, title, eventObj);
/*
	var cartItem = { code : code, title : title };
	
	if (getIndexOfCart(code) >= 0) {
		enhanceCartItem(code);
	} else {
		cartItemList.push(cartItem);
		option = { whatsnew : code };
		updateCartHTML(option);
	}
*/
}

function addCartItem(code, title) {
	var cartItem = { code : code, title : title };

	if (getIndexOfCart(code) >= 0) {
		enhanceCartItem(code);
	} else {
		cartItemList.push(cartItem);
		option = { whatsnew : code };
		updateCartHTML(option);
	}
}

function removeCart(code) {
	var index = getIndexOfCart(code);
	if (index >= 0) {
		new Effect.Opacity($('cartItemList').immediateDescendants()[index], 
		{ duration: 0.5, 
		    transition: Effect.Transitions.linear, 
		   	 from:1.0, to: 0.01, afterFinish:function (obj) { removeCartData(code) } });
	}
}

function updateCartHTML(option) {
	var t = new Template($('cartItemTemplate').innerHTML);
	if (cartItemList.length == 0) {
		$('cartItemEmpty').show();
		$('cartItemList').update("");
	} else {
		$('cartItemEmpty').hide();
		$('cartItemList').update($A(cartItemList).collect(function (item) { return t.evaluate(item) }).join(""));
		if (option && typeof option.whatsnew != "undefined") {
			enhanceCartItem(option.whatsnew);
		}
	}
	if (cartWindow) {
		cartWindow.updateHeight();
	}
	if (isCookieChanged()) {
		saveCartToCookie();
	}
}

function removeCartData(code) {
	var newCartItemList = $A(cartItemList).findAll(function (item) { return item.code != code });
	cartItemList = newCartItemList;
	updateCartHTML();
}

function getIndexOfCart(code) {
	var i, l;
	for (i = 0, l = cartItemList.length; i < l; ++i) {
		if (cartItemList[i].code == code) {
			return i;
		}
	}
	return -1;
}

function enhanceCartItem(code) {
	var index = getIndexOfCart(code);
	new Effect.Pulsate($('cartItemList').immediateDescendants()[index]);
}

// 

function getRequestCode() {
	return $A(cartItemList).collect(function (item) { return item.code }).join(",");
}

function requestCart() {
	var a = serializeCart();
	alert(a);
}

// Cart Cursor

function initItemCursor() {
	Position.absolutize($('cursor'));
}

function startCursorMotion(code, title, eventObj) {
	var t = new Template($('cursorTemplate').innerHTML);
	var button = $(eventObj);
	var cursor = $('cursor');
	Position.clone(button, cursor, {offsetTop: (button.getHeight() - thumbnailHeight) / 2, offsetLeft: (button.getWidth() - thumbnailWidth) / 2});

	cursor.update(t.evaluate({ code : code }));
	new Effect.Opacity(cursor, {duration:0.3, transition: Effect.Transitions.linear, from: 0.01, to: 1.0, afterUpdate:function (obj) { if (obj.currentFrame == 0) cursor.show() } });
	new Effect.Opacity(cursor, {duration:0.5, transition: Effect.Transitions.linear, from: 1.0, to: 0.01, queue: 'end', afterFinish:function (obj) { $('cursor').hide(); addCartItem(code, title) }});
	new Effect.MoveBy(cursor, 0, 240, {duration:1.0, transition: Effect.Transitions.linear });
}

// Cookie I/O

function saveCartToCookie() {
	document.cookie = cookieEntryKey + "=" + serializeCart() + "; path=/setsubi";
}

function loadCartFromCookie() {
	var str = getCartCookieString();
	if (str != "") {
		cartItemList = unserializeCart(str);
	}
}

function isCookieChanged() {
	return serializeCart() != getCartCookieString();
}

function getCartCookieString() {
	var re = new RegExp(cookieEntryKey + "=([^;]+)");
	var result = re.exec(document.cookie);
	if (result) {
		return result[1];
	} else {
		return "";
	}
}

// Serialization and Unserialization

function serializeCart() {
	return $A(cartItemList).collect(function (item) { return item.code + ":" + escape(item.title) }).join(",");
}

function unserializeCart(str) {
	return $A(str.split(",")).collect(function (item) { var x = item.split(":"); return { code : x[0], title : unescape(x[1]) } });
}

// Submit

function executeRequest(formId) {
	$A(cartItemList).each(function (item) { new Insertion.Bottom(formId, '<input type="hidden" name="KC" value="' + item.code + '" />') });
	$(formId).submit();
}

