var fromApply = false;
var promoInput, promoApply;
var totalDiscount = 0;

function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function submitThisForm(thisurl) {
	//jQuery(document.forms.cart).append('<input type="hidden" value="" name="redirect" />');
	
	document.forms['cart'].elements['redirect'].value = thisurl;
	document.forms['cart'].submit();
}

var cookieValue = '';

function checkDiscount(couponCode) {
	if(couponCode["error"]) {
		jQuery(promoInput).removeAttr('disabled');
		jQuery(promoInput).val('Enter Coupon Code');
		deleteCookie('scPromoCode');
		alert(couponCode["error"]);
	} else {
		if(fromApply || !getCookie('scPromoCode')) {
			setCookie('scPromoCode',couponCode["code"]);
			document.location.href =   '/s.nl/sc.3/.f?promocode=' + couponCode["code"];
        	return;
        }
		
		jQuery(promoInput).val(couponCode["code"] + ' Applied');
		jQuery(promoApply).css('display','none');
		if(!document.getElementById('youSaveText')) {
			jQuery('#promoCodeBox').append('<span id="youSaveText" class="youSaveText">You save ' + ((couponCode['rate'].indexOf('%')==-1)?'$':'') + ((couponCode['rate'].indexOf('%')!=-1)?parseFloat(couponCode['rate'].replace('%','')).toFixed(0):parseFloat(couponCode['rate'].replace('$','')).toFixed(2)) + ((couponCode['rate'].indexOf('%')!=-1)?'%':'') + '</span>');
		}
		// Create discount rows
		var itemsrowsincart = getElementByIdLike('carttablerow','tr');
		var itemsKayakRowsInCart = new Array();

		var tempRows = new Array();
		
		for(var ir = 0; ir < itemsrowsincart.length; ir++) {
			var addThis = true;
			jQuery(itemsrowsincart[ir]).find('a').each(function() {
				if(jQuery(this).html().indexOf('remove') == -1) {
					if(excludeItems.length > 0) {
						for(var ak = 0; ak < excludeItems.length; ak++) {
							if(jQuery(this).attr('href').indexOf('id.') != -1) {
								if('id.' + excludeItems[ak] == jQuery(this).attr('href').match('id.[0-9]*')[0]) {
									addThis = false;
									break;
								}
							}
						}
						if(addThis) {
							tempRows.push(jQuery(this).parent().parent());
						}
					} else {
						tempRows = itemsrowsincart;
					}
				}
			});
		}
		
		var theDiscount = 0;
		var totalDiscount = 0;
		var isFlat = false;
		for(var it in tempRows) {
			if(couponCode['rate'].indexOf('%') != -1) {
				var rateDiscount = parseFloat(couponCode['rate'].replace('%',''));
				theDiscount = jQuery(jQuery(tempRows[it]).children()[jQuery(tempRows[it]).children().length-1]).html()
				
				//theDiscount = theDiscount.replace('.','[dot]');
				while(theDiscount.indexOf(',') != -1) {
					theDiscount = theDiscount.replace(',','');
				}
				//theDiscount = theDiscount.replace('[dot]',',');
				theDiscount = theDiscount.replace('$','');
				
				theDiscount = ((!isNaN(parseFloat(theDiscount)))?parseFloat(theDiscount):0);
				
				totalDiscount += theDiscount;
				
				theDiscount = '$' + theDiscount.toFixed(2);
			} else {
				isFlat = true;
				totalDiscount = parseFloat(couponCode['rate']);
				theDiscount = '$' + couponCode['rate'];
			}
		}
		
		totalDiscount = (totalDiscount>0)?((totalDiscount * rateDiscount) / 100):0;
		
		if(!document.getElementById('cartDiscount')) {
			jQuery(itemsrowsincart[itemsrowsincart.length - 1]).after('<tr id="cartDiscount" class="discountRow"><td class="disc texttable">&nbsp;</td><td class="disc texttable">&nbsp;</td><td class="disc texttable">&nbsp;</td><td class="disc texttable">&nbsp;</td><td class="disc texttable">&nbsp;</td><td class="disc texttablert"><b>Discount</b></td><td class="disc texttablert" id="ctm_discount"><b>$-' + addCommas(totalDiscount.toFixed(2).toString()) + '</b></td>');
		}
		totalDiscount = totalDiscount.toFixed(2);
		
		var cartTotal = jQuery('#total_id');
		if(cartTotal) cartTotal = jQuery(cartTotal).html();
		cartTotal = cartTotal.replace('(','').replace(')','');
		
		//cartTotal = cartTotal.replace('.','[dot]');
		while(cartTotal.indexOf(',') != -1) {
			cartTotal = cartTotal.replace(',','');
		}
		//cartTotal = cartTotal.replace('[dot]',',');
		
		cartTotal = parseFloat(cartTotal.replace('$',''));
		cartTotal = cartTotal - totalDiscount;
		var totalRow = jQuery('#carttable>tbody>tr:last');
		//jQuery(totalRow).remove();
		jQuery(totalRow).css('display','none');
		
		//var newRowTotal = '<tr><td class="texttable">&nbsp;</td><td class="texttable">&nbsp;</td><td class="texttable">&nbsp;</td><td class="texttable">&nbsp;</td><td class="texttable">&nbsp;</td><td class="texttablert"><b>Total</b></td><td class="texttablert" id="ctm_carttotal"><b>$' + addCommas(cartTotal.toFixed(2).toString()) + '</b></td>';
		var newRowTotal = '<tr><td class="texttable" colspan="3"><b>Items will remain in your cart for 7 days</b></td><td class="texttable">&nbsp;</td><td class="texttable">&nbsp;</td><td class="texttablert"><b>Total</b></td><td class="texttablert" id="ctm_carttotal"><b>$' + addCommas(cartTotal.toFixed(2).toString()) + '</b></td>';
	
		jQuery('#carttable>tbody').append(newRowTotal);
	}
}

