// 초기 변수 설정
var CartControl = {
	loadingHtml: '<table height="100%" width="99%"><tr><td align="center" valign="middle">Loading...</td></tr></table>',
	currentAlbum: 0,
	maxAlbumCount: 5,
	onLoad: false,
	
	deleteItem: function() {
		if (CartControl.currentAlbum == 0) {
			alert('스타일을 선택해주세요.');
			return;
		}
		
		var obj = $('cartItem_' + CartControl.currentAlbum);
		var list = $('cartItems');
		
		list.removeChild( obj );
		
		CartControl.currentAlbum = 0;
		
		// saveCart
		this.saveCart();
	},
	
	deleteAllItem: function() {
		CartControl.currentAlbum = 0;
		
		var list = $('cartItems');
		
		var cartItems = $$('#cartItems div');
		
		for (var i=0;i<cartItems.size();i++) {
			var item = cartItems[i];
			var obj = $('cartItem_' + item.styleSeq);
			
			list.removeChild( obj );	
		}
		
		// saveCart
		this.saveCart();
	},
	
	moveLeftItem: function() {
		if (CartControl.currentAlbum == 0) {
			alert('스타일을 선택해주세요.');
			return;
		}
		
		// 맨 처음인지 체크
		var position = this.positionItem(CartControl.currentAlbum);
		if (position < 0) {
			alert('스타일을 선택해주세요.');
			return;
		}
		
		if (position == 0) {
			// do nothing..
			return;
		}
		
		this.changePositionItem(position-1, position);
		
		// saveCart
		this.saveCart();
	},
	
	moveRightItem: function() {
		if (CartControl.currentAlbum == 0) {
			alert('스타일을 선택해주세요.');
			return;
		}
		
		// 맨 처음인지 체크
		var position = this.positionItem(CartControl.currentAlbum);
		if (position < 0) {
			alert('스타일을 선택해주세요.');
			return;
		}
		
		if (position >= (this.getItemCount()-1)) {
			// do nothing..
			return;
		}
		
		this.changePositionItem(position, position+1);
		
		// saveCart
		this.saveCart();
	},
	
	changePositionItem: function(pos1, pos2) {
		var cartItems = $$('#cartItems div');
		var item1 = cartItems[pos1];
		var item2 = cartItems[pos2];
		var id1 = item1.id;
		var id2 = item2.id;
		var html1 = item1.innerHTML;
		var html2 = item2.innerHTML;
		var styleSeq1 = item1.styleSeq;
		var styleSeq2 = item2.styleSeq;
		
		var price1 = item1.price;
		var price2 = item2.price;
		var fileSize1 = item1.fileSize;
		var fileSize2 = item2.fileSize;
		
		$('cartItem_' + item1.styleSeq).innerHTML = html2;
		$('cartItem_' + item2.styleSeq).innerHTML = html1;
		
		$('cartItem_' + item1.styleSeq).id = 'cartItem_tmp';
		$('cartItem_' + item2.styleSeq).id = id1;

		$('cartItem_tmp').id = id2;
		
		$(id1).styleSeq = styleSeq1;
		$(id2).styleSeq = styleSeq2;
		$(id1).price = price1;
		$(id2).price = price2;
		$(id1).fileSize = fileSize1;
		$(id2).fileSize = fileSize2;
	},
	
	goOrder: function(productSeq) {
		var styleSeqs = this.getstyleSeqs();
		
		if (styleSeqs == '') {
			alert('주문할 스타일을 장바구니에 먼저 담아 주세요.');
			return;
		}
		
		document.location.href = '/main/order/orderForm.jsp?productSeq=' + productSeq + '&_uid=' + (new Date()).getTime();
	},
	
	selectItem: function(styleSeq) {
		if (CartControl.currentAlbum > 0) {
			$('cartItemImg_' + CartControl.currentAlbum).className = 'albumCartImg';
		}
		
		//$('debug').innerHTML = styleSeq + ', currentAlbum=' + CartControl.currentAlbum;
		
		CartControl.currentAlbum = styleSeq;
		$('cartItemImg_' + styleSeq).className = 'albumCartImgSel';
	},
	
	addItem: function(styleSeq, name, imgSrc, cgSeq, stylePrice, fileSize) {
		if (!this.isOnLoad()) {
			alert('페이지로드가 완료된 이후에 다시 요청 해주세요.');
			return;
		}
		
		// 해당 스타일 기 등록 여부 체크
		if (this.exsitItem(styleSeq)) {
			alert('이미 장바구니에 담겨져 있는 스타일입니다.');
			return;
		}
		
		// 갯수 체크;
		if (this.getItemCount() >= this.maxAlbumCount) {
			alert('이미 장바구니에 5개의 스타일이 선택되어 있어서 장바구니에 추가할 수 없습니다.\n기존에 선택된 장바구니의 스타일을 제거 하시고 새로 추가 해주세요.');
			return;
		}
		
		CartView.writeCartList(styleSeq, name, imgSrc, cgSeq, stylePrice, fileSize);
		
		// effect
		Element.hide('cartItem_' + styleSeq);
		Effect.Appear('cartItem_' + styleSeq);
		
		// saveCart
		this.saveCart();
	},
	
	hidePrice:function() {
		$('priceLoadingDiv').style.display = 'block';
		$('priceDiv').style.display = 'none';
	},

	showPrice:function() {
		$('priceLoadingDiv').style.display = 'none';
		$('priceDiv').style.display = 'block';
	},
		
	saveCart: function() {
		this.hidePrice();
		this.updateSortable();
		
		var styleSeqs = this.getStyleSeqs();
		
		CartControl.getPrice();
	},
	
	getItemCount: function() {
		var cartItems = $$('#cartItems div');
		
		return cartItems.size();
	},
	
	getItemPrice: function() {
		var price = 0;
		var cartItems = $$('#cartItems div');
		
		for (var i=0;i<cartItems.size();i++) {
			var item = cartItems[i];
			price = price + parseInt(item.price, 10);
		}
		return price;
	},
	
	getPrice: function() {
		var styleSeqs = this.getStyleSeqs();
		
		// Ajax Call
		var param = 'cmd=getOrderAmountAllProductByStyle' +
			'&styleSeqs=' + styleSeqs +
			'&quantity=1' +
			'&_uid=' + (new Date()).getTime();
				
		var url = '/main/shop/order';
		new Ajax.Request(url, {
			parameters: param,
			onSuccess: function(xmlHttp) {
				CartView.printPrice(xmlHttp);
			},
			onFailure: function(xmlHttp) {
				alert('서버에 응답이 없습니다. 잠시 후 다시 시도해주세요.');
			}
		});
	},
	
	exsitItem: function(styleSeq) {
		var result = false;
		var cartItems = $$('#cartItems div');
		
		result = cartItems.find( function(value) {
			if (value.id == 'cartItem_' + styleSeq) {
				return true;
			}
		});
		
		return result;
	},
	
	positionItem: function(styleSeq) {
		var positon = -1;
		var cartItems = $$('#cartItems div');
		
		for (var i=0;i<cartItems.size();i++) {
			var item = cartItems[i];
			
			if (item.styleSeq == styleSeq) {
				return i;
			}
		}
		
		return positon;
	},
	
	getStyleSeqs: function() {
		var cartItems = $$('#cartItems div');
		var styleSeqs = '';
		for (var i=0;i<cartItems.size();i++) {
			var item = cartItems[i];
			if (i>0) styleSeqs = styleSeqs + ',';
			styleSeqs = styleSeqs + item.styleSeq;
		}
		return styleSeqs;
	},
	
	getCartList: function() {
		CartControl.updateSortable();
		CartControl.getPrice();
	},
	
	updateSortable: function() {
		Sortable.create("cartItems",{tag:'div',constraint:'horizontal',onUpdate: function() { CartControl.saveCart(); } });
	},
	
	isOnLoad: function () {
		return this.onLoad;
	}
}

