/**
 * @author zsolthorvath
 */

if (!this.SB) {
	SB = {};
	SB.basket = new basket();
	SB.coupons = new coupons();
	
	SB.coupons.addCoupon({coupon: 'JNNA20', stylenumber: 'MCP07JOANNA', percentage: 20, description: '20% off on Joanna Clutch'});
	
	readBasketFromCookie();
}

function basket() {
	this.items = new Array();
	this.coupon = null;
	
	this.empty = function() {
		this.items.splice(0, this.items.length);
		this.coupon = null;
	}
	
	this.addItem = function(item) {
		var existingItem = this.containsItem(item.itemRef);
		if (existingItem != null) {
			existingItem.qty = existingItem.qty + parseInt(item.qty);
			this.recalculateDiscount(existingItem);
		} else {
			newItem = new sbitem(item);
			this.items[this.items.length] = newItem;
			this.recalculateDiscount(newItem);
		}
		
		
	}
	
	this.changeQty = function(itemRef, newQty){
		if (newQty == null || newQty == 0) {
			this.removeItem(itemRef); 
		} else {
			var existingItem = this.containsItem(itemRef);
			if (existingItem != null) {
				existingItem.qty = parseInt(newQty);
			}
		}
	}
	
	this.removeItem = function(itemRef) {
		var index = -1;
		
		if (this.items != null) {
			for (i=0; i<this.items.length && index == -1; i++) {
				if (this.items[i].itemRef == itemRef) {
					index = i;
				}
			}
		}
		
		if (index >= 0)
			this.items.splice(index, 1);
	}
	
	this.containsItem = function(itemRef) {
		var contains = null;
		
		if (this.items != null) {
			for (i=0; i<this.items.length && contains == null; i++) {
				if (this.items[i].itemRef == itemRef) {
					contains = this.items[i];
				}
			}
		}
		
		return contains;
	}
	
	this.getTotalPrice = function() {
		var totalPrice = parseFloat(0.0);
		if (this.items != null) {
			for (i = 0; i < this.items.length; i++) {
				totalPrice += this.items[i].getItemPrice();
			}
		}	
		
		return totalPrice;	
	}
	
	this.addCoupon = function(coupon){
		var couponObj = SB.coupons.getCoupon(coupon);
		
		if (couponObj != null) {
			this.coupon = couponObj;
			
		}
		this.recalculate();
	
		return couponObj != null;
	}
	
	this.removeCoupon = function () {
		this.coupon = null;
		this.recalculate();
	}
	
	this.recalculate = function() {
		if (this.items != null) {
			for (i = 0; i < this.items.length; i++) {
				this.recalculateDiscount(this.items[i]);
			}
		}	
		
	}
	
	this.recalculateDiscount = function(item) {
		if (this.coupon != null && item.itemRef.indexOf(this.coupon.stylenumber) == 0) {
			item.discountPrice = item.unitPrice * (1-this.coupon.percentage/100);
		} else
			item.discountPrice = null;
		
	}
	
	this.toHtml = function() {
		var html = '\
	        <table width="567" cellpadding="1" cellspacing="0" class="productsname">\
              <tr align="center" valign="bottom">\
                <td width="180" height="34" align="left" style="border-bottom:solid 1px #ffffff "><strong>Name</strong></td>\
                <td width="100" height="34" align="left" style="border-bottom:solid 1px #ffffff "><strong>Color</strong></td>\
                <td width="73" height="34" align="center" style="border-bottom:solid 1px #ffffff "><strong>Quantity</strong></td>\
                <td width="100" height="34" align="center" style="border-bottom:solid 1px #ffffff "><strong>Price</strong></td>\
                <td colspan="2" style="border-bottom:solid 1px #ffffff ">&nbsp;</td>\
              </tr>';
		
		if (this.items != null) {
			for (i = 0; i < this.items.length; i++) {
				var cItem = this.items[i];

              html += '<tr align="center">\
                <td height="16" align="left" valign="middle">'+cItem.name+'</td>\
                <td height="16" align="left" valign="middle">'+cItem.color+'</td>\
                <td height="16" align="center" valign="middle"><input id="'+cItem.itemRef+'Qty" value="'+cItem.qty+'" style="border: solid 1px black; background-color: #e5e4e0;width:30px;text-align:center;" /></td>\
                <td height="16" align="center" valign="middle">$'+dojo.currency.format(cItem.getItemPrice())+'</td>\
                <td height="16" width="60"><a href="#" onclick="changeItemQty(\''+cItem.itemRef+'\',document.getElementById(\''+cItem.itemRef+'Qty\').value);"><img src="../images/one_october_update.gif" border="0" /></a></td>\
                <td height="16" width="60"><a href="#" onclick="removeItem(\''+cItem.itemRef+'\')"><img src="../images/one_october_remove.gif" border="0" /></a></td>\
              </tr>';

			}
			
			html += '\
             <tr align="center" valign="center">\
                <td colspan="2" style="border-top:solid 1px #ffffff ">&nbsp;</td>\
                <td align="center" style="border-top:solid 1px #ffffff;"><strong>Subtotal:</strong></td>\
                <td style="border-top:solid 1px #ffffff "><strong>'+dojo.currency.format(SB.basket.getTotalPrice())+'</strong></td>\
                <td colspan="2" style="border-top:solid 1px #ffffff ">&nbsp;</td>\
              </tr>';
		}
		html += '</table>';
		
		return html;
	}
	
}

