(function(){

var dropMenu = window.dropMenu = function(eid) { 
	return new dropMenu.prototype.init(eid);
}
dropMenu.timer = null;
dropMenu.prototype = {
	init: function(eid) {
		var isMenu = document.getElementById(eid);
		if(isMenu && isMenu != null) { this.mainLinksEvent(isMenu); }
	},
	mainLinksEvent: function(isMenu) {
		var _this = this, mainlis = isMenu.getElementsByTagName('li');
		for(var i = 0; i < mainlis.length; i ++) {
			var mlink = mainlis[i].getElementsByTagName('a')[0];
			mlink.onmouseover = function() { _this.resetAll(mainlis); _this.subMenuPop(this); }
			mlink.onmouseout = function()  { _this.subMenuPop(this); }
		}
	},
	subMenuPop: function(mlink) {
		clearTimeout(dropMenu.timer);
		var _this = this, sublink = mlink.parentNode.getElementsByTagName('div')[0];
		
		if (sublink) {
			var isShow = sublink.style.display;
			if (isShow == 'none' || isShow == '') {
				sublink.style.display = 'block';
			}
			if (isShow == 'block') {
				sublink.onmouseout = function(){ 
					clearTimeout(dropMenu.timer);
					dropMenu.timer = setTimeout(function(){ sublink.style.display = 'none'; }, 200); 
				}
				sublink.onmouseover = function(){ clearTimeout(dropMenu.timer); sublink.style.display = 'block'; }
			}
		}
	},
	resetAll: function(mainlis) {
		for(var i = 0; i < mainlis.length; i ++) {
			var subBoxes = mainlis[i].getElementsByTagName('div')[0];
			if (subBoxes) {
				subBoxes.style.display = 'none';
			}
		}
	}
}
dropMenu.prototype.init.prototype = dropMenu.prototype;
})();

if (typeof jCart == "undefined" || !jCart) { var jCart = {}; }
jCart.namespace = function() {
    var a = arguments, o = null, i, j, d;
    for (i = 0; i < a.length; i = i + 1) {
        d = ("" + a[i]).split("."); 
        o = jCart;
		
        for (j = (d[0] === "jCart") ? 1 : 0; j < d.length; j = j + 1) {
            o[d[j]] = o[d[j]] || {};
            o = o[d[j]];
        }
    }
    return o;
};

jCart.namespace("jCart.structure", "jCart.todo");

