/********************************
 * WebMall Cart system
 *
 *
 ********************************/
var Cart = function(sname){

	this.sname = sname;
	this.cookie = new Cookie();
	this.saved = this.cookie.get(this.sname);
	this.LC = 0;
	this.pt = 0;
	this.BC = 0;
	
	//カートに入れれる種類の最大数。
	this.max_cart_num = 19;
	//1種類のアイテムの最大個数。
	this.max_quantity = 99;
	
	/*------------------------
	 * カートの中身取得
	 *------------------------*/
	this.getCart = function(){
		c_tmp = this.cookie.get(this.sname);
		return (c_tmp);
	}
	
	/*-------------------------------------------
	 * ショッピングカートパーツ内サマリー情報
	 *-------------------------------------------*/
	this.getCartSummary = function(id_name,ar){

		var elem = document.getElementById(id_name);
		var TMP_TABLE   = this.removeComment(document.getElementById(id_name + "_TABLE").innerHTML);
		var TMP_DATA    = this.removeComment(document.getElementById(id_name + "_DATA").innerHTML);

		var tmp = this.getCart();
		
		if (tmp !=""){
			var ar_tmp = tmp.evalJSON();
			var types = new Array();
			
			for ( i = 0 ; i < ar.length ; i ++){
				types[i] = new Array();
				types[i]["name"] = ar[i];
				types[i]["value"] = 0;
				types[i]["point"] = 0;
			}
			
			for (var i = 0 ; i < ar_tmp.length ; i++ ){
				for (var j = 0 ; j < types.length ; j++ ){
					if (ar_tmp[i].pType == types[j]["name"]){
						types[j]["value"] += ar_tmp[i].iQty * ar_tmp[i].iPrice;
						types[j]["point"] += ar_tmp[i].iQty * ar_tmp[i].iPoint*10;
						types[j]["pType"] = ar_tmp[i].pType;
					}
				}
			}

			var DATA = "";
			var THISLINE = "";
			var idx_point = -1;
			for (var i = 0  ;i < types.length ; i++){
				// ポイントは一番最後に表示
				if(types[i]["name"] == "pt") {
				 	idx_point = i;
				}else{
					THISLINE = TMP_DATA.replace(/<%SUM%>/g, types[i]["value"]);
					DATA += THISLINE.replace(/<%TYPE%>/g, types[i]["name"] );
				}
			}
			if((idx_point>0)&&(types[idx_point]["value"] > 0)) {
				THISLINE = TMP_DATA.replace(/<%SUM%>/g, types[idx_point]["value"]*10);
				DATA += THISLINE.replace(/<%TYPE%>/g, "pt" );
			}
			
			elem.innerHTML = TMP_TABLE.replace(/<%DATA%>/g, DATA);
		}
	}


	/*-------------------------------------------
	 * ショッピングカートパーツ内商品一覧
	 *-------------------------------------------*/
	this.getCartDetail = function(id_name){
		
		var elem = document.getElementById(id_name);

		var TMP_TABLE   = this.removeComment(document.getElementById(id_name + "_TABLE").innerHTML);
		var TMP_DATA    = this.removeComment(document.getElementById(id_name + "_DATA").innerHTML);

		var tmp = this.getCart();
		
		if (tmp !=""){
			var ar_tmp = tmp.evalJSON();
			var DATA = "";

			for ( i = 0 ; i < ar_tmp.length ; i++ ){
				var THISLINE = TMP_DATA.replace(/<%NAME%>/g, 	ar_tmp[i]["pName"]);
				if(ar_tmp[i].pType == 'pt') {
					THISLINE = THISLINE.replace(/<%AT%>/g, 		(ar_tmp[i].iPrice*10)  + ar_tmp[i].pType );
				}else{
					THISLINE = THISLINE.replace(/<%AT%>/g, 		ar_tmp[i].iPrice  + ar_tmp[i].pType );
				}
				THISLINE = THISLINE.replace(/<%AMOUNT%>/g,	ar_tmp[i].iQty);
				DATA += THISLINE.replace(/<%DELNUM%>/g,		i);
			}
			
			elem.innerHTML = TMP_TABLE.replace(/<%DATA%>/, DATA);
		}
	}
	
	/*-------------------------------------------
	 * カートのリセット
	 *-------------------------------------------*/
	this.reset = function(){
		c_tmp = this.cookie.delele(this.sname);
	}

	/*-------------------------------------------
	 * カートの初期化
	 *-------------------------------------------*/
	this.init = function(cartName){

		strTmp = this.cookie.get(this.sname);
		if(strTmp != ""){
			var objTmp = strTmp.evalJSON();
		}else{
			var objTmp = {
				"cartName" : cartName , 
				"createDate" : parseInt((new Date)/1000)
			}
		}

	}
  
	/*-------------------------------------------
	 * カートの削除
	 *-------------------------------------------*/
	this.del =  function(i){
		strTmp = this.cookie.get(this.sname);
		objTmp = strTmp.evalJSON();
		objTmp.splice(i, 1);
		this.cookie.set(this.sname,objTmp.toJSON());
	}
	
	/*-------------------------------------------
	 * カートにアイテムを追加
	 *-------------------------------------------*/
	this.add =  function(pName,pId,iPrice,iPoint,iQty,pType,bStackable){
		
		strTmp = this.cookie.get(this.sname);
		iNewQty = 0;
		
		if(strTmp == ""){
			objTmp = [];
			num = 0;
			
		}else{
			objTmp = strTmp.evalJSON();
			num = objTmp.length;
		}
		
		//個数の数値チェック数字以外は入力できない。
		if (isNaN(iQty)) {
			alert("数値以外が含まれています。");
			return false;
			//return void(0);
		}

		//0以下の場合はアラートを表示して終了
		if (iQty <= 0) {
			alert('数量は1以上で入力してください。');
			return false;
			//return void(0);
		}
			var unititemflg = false;
			var updated = false;
			//カートの限界20個まで
			if (objTmp.length > this.max_cart_num) {
				alert('これ以上カートに入りません。');
				return false;
			}
			for ( i = 0 ; i < objTmp.length ; i++ ){
				if(objTmp[i]["pId"] == pId ){
					//単体購入
					if (bStackable == 'unit') {
						//何もしない
						alert('すでにカートに入っています。');
						return false;
						unititemflg = true;
					} else {
						iNewQty = objTmp[i]["iQty"] + iQty;
						//限界個数。99個まで。
						if (iNewQty > this.max_quantity) {
							alert('1度に購入出来る個数は99個までです');
							return false;
						}
						var x =   {
							"pId" : objTmp[i]["pId"],
							"pName" : objTmp[i]["pName"],
							"iPrice" : objTmp[i]["iPrice"],
							"iPoint" : objTmp[i]["iPoint"],
							"iQty" : iNewQty,
							"pType" : pType
						}
						objTmp[i] = x;
						updated = true;
					}
				}
			}
			if(!updated){
				//限界個数。99個まで。
						if (iQty > this.max_quantity) {
							alert('1度に購入出来る個数は99個までです');
							return false;
						}
				if (!unititemflg) {
					var x =   {
						"pId" : pId,
						"pName" : pName,
						"iPrice" : iPrice,
						"iPoint" : iPoint,
						"iQty" : iQty ,
						"pType" : pType 
					}
					objTmp[objTmp.length] = x;
				}
			
			}

		this.cookie.set(this.sname,objTmp.toJSON());
	}

	/*-------------------------------------------
	 * カートが空かどうかを判別
	 *-------------------------------------------*/
	this.isEmpty = function() {
		var tmp = this.getCart();
		if(tmp == "")   return true;

		var ar_tmp = tmp.evalJSON();
		if( ar_tmp.length > 0)	return false;

		return true;
	}
	

	/*-------------------------------------------
	 * テンプレート処理関数
	 *	htmlコメント部削除
	 *-------------------------------------------*/
	this.removeComment = function(strHtml) {
		return( strHtml.substr(strHtml.indexOf("<!--")+4, strHtml.lastIndexOf("-->")-4) );
	}

	/*-------------------------------------------
	 * カートの明細のHTML組み立て
	 *-------------------------------------------*/
	this.getCartLayout = function(id_name, ar_tmp) {

		if(ar_tmp.length == 0) {
			return('<b><font color="red">カートは空っぽです。</font></b>')
		}

		// テンプレート取得
		var TMP_TABLE 	= this.removeComment(document.getElementById(id_name + "_TABLE").innerHTML);
		var TMP_DATA  	= this.removeComment(document.getElementById(id_name + "_DATA").innerHTML);
		var TMP_SUM = this.removeComment(document.getElementById(id_name + "_SUM").innerHTML);
		var TMP_SUM1	= this.removeComment(document.getElementById(id_name + "_SUM1").innerHTML);
		var TMP_SUM2	= this.removeComment(document.getElementById(id_name + "_SUM2").innerHTML);

		var DATA = "";
		var SUM = "";

		var sumPrice = {};
		var sumMillage = 0
		for ( var i = 0 ; i < ar_tmp.length ; i++ ){
			var point = "";
			if(ar_tmp[i].iPoint > 0) {
				point = (ar_tmp[i].iPoint * ar_tmp[i].iQty*10) + "pt";
			}else{
				point = "-"
			}

			var THISLINE = TMP_DATA.replace(/<%NAME%>/g,ar_tmp[i]["pName"]);	//商品名
			THISLINE = THISLINE.replace(/<%AMOUNT%>/g,	ar_tmp[i].iQty + '個');		// 個数
			if(ar_tmp[i].pType == 'pt') {
				THISLINE = THISLINE.replace(/<%AT%>/g, (ar_tmp[i].iPrice*10) + ar_tmp[i].pType );	// 単価
				THISLINE = THISLINE.replace(/<%PRICE%>/g,	(ar_tmp[i].iPrice * ar_tmp[i].iQty*10) + ar_tmp[i].pType);	// 価格
			}else{
				THISLINE = THISLINE.replace(/<%AT%>/g, ar_tmp[i].iPrice + ar_tmp[i].pType );	// 単価
				THISLINE = THISLINE.replace(/<%PRICE%>/g,	(ar_tmp[i].iPrice * ar_tmp[i].iQty) + ar_tmp[i].pType);	// 価格
			}
			THISLINE = THISLINE.replace(/<%MILLAGE%>/g,	point);	// 付与マイレージ（LP)
			THISLINE = THISLINE.replace(/<%DELNUM%>/g,	i);	// 削除Index

			DATA += THISLINE;

			if(sumPrice[ar_tmp[i].pType] === undefined)	sumPrice[ar_tmp[i].pType] = 0;

			if(ar_tmp[i].pType == 'pt') {
				sumPrice[ar_tmp[i].pType] += (ar_tmp[i].iPrice * ar_tmp[i].iQty*10);
			}else{
				sumPrice[ar_tmp[i].pType] += (ar_tmp[i].iPrice * ar_tmp[i].iQty);
			}
			sumMillage += (ar_tmp[i].iPoint * ar_tmp[i].iQty*10);
		}


		var rowSpan = 0;
		var firstPayType = "";
		// rowspan数と最初のPayTypeを求める(Pointは最後に表示）
		for(var pType in sumPrice) {
			rowSpan++;
			if(pType != "pt") {
				if(firstPayType == "")	firstPayType = pType;
			}
		}
		if(firstPayType == "")	firstPayType = "pt";


		// 最初のPayTypeを表示
		var addMillage = "-";
		if(sumMillage > 0)	addMillage = sumMillage + "pt";

		var SUM1 = TMP_SUM1.replace(/<%COUNT%>/g, rowSpan);
		SUM1 = SUM1.replace(/<%SUMPRICE%>/g, 	sumPrice[firstPayType] + firstPayType);
		SUM1 = SUM1.replace(/<%MILLAGE%>/g, 	addMillage);

		var SUM2 = "";

		// 2個目以降のPayTypeを表示（rowspan)
		if(firstPayType != "pt") {
			for(var pType in sumPrice) {
				if(("pt" != pType)&&(firstPayType != pType)) {  // pt以外を先に表示
					SUM2 += TMP_SUM2.replace(/<%SUMPRICE%>/g,	sumPrice[pType] + " " + pType );
				}
			}
			if(sumPrice["pt"] > 0) SUM2 += TMP_SUM2.replace(/<%SUMPRICE%>/g,	sumPrice["pt"] + "pt");
		}

		SUM = TMP_SUM.replace(/<%SUM1%>/g, SUM1);
		SUM = SUM.replace(/<%SUM2%>/g, SUM2);

		// 出力用HTML
		var OUT_HTML = TMP_TABLE.replace(/<%DATA%>/g, DATA);
		OUT_HTML = OUT_HTML.replace(/<%SUM%>/g, SUM);

		return(OUT_HTML)
	}

	/*-------------------------------------------
	 * カートの明細表示
	 *-------------------------------------------*/
	this.getCartCheck = function(id_name){
		
		var elem = document.getElementById(id_name);
		var tmp = this.getCart();
		if(tmp == "")	return;
		
		var ar_tmp = tmp.evalJSON();
		var html_tmp = this.getCartLayout(id_name, ar_tmp);

		elem.innerHTML = this.htmlEscape(html_tmp);
	}
	
	
	/*-------------------------------------------
	 * 購入確認（confirm画面）のカート部表示
	 *-------------------------------------------*/
	this.getBuyCheck = function(id_name){
		var elem = document.getElementById(id_name);
		var tmp = this.getCart();
		if(tmp == "")   return;

		var ar_tmp = tmp.evalJSON();
		var html_tmp = this.getCartLayout(id_name, ar_tmp);

		elem.innerHTML = this.htmlEscape(html_tmp);

		return;
	}
	
	/*-------------------------------------------
	 * 購入確認（confirm画面）の購入後残高
	 *-------------------------------------------*/
	this.getAfterBuy = function(id_name){
		var elem = document.getElementById(id_name);
		var tmp = this.getCart();
		if(tmp == "")   return;

		var ar_tmp = tmp.evalJSON();

		// 利用額計算
		var sumLC = 0;
		var sumBC = 0;
		var sumpt = 0;
		var sumptAdd = 0;

		for ( var i = 0 ; i < ar_tmp.length ; i++ ){
			if(ar_tmp[i].iPoint > 0)	sumptAdd += ar_tmp[i].iPoint * ar_tmp[i].iQty*10;
			if(ar_tmp[i].pType == "LC")	sumLC    += ar_tmp[i].iPrice * ar_tmp[i].iQty;
			if(ar_tmp[i].pType == "pt")	sumpt    += ar_tmp[i].iPrice * ar_tmp[i].iQty*10;
			if(ar_tmp[i].pType == "BC")	sumBC    += ar_tmp[i].iPrice * ar_tmp[i].iQty;
		}

		// HTMLの組み立て
		var TMP_TABLE   = this.removeComment(document.getElementById(id_name + "_TABLE").innerHTML);

		TMP_TABLE = TMP_TABLE.replace(/<%LC1%>/g, this.LC );
		TMP_TABLE = TMP_TABLE.replace(/<%LC2%>/g, this.divMinusWrap(sumLC*-1, id_name));
		TMP_TABLE = TMP_TABLE.replace(/<%LC3%>/g, this.divMinusWrap(this.LC - sumLC, id_name));

		TMP_TABLE = TMP_TABLE.replace(/<%BC1%>/g, this.BC );
		TMP_TABLE = TMP_TABLE.replace(/<%BC2%>/g, this.divMinusWrap(sumBC*-1, id_name));
		TMP_TABLE = TMP_TABLE.replace(/<%BC3%>/g, this.divMinusWrap(this.BC - sumBC, id_name));

		TMP_TABLE = TMP_TABLE.replace(/<%pt1%>/g, this.pt*10 );
		TMP_TABLE = TMP_TABLE.replace(/<%pt20%>/g, this.divMinusWrap(sumpt*-1, id_name));
		TMP_TABLE = TMP_TABLE.replace(/<%pt21%>/g, this.divPlusWrap(sumptAdd, id_name));
		TMP_TABLE = TMP_TABLE.replace(/<%pt3%>/g, this.divMinusWrap(this.pt*10 - sumpt + sumptAdd , id_name));

		elem.innerHTML = this.htmlEscape(TMP_TABLE);
		return;
	}

	/*-------------------------------------------
	 * プラス数値の div 囲い
	 *-------------------------------------------*/
	this.divPlusWrap = function( val, name ) {
		if(val <= 0)	return val;
		return '<div class="' + name + '_plus">+' + val + '</div>';
	}

	/*-------------------------------------------
	 * マイナス数値の div 囲い
	 *-------------------------------------------*/
	this.divMinusWrap = function( val, name ) {
		if(val >= 0)	return val;
		return '<div class="' + name + '_minus">' + val + '</div>';
	}

	/**LC,pt,BC のセット*/
	/*-------------------------------------------
	 * 各残高のセット
	 *-------------------------------------------*/
	this.setCoin = function(LC,pt,BC){
		this.LC = LC;
		this.BC = BC;
		this.pt = pt;
	}
	
	/*-------------------------------------------
	 * HTMLのエスケープ関数 ??????
	 *-------------------------------------------*/
	this.htmlEscape = function(html){
		return html;
		/*
		var scriptbox = document.createElement('div');
	    scriptbox.style.display = 'none';
	    scriptbox.innerHTML = html;
	    document.body.appendChild(scriptbox);
	    */
	}

	/*-------------------------------------------
	 * 購入ボタンの押下チェック
	 *-------------------------------------------*/
	this.submit_confirm = function(formObj){
		// 合計額のチェック
		var tmp = this.getCart();
		var ar_tmp = tmp.evalJSON();

		var sumPrice = {};
		sumPrice['LC'] = 0;
		sumPrice['BC'] = 0;
		sumPrice['pt'] = 0;
		for ( var i = 0 ; i < ar_tmp.length ; i++ ){
			sumPrice[ar_tmp[i].pType] += (ar_tmp[i].iPrice * ar_tmp[i].iQty);
		}

		if(sumPrice['LC']>0) {
			if(this.LC < sumPrice['LC']) {
				alert("LC残高が不足しています");
				return false;
			}
		}

		if(sumPrice['BC']>0) {
			if(this.BC < sumPrice['BC']) {
				alert("BC残高が不足しています");
				return false;
			}
		}
				
		if(sumPrice['pt'] > 0) {
			if(this.pt < sumPrice['pt']) {
				alert("pt残高が不足しています");
				return false;
			}
		}
			

		// 受け取りサーバのチェック
		if( typeof formObj.server_id != "undefined" ) {

			if( "SELECT" == formObj.server_id.nodeName ) {
				// SelectBox 
				if(formObj.server_id.value == "") {
					alert("受け取り先のサーバを選択してください");
					return false;
				}
			}else{
				// その他（check or radio)
				var result=false;
				for(var i=0; i < formObj.server_id.length; i++) {
					if(formObj.server_id[i].checked) {
				 		result = true;
						break;
					}
				}
				if(!result) {
					alert("受け取り先のサーバを選択してください");
					return false;
				}
			}
		}

		// 多重Submit防止
		formObj.cart_submit.disabled = true;

		return true;
	}

}