var CartView = {
	printCartList: function(xmlHttp) {
		var xml = xmlHttp.responseXML;
		
		// 기존 목록 초기화 
		CartView.clearCartList();
		
		var record_data = xml.getElementsByTagName("record");
		
		if(record_data){
			var row = 0;
			for(row=0;row<record_data.length;row++){
				
				if (record_data.item(row).hasChildNodes())
				{
					var rows = record_data.item(row);
					var styleSeq = GetValue(rows, "album_seq");
					var name = GetValue(rows, "name");
					var cgSeq = GetValue(rows, "cg_seq");
					var imgSrc = GetValue(rows, "img_src");
					var stylePrice = GetValue(rows, "style_price");
					var fileSize = GetValue(rows, "file_size");
					
					CartView.writeCartList(styleSeq, name, imgSrc, cgSeq, stylePrice, fileSize);
				}
			}
			
			if (row == 0) {
				this.writeNoCartList();
			}
			
			CartControl.updateSortable();
			CartControl.getPrice();
		}
	},
	
	printPrice: function(xmlHttp) {
		var xml = xmlHttp.responseXML;
		
		var record_data = xml.getElementsByTagName("record");
		
		if(record_data){
			var row = 0;
			for(row=0;row<record_data.length;row++){
				
				if (record_data.item(row).hasChildNodes())
				{
					var rows = record_data.item(row);
					var price1 = GetValue(rows, "price1");
					var price2 = GetValue(rows, "price2");
					var price4 = GetValue(rows, "price4");
					var price5 = GetValue(rows, "price5");
					var price8 = GetValue(rows, "price8");
					
					$('priceProduct1').innerHTML = Comma(price1);
					$('priceProduct2').innerHTML = Comma(price2);
					$('priceProduct4').innerHTML = Comma(price4);
					$('priceProduct5').innerHTML = Comma(price5);
					$('priceProduct8').innerHTML = Comma(price8);
				}
			}
		}
		
		CartControl.showPrice();
	},

	clearCartList: function() {
		// $('cartItems').innerHTML = '';
	},
	
	loadingCartList: function() {
		// $('cartItems').innerHTML = CartControl.loadingHtml;
	},
	
	writeCartList: function(styleSeq, name, imgSrc, cgSeq, price, fileSize) {
		var albumHtml = '';
		var className = 'albumCartImg';
		
		name = name.replace('"', '&quot;');
		
		albumHtml = '<img alt="'+ name +'" id="cartItemImg_'+ styleSeq + '" src="'+ imgSrc +'" class="'+className+'" onmousedown="CartControl.selectItem(\''+ styleSeq + '\');">'
			+ '<br>'; //+Comma(price)+'원';
			
		var albumObj = document.createElement('div');
		$('cartItems').appendChild(albumObj);
		albumObj.innerHTML = albumHtml;
		albumObj.id = 'cartItem_' + styleSeq;
		albumObj.styleSeq = styleSeq;
		albumObj.price = price;
		albumObj.fileSize = fileSize;
		$('cartItem_' + styleSeq).addClassName('cartItem');
	},
	
	writeNoCartList: function() {
		
	},
	
	cartPostionSetting: function() {
		// ie 6.0 position:fixed 지원 안되는 문제를 해결하기 위해 처리
		var height = document.documentElement.clientHeight - $('cartBase').getHeight() ;
		$('wrapOuter').setStyle({'height': height + 'px'});
	}
}

Event.observe(window, 'resize', function() {
	CartView.cartPostionSetting();
});

Event.observe(window, 'load', function() {
	CartView.cartPostionSetting();
	CartControl.getCartList();
	CartControl.onLoad = true;
});