//checkDiscount( { "code": "15OFF", "rate": "15.00%", "expires": "Wed Jan 27 2010 11:06:35 GMT-0800 (PST)" } )

function checkForGiftwrap() {
	var inremove_itemsLinks = new Array();
	var giftWrapExist = false;
	var removeGiftWrap = true;
	var kayaksAmount = 0;
	var giftWrapAmount = 0;
	
	var kayaksRows = new Array();
	
	// ITER IN ALL LINKS FROM CART
	jQuery('td > a').each(function() {
		// IF HREF OF CURRENT LINK HAVE id. STRING, THEN IS AN ITEM LINK
		if(jQuery(this).attr('href').indexOf('id.') != -1) {
			inremove_itemsLinks.push(jQuery(this)[0]);
		}
		// IF HREF OF CURRENT LINK HAVE id.4099 STRING, THEN THE GIFT WRAP EXIST
		if(jQuery(this).attr('href').indexOf('id.4099') != -1) {
			giftWrapExist = true;
		}
	});
 
	// ITER IN ALL ITEM LINKS
	for(var i = 0; i < inremove_itemsLinks.length; i++) {
		// ITER IN ALL KAYAKSINCART ARRAY
		for(var k = 0; k < kayaksInCart.length; k++) {
			// IF HREF FROM CURRENT LINK HAVE id. + kayaksInCart[k] THEN THIS CURRENT ITEM IS A KAYAK AND I DON'T HAVE TO REMOVE THE GIFTWRAP
			if(jQuery(inremove_itemsLinks[i]).attr('href').indexOf('id.' + kayaksInCart[k]) != -1) {
				kayaksRows.push(jQuery(inremove_itemsLinks[i]).parent().parent().find('input[type=text]:first'));
				kayaksAmount += parseFloat(jQuery(inremove_itemsLinks[i]).parent().parent().find('input[type=text]:first').val());
				removeGiftWrap = false;
			}
		}
	}
	
	// IF REMOVEGIFTWRAP IS TRUE, AND GIFTWRAPEXIST IS TRUE, I HAVE TO REMOVE THIS
	if(removeGiftWrap && giftWrapExist) {
		jQuery('#carttable td').each(function() {
			if(jQuery(this).html().indexOf('Boat Wrapping Charge') != -1) {
				jQuery(this).parent().find('td').each(function() {
					if(jQuery(this).find('input[type=text]').length > 0) {
						giftWrapAmount = jQuery(this).find('input[type=text]').val();
					}
				});
			}
		});
		document.location.href = '/app/site/backend/additemtocart.nl?buyid=4099&qty=-' + giftWrapAmount + '&c=436469';
	} else if(giftWrapExist) {
		jQuery('#carttable td').each(function() {
			if(jQuery(this).html().indexOf('Boat Wrapping Charge') != -1) {
				jQuery(this).parent().find('td').each(function() {
					if(jQuery(this).find('input[type=text]').length > 0) {
						giftWrapAmount = jQuery(this).find('input[type=text]').val();
					}
				});
			}
		});
		
		if(parseFloat(giftWrapAmount) > parseFloat(kayaksAmount)) {
			document.location.href = '/app/site/backend/additemtocart.nl?buyid=4099&qty=-' + (parseFloat(giftWrapAmount) - parseFloat(kayaksAmount)) + '&c=436469';
		} else if(parseFloat(giftWrapAmount) < parseFloat(kayaksAmount)) {
			document.location.href = '/app/site/backend/additemtocart.nl?buyid=4099&qty=' + (parseFloat(kayaksAmount) - parseFloat(giftWrapAmount)) + '&c=436469';
		} else {
			return;
		}
	}
}