jCart.structure = (function(){
	var cartName = 'BACART';
	var cartView = 'jCart_viewbox';
	var cartCount = 'jCart_countbox';
	
	function formatFloat(num) { return Math.round(num*Math.pow(10, 2))/Math.pow(10, 2); }
	String.prototype.trim = function() { return this.replace(/^\s*|\s*$/g,''); };

	function _readCart(cname) {
	  var cartValue = "", search = cname + "=";
	  if (document.cookie.length > 0) { 
		offset = document.cookie.indexOf(search);
		if (offset != -1) { 
			offset += search.length;
			end = document.cookie.indexOf(";", offset);
			if (end == -1) end = document.cookie.length;
			cartValue = document.cookie.substring(offset, end)
		}
	  }
	  return cartValue;
	}
	
	function _getCart() {
		var cartValues = _readCart(cartName), arr = [];
			
		if (cartValues != "") {
			values = cartValues.split(',');
			for (var i = 0; i < values.length; i ++) {			
				if (values[i] != '' && typeof values[i] == 'string') {
					var info = values[i].split('#');
					
					product = {
						'id'	: info[0],
						'name'	: info[1],
						'amt'	: info[2],
						'price'	: info[3],
						'img'	: info[4],
						'year'	: info[5]
					};
					
					arr.push(product);
				}	
			}
		}
		return arr;
	}
	
	function _deleteProduct(pro) {
		if (confirm("Remove?")) {
			document.cookie = cartName + "=" + _readCart(cartName).replace(','+pro, '');
			jCart.todo.putHtml();
		}
	}
	
	function _dimAmt(pro){
		_updateAmt(pro, -1);
	}
	
	function _addAmt(pro){
		_updateAmt(pro, 1);
	}
	
	function _modifyAmt(pro, obj){
		var curamt = obj.value.trim();
		
		if( /^\d+$/.test(curamt) ){
	
			var matchAmt = /(^0+)\d+/.exec(curamt);
			if ( matchAmt != null ) {
				curamt = matchAmt[0].replace(matchAmt[1], '');
			}
			
			if (curamt <= 0) {
				_deleteProduct(pro);
			} else {
				_updateAmt(pro, curamt);
			}
		} else {  }
	}
	
	function _updateAmt(pro, n) {
		var proinfo = pro.split('#'),
			pid 	= proinfo[0],
			pname 	= proinfo[1],
			amt		= proinfo[2],
			price 	= proinfo[3],
			img		= proinfo[4],
			year	= proinfo[5];
		
		var curamt = amt;
		if (n === -1 || n === 1) {
			curamt = parseInt(amt) + parseInt(n);
		} else {
			curamt = parseInt(n);	
		}
		
		if (curamt <= 0) {
			_deleteProduct(pro);
		} else {
			var	newinfo = [pid, pname, curamt, price, img, year].join("#");
			
			document.cookie = cartName + "=" + _readCart(cartName).replace(pro, newinfo);
			jCart.todo.putHtml();
		}
	}
	
	return {
	
		count: function(){
			var cartValues = _readCart(cartName), values = cartValues.split(',');
			document.getElementById(cartCount).innerHTML = (values.length - 1);
		},
	
		add: function(pid, pname, amt, price, img, year) {
			var is_Product = false,
				proValue = ','+[pid, escape(pname), amt, price, img, year].join("#");
			
			var curamt = 0;
			
			var cartValues = _readCart(cartName), values = cartValues.split(',');
			if (values.length > 1) {
				for (var i = 0; i < values.length; i ++) {
					var match = RegExp('^'+pid+'#', "ig");
					if (match.exec(values[i]) != null) {
						is_Product = true;
						
						proValue = values[i];
						curamt = values[i].split('#')[2];
					}			
				}
			}
			
			var info = 'Success Add to Cart.';
			if (is_Product) {
				var addamt = parseInt(amt) + parseInt(curamt),
					newinfo = [pid, escape(pname), addamt, price, img, year].join("#");
				
				document.cookie = cartName + "=" + cartValues.replace(proValue, newinfo);
				info = unescape(pname) +' '+ year +': number has been updated.';
			}
			else {
				document.cookie = cartName + "=" + cartValues + proValue;
			}
			
			if (document.getElementById(cartCount)) { jCart.todo.count(); }
			
			alert(info);
		},
		
		modify: function(pid, dotype) {
			var cartValues = _readCart(cartName), values = cartValues.split(',');
			
			for (var i = 0; i < values.length; i ++) {
				var match = RegExp('^'+pid+'#', "ig");
				if (match.exec(values[i]) != null) {
					
					if (dotype === 0) {
						_deleteProduct(values[i]);
					} else if (dotype === -1) {
						_dimAmt(values[i]);
					} else if (dotype === 1) {
						_addAmt(values[i]);
					} else {
						if (typeof dotype === 'object') {
							_modifyAmt(values[i], dotype);
						}
					}
					
				}			
			}
		},
		
		putHtml: function() {
			var arr = _getCart(), ch = [], cartPrice = 0;
	
			ch.push('<table class="list_view" cellpadding="5" cellspacing="0">');
				ch.push('<tr class="title">');
				ch.push('<td>Product</td>');
				ch.push('<td>Quantity</td>');
				ch.push('<td>Status</td>');
				ch.push('<td>Remove</td>');
				ch.push('<td>Price</td>');
				ch.push('<td>Total</td>');
				ch.push('</tr>');
			
			for (var i = 0; i < arr.length; i ++) {
				var pro = arr[i], 
					proPrice = formatFloat(pro.amt * pro.price);
				
				ch.push('<tr>');
				ch.push("<td>"+
							"<img class=left src="+ pro.img +" width=150 />"+
							"<div class=left style='padding-left: 10px;'>"+
							"<p>"+ unescape(pro.name) +"</p>"+
							"<p>"+ pro.year +"</p>"+
							"</div>"+
						"</td>");
				ch.push("<td>"+
							"<input onclick=jCart.todo.modify('"+ pro.id +"',-1) value=- type=button />"+
							"<input class=smalltxt value='"+ pro.amt +"' onblur=jCart.todo.modify('"+ pro.id +"',this) />"+
							"<input onclick=jCart.todo.modify('"+ pro.id +"',1) value=+ type=button />"+
						"</td>");
				ch.push('<td>In Stock</td>');
				ch.push("<td><input onclick=jCart.todo.modify('"+ pro.id +"',0) type=checkbox /></td>");
				ch.push('<td>$'+ formatFloat(pro.price) +'</td>');
				ch.push('<td>$'+ formatFloat(proPrice) +'</td>');
				ch.push('</tr>');
				
				cartPrice += formatFloat(proPrice);
			}
				ch.push('<tr>');
				ch.push('<td colspan="5" style="text-align: right;">Current Subtotal：</td>');
				ch.push('<td>$'+ formatFloat(cartPrice) +'</td>');
				ch.push('</tr>');
				
			ch.push('</table>');
			
			if (arr.length == 0) { ch.push('<div>No product.</div>'); }
			
			if (document.getElementById(cartView)) { document.getElementById(cartView).innerHTML = ch.join(''); }
		}
	};
})();
jCart.todo = jCart.structure;