function sbitem(props) {
	this.itemRef = props.itemRef;
	this.qty = parseInt(props.qty);
	this.name = props.name;
	this.color = props.color;
	this.unitPrice = parseFloat(props.unitPrice);
	this.discountPrice = null;
	
	this.changeQty = function(newQty) {
		this.qty = newQty;
	};
	
	this.getItemPrice = function () {
		if (this.discountPrice == null)
			return this.qty * this.unitPrice;
		else
			return this.qty * this.discountPrice;
	}
}

function coupons () {
	this.couponList = new Array();
	
	this.addCoupon = function(props) {
		this.couponList.push(new coupon(props));
	}
	
	this.getCoupon = function (coupon) {
		var couponObj = null;
		if (this.couponList != null) {
			for (i = 0; i < this.couponList.length && couponObj == null; i++) {
				if (this.couponList[i].coupon == coupon)
				couponObj = this.couponList[i];
			}
		}	
		
		return couponObj;
	}
}

function coupon(props) {
	this.coupon = props.coupon;
	this.stylenumber = props.stylenumber;
	this.percentage = props.percentage;
	this.description = props.description;
}

function writeShoppingBasket(){
	var sbDiv = document.getElementById('shoppingBasketDiv');
	var spanCpn = dojo.byId('couponSpan');
	if (SB.basket.items.length > 0) {
		sbDiv.innerHTML = SB.basket.toHtml();
		document.getElementById('submitbutton').style.display = 'block';
		
		if (SB.basket.coupon == null) {
			spanCpn.innerHTML = '<span class="productsname">Coupon code:</span> <input id="couponCode" style="border: 1px solid black; background-color: rgb(229, 228, 224); \
			                     width: 100px; text-align: left;" /><div id="promotion" style="display:inline;cursor:pointer;\
								 padding-left:8px;" onclick="applyCoupon(dojo.byId(\'couponCode\').value);"><img border="0" \
								 src="../images/one_october_apply.gif"/></div>';
		} else {
			spanCpn.innerHTML = '<span class="productsname">Coupon code: '+SB.basket.coupon.coupon+' - '+SB.basket.coupon.description+'</span>\
								<div id="promotion" style="display:inline;cursor:pointer;\
								 padding-left:8px;" onclick="removeCoupon();">\
								 <img src="../images/one_october_remove.gif" border="0" /></div>';
		}
	}
	else {
		document.getElementById('submitbutton').style.display = 'none';
		sbDiv.innerHTML = '\
	        <table width="540" cellpadding="1" cellspacing="0" class="productsname">\
              <tr align="center" valign="bottom">\
                <td width="180" height="34" align="left" style="border-bottom:solid 1px #ffffff "><strong>Name</strong></td>\
                <td width="100" height="34" align="left" style="border-bottom:solid 1px #ffffff "><strong>Color</strong></td>\
                <td width="73" height="34" align="center" style="border-bottom:solid 1px #ffffff "><strong>Quantity</strong></td>\
                <td width="100" height="34" align="center" style="border-bottom:solid 1px #ffffff "><strong>Price</strong></td>\
                <td width="120" style="border-bottom:solid 1px #ffffff ">&nbsp;</td>\
              </tr><tr><td colspan="5" align="center" style="border-bottom:solid 1px #ffffff">Your shopping basket is empty</td></tr></table>';
		spanCpn.innerHTML = '';
	}
		
	createCookie('shoppingbasket',JSON.stringify(SB.basket), 3*60*24);	
}