function validateCode() {
	var executeScript = document.createElement('script');
		executeScript.setAttribute('src','/app/site/hosting/scriptlet.nl?script=27&deploy=1&code=' + getCookie('scPromoCode'));
	jQuery('head').append(executeScript);
	
	setCookie('scPromoCode2',getCookie('scPromoCode'));
}

if(document.location.href.indexOf('checkout') == -1) {
	if(document.getElementById('carttable')) {
		jQuery(document).ready(function() {
			
			// Delete the free ups shipping row
			jQuery('#carttable tr').each(function() {
			    if(jQuery(this).html().indexOf('Free Shipping') != -1 && jQuery(this).html().indexOf('(UPS Ground)') != -1) jQuery(this).hide();
			});
			
			var cartTotal = jQuery('#total_id');
			if(cartTotal.length > 0) cartTotal = jQuery(cartTotal).html();
			cartTotal = cartTotal.replace('(','').replace(')','');
			//cartTotal = cartTotal.replace('.','[dot]');
			while(cartTotal.indexOf(',') != -1) {
				cartTotal = cartTotal.replace(',','');
			}
			//cartTotal = cartTotal.replace('[dot]',',');
			
			cartTotal = parseFloat(cartTotal.replace('$',''));
			cartTotal = cartTotal - totalDiscount;
				
			// Change rows in cart
			//jQuery('#carttable tbody tr:last').prev().remove();
			var colsNum = jQuery('#carttable>tbody>tr:last').children().length;
			if(!document.getElementById('subtotalsRow')) {
				var newRowSubtotals = '<tr id="subtotalsRow"><td colspan="' + (colsNum - 1) + '" class="txttitles"><div><b>Sub-Total</b></div><div><b>Free Shipping</b></div><div><b>No Sales Tax</b></div></td><td class="txtamounts"><div><b>$' + addCommas(cartTotal.toFixed(2).toString()) + '</b></div><div><b>$0</b></div><div><b>$0</b></div></td></tr>';
				//var newRowTotal = '<tr><td class="texttable">&nbsp;</td><td class="texttable">&nbsp;</td><td class="texttable">&nbsp;</td><td class="texttable">&nbsp;</td><td class="texttable">&nbsp;</td><td class="texttablert"><b>Total</b></td><td class="texttablert" id="ctm_carttotal"><b>$' + addCommas(cartTotal.toFixed(2).toString()) + '</b></td>';
				var newRowTotal = '<tr><td class="texttable" colspan="3"><b>Items will remain in your cart for 7 days</b></td><td class="texttable">&nbsp;</td><td class="texttable">&nbsp;</td><td class="texttablert"><b>Total</b></td><td class="texttablert" id="ctm_carttotal"><b>$' + addCommas(cartTotal.toFixed(2).toString()) + '</b></td>';
				
				var totalRow = jQuery('#carttable>tbody>tr:last');
				//jQuery(totalRow).prev().hide();
				
				//jQuery(totalRow).remove();
				jQuery(totalRow).css('display','none');
				if(jQuery('#carttable>tbody>tr:last').prev().length > 0) {
					if(jQuery('#carttable>tbody>tr:last').prev().html().indexOf('Estimated Shipping') != -1) {
						jQuery('#carttable>tbody>tr:last').prev().css('display','none');
					}
				}
				
				jQuery('#carttable>tbody').append(newRowSubtotals + newRowTotal);
				//jQuery('#carttable tbody').append(totalRow);
			}
			
			if(isOpMember != "Yes") {
				var promoCodeRow = '<div id="promocodeRow"><span id="promoCodeBox"><input type="text" value="Enter Coupon Code" id="promoCodeInput" /><a href="javascript:;" id="applyButton">Apply</a></span></div>';
				if(!document.getElementById('promocodeRow')) {
					jQuery('#carttable').parent().append(promoCodeRow)
					jQuery('#promoCodeBox').before(jQuery("#couponLinksId"));
					jQuery("#couponLinksId").css('display','inline');
				}
			
				promoInput = jQuery('#promoCodeInput');
				jQuery(promoInput).focus(function() {
					if(jQuery(this).val() == '' || jQuery(this).val() == ' ' || jQuery(this).val() == '  ' || jQuery(this).val() == '   ' || jQuery(this).val() == 'Enter Coupon Code') {
						jQuery(this).val('');
					}
				});
				jQuery(promoInput).blur(function() {
					if(jQuery(this).val() == '' || jQuery(this).val() == ' ' || jQuery(this).val() == '  ' || jQuery(this).val() == '   ') {
						jQuery(this).val('Enter Coupon Code');
					}
				});
				
				//if(getCookie('sc_promocode')) {
				if(getCookie('scPromoCode') || getCookie('promocode')) {
					setCookie('scPromoCode',getCookie('promocode'));
					promoApply = jQuery('#applyButton');
					jQuery(promoInput).val('Loading Coupon Code...');
					jQuery(promoInput).attr('disabled','true');
					
					var itemsString = '';
					
					//inremove_itemsLinks = new Array();
	
					jQuery('td > a').each(function() {
						if(jQuery(this).attr('href').indexOf('id.') != -1) {
							//inremove_itemsLinks.push(jQuery(jQuery(this)[0]).attr('href').match('id.[0-9]*')[0].replace('id.',''));
							itemsString += ',' + jQuery(jQuery(this)[0]).attr('href').match('id.[0-9]*')[0].replace('id.','');
						}
					})
	
					var executeScript = document.createElement('script');
					//executeScript.setAttribute('src','/app/site/hosting/scriptlet.nl?script=27&deploy=1&code=' + getCookie('sc_promocode'));
					executeScript.setAttribute('src','/app/site/hosting/scriptlet.nl?script=31&deploy=1&items=' + itemsString);
					jQuery('head').append(executeScript);
					
		   			
				} else {
					promoApply = jQuery('#applyButton');
					jQuery(promoApply).click(function() {
						fromApply = true;
						//setCookie('sc_promocode','bce-1000');
						setCookie('scPromoCode',jQuery(promoInput).val());
						
						if(jQuery(promoInput).val() != 'Enter Coupon Code') {
							//var promoCode = 'bce-1000';
							var promoCode = jQuery(promoInput).val();
							jQuery(promoInput).val('Loading Coupon Code...');
							jQuery(promoInput).attr('disabled','true');
							
							var itemsString = '';
							
							jQuery('td > a').each(function() {
								if(jQuery(this).attr('href').indexOf('id.') != -1) {
									//inremove_itemsLinks.push(jQuery(jQuery(this)[0]).attr('href').match('id.[0-9]*')[0].replace('id.',''));
									itemsString += ',' + jQuery(jQuery(this)[0]).attr('href').match('id.[0-9]*')[0].replace('id.','');
								}
							})
			
							//inremove_itemsLinks
							var executeScript = document.createElement('script');
								//executeScript.setAttribute('src','/app/site/hosting/scriptlet.nl?script=27&deploy=1&code=' + getCookie('sc_promocode'));
								executeScript.setAttribute('src','/app/site/hosting/scriptlet.nl?script=31&deploy=1&items=' + itemsString);
							jQuery('head').append(executeScript);
						} else {
							alert('Enter Coupon Code');
						}
					});
				}
			}
			jQuery('#carttable td').each(function() {
				if(jQuery(this).html().indexOf('Boat Wrapping Charge') != -1) {
					jQuery(this).find('a:first').css("display",'none');
					jQuery(this).append('<span style="padding: 5px">' + jQuery(this).find('a').html() + '</span>');
					jQuery(this).append('<span id="moreinfo_boatwrappinglink"></span>');
					jQuery('#moreinfo_boatwrap>a').appendTo(jQuery('#moreinfo_boatwrappinglink'));
					jQuery(this).parent().find('td').each(function() {
						if(jQuery(this).html().indexOf('remove') != -1) {
							jQuery(this).html('&nbsp;');
						}
						if(jQuery(this).find('input[type=text]').length > 0) {
							jQuery(this).find('input[type=text]').attr('disabled','true');
						}
					});
				}
			});
	
			setPopupModal('.lg_link');
			
			if(document.all) {
				var itemsString = '';
					
				//inremove_itemsLinks = new Array();

				jQuery('td > a').each(function() {
					if(jQuery(this).attr('href').indexOf('id.') != -1) {
						//inremove_itemsLinks.push(jQuery(jQuery(this)[0]).attr('href').match('id.[0-9]*')[0].replace('id.',''));
						itemsString += ',' + jQuery(jQuery(this)[0]).attr('href').match('id.[0-9]*')[0].replace('id.','');
					}
				})

				var executeScript = document.createElement('script');
				//executeScript.setAttribute('src','/app/site/hosting/scriptlet.nl?script=27&deploy=1&code=' + getCookie('sc_promocode'));
				executeScript.setAttribute('src','/app/site/hosting/scriptlet.nl?script=31&deploy=1&items=' + itemsString);
				jQuery('head').append(executeScript);
			}
		})
	}
}