function removeItem(refnum) {
	SB.basket.removeItem(refnum);
	writeShoppingBasket();
}

function changeItemQty(refnum, newQty) {
	SB.basket.changeQty(refnum, newQty);
	writeShoppingBasket();
}

function emptyBasket() {
	SB.basket.empty();
	writeShoppingBasket();
}

function addItemToBasket(stylenum, colorId, qtyId, name, defaultPrice) {
	
	var qty = document.getElementById(qtyId).value;
	var quantity = parseInt(qty);
	if (quantity > 0) {
		//get color
		var cselect = document.getElementById(colorId);
		var actualColor = cselect.options[cselect.selectedIndex].text;
		var colorCodeAndPrice = cselect.options[cselect.selectedIndex].value;
		var actualPrice;
		if (colorCodeAndPrice.indexOf('_')>=0) {
			var values = colorCodeAndPrice.split('_',2);
			actualPrice = parseInt(values[1]);
			if (!actualPrice)
				actualPrice = defaultPrice;
		} else {
			actualPrice = defaultPrice;
		}
		
		SB.basket.addItem({itemRef: stylenum+actualColor, color: actualColor, qty: quantity, name: name, unitPrice: actualPrice});
		
		createCookie('shoppingbasket',JSON.stringify(SB.basket), 3*60*24);	
	}
}

function readBasketFromCookie() {
	var jsonText = readCookie('shoppingbasket');
	
	if (jsonText != null) {	
		
		var basket = JSON.parse(jsonText);
		SB.basket.coupon = basket.coupon;
		if (basket != null && basket.items != null) {
			for (i=0; i<basket.items.length; i++) {
				SB.basket.addItem(basket.items[i]);
			}
		}	
	}
}

function closeSubmitOrder() {
	changeZIndex('popupSubmitOrder',990,'hidden');
}

function showSubmitOrder() {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		top = (document.documentElement.clientHeight - 480) / 2;
		left = (document.documentElement.clientWidth - 570) / 2;
	}
	else {
		top = (window.innerHeight - 480) / 2;
		left = (window.innerWidth - 570) / 2;
	}
	
	if (top < 10) 
		top = 10;

	var soDiv = document.getElementById('popupSubmitOrder');
	if (soDiv != null) {
		soDiv.style.top = top+'px'; 
		soDiv.style.left = left+'px'; 
	}
	
	changeZIndex('popupSubmitOrder',1001,'visible');
}

function submitOrder(){
	var name = document.getElementById('fullname').value;
	var email = document.getElementById('email').value;
	var streetaddress = document.getElementById('streetaddress').value;
	var city = document.getElementById('city').value;
	var state = document.getElementById('state').value;
	var zip = document.getElementById('zip').value;
	var cS = document.getElementById('country');
    var country = cS.options[cS.selectedIndex].text;
    //var country = document.getElementById('country').value;
	
	if (name != null && name.length > 0 &&
	email != null &&
	email.length > 0 &&
	streetaddress != null &&
	streetaddress.length > 0 &&
	city != null &&
	city.length > 0 &&
	state != null &&
	state.length > 0 &&
	zip != null &&
	zip.length > 0 &&
	country != null &&
	country.length > 0) {
		var errorDiv = document.getElementById('errortd');
		errorDiv.style.color = "green";
		errorDiv.innerHTML = '<strong>Sending order... Please wait...</strong>';
		errorDiv.style.display = "block";
		document.getElementById('errortd').style.display = "block";
		document.getElementById('sbasket').value = JSON.stringify(SB.basket);
		document.getElementById('basketform').submit();
	}
}

function applyCoupon(coupon) {
	SB.basket.addCoupon(coupon);
	writeShoppingBasket();
}

function removeCoupon(){
	SB.basket.removeCoupon();
	writeShoppingBasket();
}

function writeBasketMessage() {
	var msg = getParameter(window.location.href, 'basket');
	var msgDiv = document.getElementById('basketmessage');
	if (msg!=null && msg=='ok') {
		SB.basket.empty();
		msgDiv.innerHTML = 'Your order has beeb successfully submitted. An e-mail has been sent.';
	} else {
		msgDiv.innerHTML = 'There was a problem while submitting your order, please send us an e-mail to info@oneoctober.net.';
	}
	if (msg!='null')
	 	msgDiv.style.display='block';
	else
		msgDiv.style.display='none';
		
}





